Home  >  Article  >  Backend Development  >  Methods of JSON data interaction in ASP.NET MVC 4

Methods of JSON data interaction in ASP.NET MVC 4

巴扎黑
巴扎黑Original
2017-04-17 10:44:421709browse

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!

Statement:
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