Home >Backend Development >C#.Net Tutorial >Methods of JSON data interaction in ASP.NET MVC 4
This article mainly introduces the JSON data interaction method in ASP.NET MVC 4. It has certain reference value. Interested friends can refer to it.
Foreground Ajax requests often need to obtain JSON format data from the background. Generally, there are the following methods:
Splicing strings
return Content("{\"id\":\"1\",\"name\":\"A\"}");
In order to strictly comply with the Json data format, the double quotes are escaped.
Use the JavaScriptSerialize.Serialize() method to serialize the object into a string in JSON format MSDN
For example, we have an anonymous object:
var tempObj=new { id=1, name="A" }
Through the Serialize() method, return the Json string:
string jsonData=new JavaScriptSerializer().Serialize(tempObj); return Content(jsonData);
Return the JsonResult type MSDN
ASP.NET MVC , you can directly return the serialized JSON object:
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 frontend, for methods 1 and 2, you need to use the parseJSON method provided by JQuery to convert the returned string into a JSON object:
$.ajax({ url:'/home/index', success:function(data){ var result=$.parseJSON(data); //... } });
For the third method, just use it directly as a JSON object.
The above is the detailed content of Methods of JSON data interaction in ASP.NET MVC 4. For more information, please follow other related articles on the PHP Chinese website!