Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中将ajax调用的响应传递给视图#_C#_Jquery_Ajax_Asp.net Mvc_Razor - Fatal编程技术网

C# 在C中将ajax调用的响应传递给视图#

C# 在C中将ajax调用的响应传递给视图#,c#,jquery,ajax,asp.net-mvc,razor,C#,Jquery,Ajax,Asp.net Mvc,Razor,我正在使用ajax调用控制器中的操作。代码是这样的 $('#kitchen').change(function () { var selectedKitchen = $('#kitchen').val(); if (selectedKitchen != '') { console.log("selected item:" + $('#kitchen').val()); $.ajax({ type: "GET",

我正在使用ajax调用控制器中的操作。代码是这样的

   $('#kitchen').change(function () {
    var selectedKitchen = $('#kitchen').val();
    if (selectedKitchen != '') {
        console.log("selected item:" + $('#kitchen').val());
        $.ajax({
            type: "GET",
            url: "/Home/GiveInsitutionsWithoutResponsibility",
            data: "id=" + selectedKitchen,
            dataType:'json',
            success: function (result) {
                result = JSON.parse(result);
                console.log(result.length);
            },
            error: function (error) {
                console.log("There was an error posting the data to the server: ");
                console.log(error.responseText);
            }
        });
    }

});
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
    public ActionResult GiveInsitutionsWithoutResponsibility()
    {
        var kitchenId = Request["id"].ToString();
        Kitchen k = Kitchen.Get(kitchenId);
        IEnumerable <Institution> ins = k.GetInstitutions();
        IEnumerable<Institution> allIns = Institution.GetAll();
        List<Institution> result = new List<Institution>();
        bool contain = true;
        int index = 0;
        if (ins.Count() > 0)
        {
            for (int i = 0; i < allIns.Count(); i++, contain = true)
            {
                for (int j = 0; j < ins.Count(); j++)
                {
                    if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
                    {
                        contain = true;
                        break;
                    }
                    else
                    {
                        index = j;
                        contain = false;
                    }
                }
                if (!contain)
                {
                    result.Add(allIns.ElementAt(index));
                }
            }
        }
        else
        {
            for (int i = 0; i < allIns.Count(); i++)
            {
                result.Add(allIns.ElementAt(index));
            }
        }
        string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
        return Json(response, JsonRequestBehavior.AllowGet);

    }
现在我想要的是使用来自服务器的结果来填充客户端的下拉列表。我该怎么做?有没有办法,或者我的方法不对

我的结果对象是这样的

   $('#kitchen').change(function () {
    var selectedKitchen = $('#kitchen').val();
    if (selectedKitchen != '') {
        console.log("selected item:" + $('#kitchen').val());
        $.ajax({
            type: "GET",
            url: "/Home/GiveInsitutionsWithoutResponsibility",
            data: "id=" + selectedKitchen,
            dataType:'json',
            success: function (result) {
                result = JSON.parse(result);
                console.log(result.length);
            },
            error: function (error) {
                console.log("There was an error posting the data to the server: ");
                console.log(error.responseText);
            }
        });
    }

});
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
    public ActionResult GiveInsitutionsWithoutResponsibility()
    {
        var kitchenId = Request["id"].ToString();
        Kitchen k = Kitchen.Get(kitchenId);
        IEnumerable <Institution> ins = k.GetInstitutions();
        IEnumerable<Institution> allIns = Institution.GetAll();
        List<Institution> result = new List<Institution>();
        bool contain = true;
        int index = 0;
        if (ins.Count() > 0)
        {
            for (int i = 0; i < allIns.Count(); i++, contain = true)
            {
                for (int j = 0; j < ins.Count(); j++)
                {
                    if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
                    {
                        contain = true;
                        break;
                    }
                    else
                    {
                        index = j;
                        contain = false;
                    }
                }
                if (!contain)
                {
                    result.Add(allIns.ElementAt(index));
                }
            }
        }
        else
        {
            for (int i = 0; i < allIns.Count(); i++)
            {
                result.Add(allIns.ElementAt(index));
            }
        }
        string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
        return Json(response, JsonRequestBehavior.AllowGet);

    }
