How to use Jsonresult under MVC (jsonrequestbehavior.allowget)

Source: Internet
Author: User

MVC default Request mode is Post.

Action
Public Jsonresult Getpersoninfo ()
{
var person = new
{
Name = "Zhang San",
Age = 22,
Sex = "Male"
};
return Json(person);
}

Or

Public Jsonresult Getpersoninfo ()
{
return Json (new{Name = "Zhang san", age = 22,sex = "Male"});
}

View

$.ajax ({
URL: "/friendlink/getpersoninfo",
Type: "POST",
DataType: "json",
Data: {},
Success:function (data) {
$ ("#friendContent"). HTML (data. Name);
}
})

There is no problem with the POST request, the GET method request error:

Workaround

The JSON method has a refactoring:

protected internal Jsonresult Json(object data);
protected internal Jsonresult Json(object data, jsonrequestbehavior behavior);

We just need to use the second type, plus a JSON request behavior is OK for Get mode

Public Jsonresult Getpersoninfo ()
{
var person = new
{
Name = "Zhang San",
Age = 22,
Sex = "Male"
};
return Json(person,jsonrequestbehavior. Allowget);
}

In this way we can request it in the front-end using get:

$.getjson ("/friendlink/getpersoninfo", NULL, function (data) {
$ ("#friendContent"). HTML (data. Name);
})

How to use Jsonresult under MVC (jsonrequestbehavior.allowget)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.