asp.net-mvc - jQuery.parseJSON 不适用于 MVC Controller 操作中的 JsonResult

标签 asp.net-mvc json asp.net-mvc-3 jquery

我正在尝试使用 jQuery.parseJSON 解析 MVC3 Controller 操作的返回值。

Controller :

    [HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        .. do stuff ..

        if (errors.Count() < 0)
        {
            return Json(new object[] { true, model, errors });

        }

        return Json(new object[] { false, model, errors });
    }

jQuery:

$.ajax({
                url: form.attr('action'),
                type: "POST",
                dataType: "json",
                data: form.serialize(),
                success: function (data) {
                    var test = jQuery.parseJSON(data);                      
                }   
            });

来自 fiddler 的 Json 结果:

Content-Type: application/json; charset=utf-8

[false,{"UserName":"1","Password":"2","RememberMe":false},[{"Key":"","Errors":[{"Exception":null,"ErrorMessage":"The user name or password provided is incorrect."}]}]]

Fiddler可以解析结果:

enter image description here

对 jQuery.parseJSON 的调用返回 null。 我的问题是,如何将 json 返回值解析为对象?

谢谢!

最佳答案

您不需要在成功处理程序中调用 parseJSON,因为 ajax 已经解析了 JSON 结果(它会自动执行此操作,因为您指定了 dataType:'json' code>) 到你的数组中。

但是,我建议返回某种结果对象(无论您在 C# 中创建实际的类还是使用匿名类型)。

    [HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        .. do stuff ..

        if (errors.Count() < 0)
        {
            return Json(new { success=true, model, errors });

        }

        return Json(new { success=false, model, errors });
    }

在客户端

$.ajax({
                url: form.attr('action'),
                type: "POST",
                dataType: "json",
                data: form.serialize(),
                success: function (result) {
                    alert(result.success);
                    // also have result.model and result.errors                      
                }   
            });

关于asp.net-mvc - jQuery.parseJSON 不适用于 MVC Controller 操作中的 JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203728/

相关文章:

asp.net-mvc-3 - MVC3 始终在新选项卡中返回文件而不替换旧选项卡

asp.net-mvc - '模型, 'ViewBag' 在 View 的当前上下文中不存在

asp.net-mvc-3 - MVC Paypal 助手错误 : PayPal. Platform.SDK.FATALException

asp.net-mvc - View 无法访问模型 MVC

javascript - 在 JavaScript 或 jQuery 中获取部分 View 中的 HTML 类名称

php - 如何在列值的 where 子句中使用内爆

java - javax.json - 如何检查值是否是字符串

asp.net-mvc - 如何在 MVC 4 中使用我自己的 User 表而不是默认的 UserProfile?

jquery - MVC2 EditorFor - 使用 jQuery 添加条目

javascript - 如何预解析 JSON 字符串?