Methods of JSON data interaction in ASP.NET MVC 4

巴扎黑
Release: 2017-04-17 10:44:42
Original
1715 people have browsed it

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\"}");
Copy after login

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"
}
Copy after login

Through the Serialize() method, return the Json string:


string jsonData=new JavaScriptSerializer().Serialize(tempObj);
return Content(jsonData);
Copy after login

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); 
}
Copy after login

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);
    //...
  }
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!