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

相關文章
相關標籤/搜索