MVC 默认 Request 方式为 Post。

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

或者

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

view

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

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

MVC 下 JsonResult 的使用方法(JsonRequestBehavior.AllowGet)<转>

解决方法

json方法有一个重构:

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

我们只需要使用第二种就行了,加上一个 json请求行为为Get方式就OK了

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

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

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
  • 2021-10-10
  • 2021-08-30
  • 2021-07-16
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-30
  • 2021-09-23
  • 2022-12-23
  • 2021-06-24
  • 2021-07-05
相关资源
相似解决方案