从Ajax调用传递响应,以查看C# [英] Passing response from ajax call to view in C#

查看:118
本文介绍了从Ajax调用传递响应,以查看C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX调用控制器的操作。在code是这样

  $('#厨房')。改变(函数(){
    。VAR selectedKitchen = $('#厨房)VAL();
    如果(selectedKitchen!=''){
        的console.log(选择的项目:+ $('#厨房)VAL());
        $阿贾克斯({
            键入:GET,
            网址:/首页/ GiveInsitutionsWithoutResponsibility
            数据:ID =+ selectedKitchen,
            数据类型:JSON,
            成功:函数(结果){
                结果= JSON.parse(结果);
                执行console.log(result.length);
            },
            错误:功能(错误){
                的console.log(发生错误张贴数据到服务器:);
                执行console.log(error.responseText);
            }
        });
    }

});
 

现在我要的是使用的结果从服务器来填充下拉在客户端。我应该怎么办呢?有没有办法为它还是我的方法在这里是错的?

我的结果对象是这样的

  {
编号:04409314-ea61-4367-8eee-2b5faf87e592
产品名称:检测机构二
NextPatientId:1
OWNERID:1
PartitionKey:1
RowKey:04409314-ea61-4367-8eee-2b5faf87e592
时间戳:/日(1417180677580)/
}
 

该控制器的功能是这样的

 公众的ActionResult GiveInsitutionsWithoutResponsibility()
    {
        VAR kitchenId =请求[ID]的ToString()。
        厨房K = Kitchen.Get(kitchenId);
        IEnumerable的<机构>插件= k.GetInstitutions();
        IEnumerable的<机构> allIns = Institution.GetAll();
        名单<机构>结果=新名单,其中,机构>();
        布尔包含= TRUE;
        INT索引= 0;
        如果(ins.Count()大于0)
        {
            的for(int i = 0; I< allIns.Count();我++,包含= TRUE)
            {
                对于(INT J = 0; J< ins.Count(); J ++)
                {
                    如果(allIns.ElementAt(我).ID == ins.ElementAt(J).ID)
                    {
                        含有= TRUE;
                        打破;
                    }
                    其他
                    {
                        指数= j的;
                        含有= FALSE;
                    }
                }
                如果(!含)
                {
                    result.Add(allIns.ElementAt(指数));
                }
            }
        }
        其他
        {
            的for(int i = 0; I< allIns.Count();我++)
            {
                result.Add(allIns.ElementAt(指数));
            }
        }
        字符串响应=新System.Web.Script.Serialization.JavaScriptSerializer()序列化(结果)。
        返回JSON(响应,JsonRequestBehavior.AllowGet);

    }
 

解决方案

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

 公众的ActionResult GiveInsitutionsWithoutResponsibility(INT ID)
{
  厨房K = Kitchen.Get(ID);
  。VAR数据= Institution.GetAll()除(k.GetInstitutions(),新InstitutionComparer())选择(I =>新
  {
    ID = i.ID,
    NAME = r.Name
  });
  返回JSON(数据,JsonRequestBehavior.AllowGet);
}
 

注意 Kitchen.ID 传入的方法参数。 LINQ查询用来选择所有机构的再排除任何机构的已经在<$存在C $ C>厨房,然后创建匿名对象,以便不必要的数据收集不发送给客户端。该 JSON()方法返回正确的JSON格式的数据(调用 JavaScriptSerializer()。序列化()不需要)。

为了对。除()复杂的对象,它需要一个比较器

 公共类InstitutionComparer:的IEqualityComparer&LT;机构&GT;
{
  公共布尔等于(机构X,机构Y)
  {
    如果(Object.ReferenceEquals(X,Y))
    {
      返回true;
    }
    如果(Object.ReferenceEquals(X,NULL)|| Object.ReferenceEquals(Y,NULL))
    {
        返回false;
    }
    返回x.ID == y.ID;
  }
  公众诠释GetHash code(机构单位)
  {
    如果(Object.ReferenceEquals(机构,NULL))
    {
      返回0;
    }
    返回institution.ID.GetHash code();
  }
}
 

接下来改变AJAX方法

  $('#厨房')。改变(函数(){
  。VAR selectedKitchen = $('#厨房)VAL();
  如果(!selectedKitchen){
    返回;
  }
  $阿贾克斯({
    键入:GET,
    网址:@ Url.Action(GiveInsitutionsWithoutResponsibility,家)',//不要硬code网址
    数据:{ID:selectedKitchen} //传递selectedKitchen的id参数
    数据类型:JSON,
    成功:函数(结果){
      。VAR选择= $('YourDropDownSelector')空()追加($('&LT;选项&GT;&LT; /选项&GT;')VAL('')文本( - 请选择 - '));
      $每个(结果,函数(指数,项目){
        select.append($('&LT;选项&GT;&LT; /选项&GT;')。VAL(item.ID)的.text(item.Name));
      });
    },
    错误:功能(错误){
    }
  });
});
 

或者你也可以使用快捷

  $的getJSON('@ Url.Action(GiveInsitutionsWithoutResponsibility,家)',{ID:selectedKitchen},功能(结果){
  $每个(结果....如上//
});
 

I am using ajax to call an action in the controller. The code is like this

   $('#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);
            }
        });
    }

});

Now what I want is to use the result coming from the server to populate a drop down on the client side. How should I do it? Is there a way for it or my approach here is wrong?

My result object is like this

{
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)/"
}

The controller function is like this

    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);

    }

解决方案

First your action method can be simplified to

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);
}

Note the Kitchen.ID is passed in the method parameter. The Linq query is used to select all Institution's then exclude any Institution's that already exist in the Kitchen, then creates a collections of anonymous object so unnecessary data is not sent to the client. The Json() method returns the data in the correct JSON format (calling JavaScriptSerializer().Serialize() is not required).

In order for .Except() to work with complex objects, you need a comparer

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();
  }
}

Next change the ajax method to

$('#kitchen').change(function () {     
  var selectedKitchen = $('#kitchen').val();
  if (!selectedKitchen) {
    return;
  }
  $.ajax({
    type: "GET",
    url: '@Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', // don't hard code urls
    data: { id: selectedKitchen }, // pass selectedKitchen to the id parameter
    dataType:'json',
    success: function (result) {
      var select = $('YourDropDownSelector').empty().append($('<option></option>').val('').text('--Please select--'));
      $.each(result, function(index, item) {
        select.append($('<option></option>').val(item.ID).text(item.Name));
      });
    },
    error: function (error) {
    }
  });
});

or you could use the short cut

$.getJSON('@Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', { id: selectedKitchen }, function(result) {
  $.each(result, .... // as above
});

这篇关于从Ajax调用传递响应,以查看C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