控制器的功能如下

   $('#kitchen').change(function () {
    var selectedKitchen = $('#kitchen').val();
    if (selectedKitchen != '') {
        console.log("selected item:" + $('#kitchen').val());
        $.ajax({
            type: "GET",
            url: "/Home/GiveInsitutionsWithoutResponsibility",
            data: "id=" + selectedKitchen,
            dataType:'json',
            success: function (result) {
                result = JSON.parse(result);
                console.log(result.length);
            },
            error: function (error) {
                console.log("There was an error posting the data to the server: ");
                console.log(error.responseText);
            }
        });
    }

});
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
    public ActionResult GiveInsitutionsWithoutResponsibility()
    {
        var kitchenId = Request["id"].ToString();
        Kitchen k = Kitchen.Get(kitchenId);
        IEnumerable <Institution> ins = k.GetInstitutions();
        IEnumerable<Institution> allIns = Institution.GetAll();
        List<Institution> result = new List<Institution>();
        bool contain = true;
        int index = 0;
        if (ins.Count() > 0)
        {
            for (int i = 0; i < allIns.Count(); i++, contain = true)
            {
                for (int j = 0; j < ins.Count(); j++)
                {
                    if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
                    {
                        contain = true;
                        break;
                    }
                    else
                    {
                        index = j;
                        contain = false;
                    }
                }
                if (!contain)
                {
                    result.Add(allIns.ElementAt(index));
                }
            }
        }
        else
        {
            for (int i = 0; i < allIns.Count(); i++)
            {
                result.Add(allIns.ElementAt(index));
            }
        }
        string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
        return Json(response, JsonRequestBehavior.AllowGet);

    }
