【问题标题】:getJSON returns null MVC3 - 4getJSON 返回 null MVC3 - 4
【发布时间】:2012-12-09 12:28:51
【问题描述】:

所以,我在从我的操作中获取 json 时遇到问题,希望有人能指出我的错误。

所以,这是我的 jQuery:

$("#ProductSelect").change(function () {
    $.getJSON('Admin/GetProduct?id=' + $(this).val(), function (data) {
        var json = $.parseJSON(data);
        alert(json);
    });
});

这是它调用的动作:

[HttpGet]
    public JsonResult GetProduct(int id)
    {
        var product = new Product();
        product.GetProductById(id);
        return this.Json(product, JsonRequestBehavior.AllowGet);
    }

JS中的alert一直显示为null。没有 JS 错误(使用 Firebug)。在 Action 上使用断点,我可以看到 Product 已正确填充。有什么想法吗?

【问题讨论】:

  • 你的 json 是什么样的?复制/粘贴示例...
  • 这就是问题所在。我在这里关注这个例子:geekswithblogs.net/michelotti/archive/2008/06/28/…,我的印象是 this.Json() 为你创建了 JSON。所以,我刚刚在 Product 中创建了一个 ToJSON() 方法,它现在可以工作了。谢谢,Xander。

标签: asp.net-mvc-3 jquery asp.net-mvc-4 getjson


【解决方案1】:

显然你的控制器使用了一个刚刚初始化的对象,没有任何信息。您是否忘记使用数据库对象然后找到该 id 作为主键?像这样:

[HttpGet]
    public JsonResult GetProduct(int id)
    {
        //private DataContext db
        return Json(db.GetProductById(id), JsonRequestBehavior.AllowGet);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2012-04-01
    • 2011-01-26
    相关资源
    最近更新 更多