JSON data interaction method in ASP. net mvc 4, mvcjson
The front-end Ajax requests often need to obtain JSON-format data from the backend. The following methods are generally used:
Concatenated string
return Content("{\"id\":\"1\",\"name\":\"A\"}");
Double quotation marks are escaped to strictly conform to the Json data format.
Use the JavaScriptSerialize. Serialize () method to Serialize an object to a string in JSON format: MSDN
For example, we have an anonymous object:
var tempObj=new { id=1, name="A"}
Return a Json string using the Serialize () method:
string jsonData=new JavaScriptSerializer().Serialize(tempObj);return Content(jsonData);
Return JsonResult type MSDN
In ASP. net mvc, serialized JSON objects can be directly returned:
public JsonResult Index(){ var tempObj=new { id=1, name="A" } return Json(tempObj, JsonRequestBehavior.AllowGet); }
You need to set the parameter 'jsonrequestbehavior. allowget' to allow GET requests.
When processing the returned data in the foreground, you must use the parseJSON method provided by JQuery to convert the returned string to a JSON object in either of the following methods:
$.ajax({ url:'/home/index', success:function(data){ var result=$.parseJSON(data); //... }});
The third method can be directly used as a JSON object.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.