ASP.NET MVC 4 中的JSON数据交互总结

来源:互联网 发布:讨鬼传极优化 编辑:程序博客网 时间:2024/06/05 10:01

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


拼接字符串:

return Content("{\"id\":\"1\",\"name\":\"A\"}");
为了严格符合Json数据格式,对双引号进行了转义。

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

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

var tempObj=new {    id=1,    name="A"}
通过Serialize()方法,返回Json字符串:

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

返回JsonResult类型 

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

public JsonResult Index(){    var tempObj=new     {        id=1,        name="A"    }        return Json(tempObj, JsonRequestBehavior.AllowGet);  }

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

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

<pre name="code" class="java">$.ajax({    url:'/home/index',    success:function(data){        var result=data.id;        //...    }});







0 0
原创粉丝点击