There is a simple ajax POST request that must stringify a simple class and pass it in the body of POST request, but the Person parameter on the server-side has empty(default) values
// 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);
});
// C# code
public IActionResult OnPostAbc(Person person)
{
return new JsonResult("my result");
}

On the server-side, there is a simple ASP.NET Core Razor page with a method that gets hit and returns the result but the person param members have no values.
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);
});
}
cshtml.cs:
public IActionResult OnPostAbc([FromBody]Person person)
{
return new JsonResult("my result");
}
result:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With