Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Razor ajax POST request data object is empty

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");
}

enter image description here

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.

like image 634
Igor Avatar asked Mar 14 '26 08:03

Igor


1 Answers

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: enter image description here

like image 64
Yiyi You Avatar answered Mar 16 '26 04:03

Yiyi You



Donate For Us

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