【问题标题】:cannot call json result using jquery无法使用 jquery 调用 json 结果
【发布时间】:2014-10-27 06:20:33
【问题描述】:

c# 和 jquery,

我有两个下拉列表(类别和产品),并且必须根据类别更改产品列表。

  @Html.DropDownList("categoryId", new SelectList(ViewBag.Category, "Id", "Name"), "Select Parent Category", new { @class = "form-control categorydata" })      
  @Html.DropDownList("productId", new SelectList(ViewBag.Product, "Id", "Name"), "Select Product", new { @class = "form-control product-list" })      

我正在编写以下控制器来获取产品列表。它工作正常。

    [HttpGet]
    public JsonResult GetProducts(int categoryId)
    {
        int tot = new Products().Total;
        int cont = 1;
        Category cat = new Category(2);
        var products = new Products(cont, tot, cat);
       // ViewBag.products = new Products(1,new Products().Total,new Category(categoryId));
        return Json(products);
    }

我的 jquery 是,

$('.categorydata').change(function () {
    var selCat = $(".categorydata").val();
    var url = "~/Add/GetProducts";   
    if (selCat.length != 0) {           
        $.get(url, { id: SelCat }, function (data) {
            alert(data);
        });
    }       
});

这个jquery没有调用控制器,无法获取数据。

请帮我解决。

【问题讨论】:

  • 使用@Url.Action("ActionName", "Controller") 代替"~/Add/GetProducts" 并且也代替$.get 使用$.getJSON
  • 您应该将dataType 设置为json。
  • 你不认为SelCat 应该是selCat 吗??

标签: javascript c# jquery json asp.net-mvc-4


【解决方案1】:

你应该保持json数据中的属性名称与动作方法的参数名称相同。

$.get(url, { categoryId : SelCat }, function (data) {

请参阅SO Post

【讨论】:

    【解决方案2】:

    你应该使用它。

    return Json(products,System.Web.Mvc.JsonRequestBehavior.AllowGet);

    【讨论】:

    • 但是 jquery 从不调用控制器动作
    • 你使用了 HttpGet 属性,所以你应该使用 JsonRequestBehavior.AllowGet 枚举。
    【解决方案3】:

    尝试将 dataType: 'json' 放入 ajax 调用中:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 2012-01-19
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多