公共行动结果无责任机构()
{
var kitchenId=Request[“id”].ToString();
Kitchen k=Kitchen.Get(kitchenId);
IEnumerable ins=k.GetInstitutions();
IEnumerable allIns=Institution.GetAll();
列表结果=新列表();
bool-contain=true;
int指数=0;
如果(ins.Count()>0)
{
for(int i=0;i
您的方法很好,您必须格式化要添加到组合框中的结果。例如,在“我有国家和州”组合框的页面上提供支持。根据所选国家,我需要填充州,因此我将编写以下代码:

    $("#billingContactCountry").change(function (e) {
        e.preventDefault();

        var countryId = $("#billingContactCountry").val();

        getStatesByCountry(countryId, "", "#billingContactState", "#billingContactZip");
    });

    function getStatesByCountry(countryId, stateId, stateCombobox, zipTextBox) {

    $.ajax({
        url: "@Url.Action("GetStatesByCountry", "Admin")",
        data: { countryId: countryId },
        dataType: "json",
        type: "GET",
        error: function (xhr, status) {
            //debugger;
            var items = "<option value=\"\">-Select State-</option>";
            $(stateCombobox).html(items);

            var zipMessage = validateZip(countryId, $(zipTextBox).val());
            if (zipMessage != "The ZIP Code field is required.") {
                $(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
            }

            $("div.overlay").hide();
        },
        success: function (data) {
            //debugger;
            var items = "<option value=\"\">-Select State-</option>";
            $.each(data, function (i, item) {
                items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
            });

            $(stateCombobox).html(items);

            if (stateId != "") {
                $('#billingContactState').val(stateId);
            }

            var zipMessage = validateZip(countryId, $(zipTextBox).val());
            if (zipMessage != "The ZIP Code field is required.") {
                $(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
            }

            $("div.overlay").hide();
        }
    });
}
$(“#billingContactCountry”).更改(功能(e){
e、 预防默认值();
var countryId=$(“#billingContactCountry”).val();
getStatesByCountry(countryId“,”billingContactState“,”billingContactZip”);
});
函数getStatesByCountry(countryId、stateId、stateCombobox、zipTextBox){
$.ajax({
url:“@url.Action(“GetStatesByCountry”、“Admin”)”,
数据:{countryId:countryId},
数据类型:“json”,
键入:“获取”,
错误:函数(xhr,状态){
//调试器;
var items=“-选择状态-”;
$(stateCombobox).html(项目);
var zipMessage=validateZip(countryId,$(zipTextBox.val());
如果(zipMessage!=“邮政编码字段是必需的。”){
$(zipTextBox).parent().find(“span.field验证错误”).text(zipMessage);
}
$(“div.overlay”).hide();
},
成功:功能(数据){
//调试器;
var items=“-选择状态-”;
$。每个(数据、功能(i、项){
项目+=“”+项目名称+“”;
});
$(stateCombobox).html(项目);
如果(stateId!=“”){
$('billingContactState').val(stateId);
}
var zipMessage=validateZip(countryId,$(zipTextBox.val());
如果(zipMessage!=“邮政编码字段是必需的。”){
$(zipTextBox).parent().find(“span.field验证错误”).text(zipMessage);
}
$(“div.overlay”).hide();
}
});
}
所以最有趣的代码是

            var items = "<option value=\"\">-Select State-</option>";
            $.each(data, function (i, item) {
                items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
            });

            $(stateCombobox).html(items);
var items=“-Select State-”;
$。每个(数据、功能(i、项){
项目+=“”+项目名称+“”;
});
$(stateCombobox).html(项目);
我们正在对服务器返回的每个元素进行操作,以便为组合框创建选项项


另外,您应该使用@Url.Action,如上面的示例所示

根据控制器中的对象,您可以循环查看结果数据并
。将此添加到下拉列表中

success: function (result) {

   $.each(result, function(index, manager) {
       $('select#yourId').append(
               '<option value="' + result.Id + '">'
                    + result.Name + 
       '</option>');
   });

}
成功:函数(结果){
$。每个(结果、功能(索引、管理器){
$('select#yourId')。追加(
''
+结果.名称+
'');
});
}

首先,您的操作方法可以简化为

public ActionResult GiveInsitutionsWithoutResponsibility(int ID)
{
  Kitchen k = Kitchen.Get(ID);
  var data = Institution.GetAll().Except(k.GetInstitutions(), new InstitutionComparer()).Select(i => new
  {
    ID = i.ID,
    Name = r.Name
  });
  return Json(data, JsonRequestBehavior.AllowGet);
}
注意,
Kitchen.ID
在方法参数中传递。Linq查询用于选择所有
机构
,然后排除
厨房
中已经存在的任何
机构
,然后创建一个匿名对象集合,以便不向客户端发送不必要的数据。
Json()
方法以正确的Json格式返回数据(不需要调用
JavaScriptSerializer()。Serialize()

为了使
.Except()
能够处理复杂对象,您需要一个比较器

public class InstitutionComparer : IEqualityComparer<Institution>
{
  public bool Equals(Institution x, Institution y)
  {
    if (Object.ReferenceEquals(x, y)) 
    {
      return true;
    }
    if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
    {
        return false;
    }
    return x.ID == y.ID;
  }
  public int GetHashCode(Institution institution)
  {
    if (Object.ReferenceEquals(institution, null))
    {
      return 0; 
    }
    return institution.ID.GetHashCode();
  }
}

您误用了
数据类型:'json',
,您可以用
$(此)
引用
$('#kitchen')
,这将是一个很好的方法。谢谢。我已经编辑了我的代码,但是对如何使用结果对象有什么建议吗?您的
结果对象到底是什么?你能把它贴出来看看它的结构是什么吗?刚刚编辑了这个问题,里面有答案。似乎是一个无效的对象。特别是在这里查看
ETag:“W/“datetime'2014-11-28813%3A17%3A57.58Z'”
,这是对象中的第一个。我知道这种方法,但我希望ASP.NET MVC能为它做点什么,比如razor会为它提供一些功能。@mohsinali1317-很高兴你知道这种方法。为什么不在你的问题中加上你“希望”的解决方案。我知道这种方法,但我希望ASP.NET MVC有一些功能,比如razor会有一些功能。啊,对不起,伙计!我并没有立即意识到剃须刀已经内置了一些东西,但你可以