Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.parseJSON not working for JsonResult from MVC controller action

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!

like image 852
rboarman Avatar asked Feb 22 '23 13:02

rboarman


1 Answers

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                      
                }   
            });
like image 109
moribvndvs Avatar answered May 09 '23 06:05

moribvndvs