jQuery.parseJSON not working for JsonResult from MVC controller action

ぃ、小莉子 提交于 2021-02-07 17:22:13

问题


I am trying to use jQuery.parseJSON to parse out the return value from an MVC3 controller action.

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

Json result from fiddler:

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 can parse the results:

enter image description here

The call to jQuery.parseJSON is returning null. My questions is, how can I parse the json return value into an object?

Thanks!


回答1:


You don't need to call parseJSON in your success handler, because ajax will have already parsed the JSON result (it does this automatically because you specified dataType:'json') into your array.

However, I'd recommend returning some sort of result object (whether you create an actual class in C# or use an anonymous type).

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

and at the client

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



回答2:


You are actually returning an array of objects and they shoould be accessed like this in the success function:

var booleanValue = data[0];

var yourModel = data[1];

var yourErrors = data[2];

I did give @HackedByChinese an up vote because naming the properties might be a better way to go about it in the end. Howvbere this will solve your immediate problem.



来源:https://stackoverflow.com/questions/9203728/jquery-parsejson-not-working-for-jsonresult-from-mvc-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!