MVC的JsonResult用法

在Asp.net Mvc 2中因为对数据的保护,默认状况下request为post,因此在前端请求的时候则须要以post方式requesthtml

action方法:前端

public JsonResult GetPersonInfo() 
{
var person = new
{
Name = "张三",
Age = 22,
Sex = ""
};
return Json(person);
}

前端请求代码:ajax

$.ajax({                
url: "/FriendLink/GetPersonInfo",
type: "POST",
dataType: "json",
data: { },
success: function(data) {
$("#friendContent").html(data.Name);
}
})

可是,若是是换成了GET方式request则会出错,以下图:json

 Get方式

难道这样一来不能用GET方式request了吗?post

固然确定是能够的,很简单url

json方法有一个重构:spa

protected internal JsonResult Json(object data);

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);

咱们只须要使用第二种就好了,加上一个 json请求行为为Get方式就OK了.net

 

 public JsonResult GetPersonInfo() 
{
var person = new
{
Name = "张三",
Age = 22,
Sex = "男"
};
return Json(person,JsonRequestBehavior.AllowGet);
}

这样一来咱们在前端就能够使用Get方式请求了:code

 

$.getJSON("/FriendLink/GetPersonInfo", null, function(data) { 
$("#friendContent").html(data.Name);
})

 

这样咱们就能够经过Json序列化咱们要返回的对象(返回JsonResult),咱们就不用再使用JavaScriptSerializer来进行序列化了,MVC已经帮咱们处理好了这些,是否是更加容易了如今!htm

相关文章
相关标签/搜索