JSON data interaction method in ASP. net mvc 4, mvcjson

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.