代码改变世界

若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet

2012-06-13 15:06  诸葛二牛  阅读(21731)  评论(1编辑  收藏  举报

若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet

请将 JsonRequestBehavior 设置为 AllowGet

MVC 默认 Request 方式为 Post。
action

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

或者

 1 public JsonResult GetPersonInfo()  {  
 2   return Json (new{Name = "张三",Age = 22,Sex = "男"});  
 3 }  
 4 view  
 5 $.ajax({  
 6   url: "/FriendLink/GetPersonInfo",  
 7   type: "POST",  
 8   dataType: "json",  
 9   data: { },  
10   success: function(data) {  
11      $("#friendContent").html(data.Name);  
12   }  
13 })  

POST 请求没问题,GET 方式请求出错:

 

解决方法
json方法有一个重构:

1 public JsonResult GetPersonInfo()  {  
2   var person = new  {  
3       Name = "张三",  
4       Age = 22,  
5       Sex = ""  
6    };  
7    return Json(person,JsonRequestBehavior.AllowGet);  
8 }  

这样一来我们在前端就可以使用Get方式请求了:

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