Igo*_*gor 3 ajax asp.net-core razor-pages
有一个简单的 ajax POST 请求,必须字符串化一个简单的类并将其传递到 POST 请求的正文中,但服务器端的Person参数具有空(默认)值
// javascript
var person = { "FirstName": "Andrew", "LastName": "Lock", "Age": "31" };
$.ajax({
type: "POST",
url: "/UpdatePostBody?handler=Abc",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(person),
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
})
.done(function (result) {
console.log(result);
});
Run Code Online (Sandbox Code Playgroud)
// C# code
public IActionResult OnPostAbc(Person person)
{
return new JsonResult("my result");
}
Run Code Online (Sandbox Code Playgroud)
在服务器端,有一个简单的 ASP.NET Core Razor 页面,其中包含一个被命中并返回结果的方法,但person参数成员没有值。
Yiy*_*You 10
Your Pesron data is null is because your Age in class Person is int type.And your person in { "FirstName": "Andrew", "LastName": "Lock", "Age": "31" } is string type,So you cannot get it.Also,as you pass json data from ajax to handler,you need to add [FromBody] in handler.Here is a demo:
cshtml:
<button onclick="postdata()">Abc</button>
function postdata() {
//change Age type to int
var person = { "FirstName": "Andrew", "LastName": "Lock", "Age": 31 };
$.ajax({
type: "POST",
url: "/UpdatePostBody?handler=Abc",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(person),
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
})
.done(function (result) {
console.log(result);
});
}
Run Code Online (Sandbox Code Playgroud)
cshtml.cs:
public IActionResult OnPostAbc([FromBody]Person person)
{
return new JsonResult("my result");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8490 次 |
| 最近记录: |