ASP.NET MVC 4 中的JSON数据交互的方法

时间:2022-08-23 08:15:02

前台Ajax请求很多时候需要从后台获取JSON格式数据,一般有以下方式:

拼接字符串

?
1
return Content("{\"id\":\"1\",\"name\":\"A\"}");

为了严格符合Json数据格式,对双引号进行了转义。 

使用JavaScriptSerialize.Serialize()方法将对象序列化为JSON格式的字符串 MSDN

例如我们有一个匿名对象:

?
1
2
3
4
5
var tempObj=new
{
  id=1,
  name="A"
}

通过Serialize()方法,返回Json字符串:

?
1
2
string jsonData=new JavaScriptSerializer().Serialize(tempObj);
return Content(jsonData);

返回JsonResult类型 MSDN

ASP.NET MVC 中,可以直接返回序列化的JSON对象:

?
1
2
3
4
5
6
7
8
9
10
public JsonResult Index()
{
  var tempObj=new
  {
    id=1,
    name="A"
  }
  
  return Json(tempObj, JsonRequestBehavior.AllowGet);
}

需要设置参数‘JsonRequestBehavior.AllowGet',允许GET请求。

前台处理返回的数据时,对于1,2种方法,需要使用JQuery提供的parseJSON方法,将返回的字符串转换为JSON对象:

?
1
2
3
4
5
6
7
$.ajax({
  url:'/home/index',
  success:function(data){
    var result=$.parseJSON(data);
    //...
  }
});

 对于第三种方法,直接作为JSON对象使用即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/luotaoyeah/p/3325264.html