Method of JSON Data Interaction in ASP. NET MVC 4
- 2021-09-16 06:43:52
- OfStack
Foreground Ajax requests often need to obtain JSON format data from the background, 1 generally have the following ways:
Splice string
return Content("{\"id\":\"1\",\"name\":\"A\"}");
In order to strictly conform to Json data format, double quotation marks are escaped.
Serialize an object to a string MSDN in JSON format using the JavaScriptSerialize. Serialize () method
For example, we have one anonymous object:
var tempObj=new
{
id=1,
name="A"
}
Returns the Json string through the Serialize () method:
string jsonData=new JavaScriptSerializer().Serialize(tempObj);
return Content(jsonData);
Returns JsonResult type MSDN
In ASP. NET MVC, you can return the serialized JSON object directly:
public JsonResult Index()
{
var tempObj=new
{
id=1,
name="A"
}
return Json(tempObj, JsonRequestBehavior.AllowGet);
}
The parameter 'JsonRequestBehavior. AllowGet' needs to be set to allow GET requests.
When the foreground processes the returned data, for 1 or 2 methods, you need to use the parseJSON method provided by JQuery to convert the returned string into an JSON object:
$.ajax({
url:'/home/index',
success:function(data){
var result=$.parseJSON(data);
//...
}
});
For the third method, you can use it directly as an JSON object.