jQuery.parseJSON不适用于来自MVC控制器操作的JsonResult

rbo*_*man 4 asp.net-mvc jquery json asp.net-mvc-3

我试图使用jQuery.parseJSON来解析MVC3控制器操作的返回值.

控制器:

    [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 });
    }
Run Code Online (Sandbox Code Playgroud)

jQuery的:

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

来自小提琴手的Json结果:

Content-Type:application/json; 字符集= utf-8的

[假,{ "用户名": "1", "密码": "2", "与rememberMe":假},[{ "键": "", "错误":[{ "异常":空"的ErrorMessage ":"提供的用户名或密码不正确."}]}]]

Fiddler可以解析结果:

在此输入图像描述

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

谢谢!

Hac*_*ese 6

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

但是,我建议返回某种结果对象(无论是在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 });
    }
Run Code Online (Sandbox Code Playgroud)

在客户端

$.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                      
                }   
            });
Run Code Online (Sandbox Code Playgroud)