JQuery.parseJSON not working for JsonResult from MVC controller action

I am trying to use jQuery.parseJSON to parse 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 violinist:

Content-Type: application / json; encoding = UTF-8

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

Fiddler can analyze the results:

enter image description here

A jQuery.parseJSON call returns null. My questions are: how can I parse the json return value into an object?

Thanks!

+4
source share
2 answers

You do not need to call parseJSON in your success handler because ajax already parsed the JSON result (it does this automatically because you specified dataType:'json' ) in your array.

However, I would recommend returning some kind of result object (do you create the 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 on 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 } }); 
+6
source

In fact, you are returning an array of objects, and they should be available this way in the success function:

 var booleanValue = data[0]; var yourModel = data[1]; var yourErrors = data[2]; 

I gave @HackedByChinese a voice, because assigning properties may be the best way to do this at the end. Howvbere it will solve your immediate problem.

+2
source

Source: https://habr.com/ru/post/1395522/


All Articles