Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC model is null when posting json in ASP.Net Core

All relevant code:

//JSON data
var dataType = 'application/json; charset=utf-8';
var data = {
    FirstName: 'Andrew',
    LastName: 'Lock',
    Age: 31
}

console.log('Submitting form...');
$.ajax({
    type: 'POST',
    url: '/Diary/Save',
    dataType: 'json',
    contentType: dataType,
    data: data,
    success: function (result) {
        console.log('Data received: ');
        console.log(result);
    }
});


[HttpPost]
public IActionResult Save([FromBody] Person person)
{
    return Json(person);
}



public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

"person" in the Save method is always null. This should work...it feels perhaps like a settings issue? Do I need to make changes here:

 services.AddMvc(options =>
        {
        });
like image 546
Paul Avatar asked Feb 02 '26 01:02

Paul


1 Answers

You need to stringify the data that you are sending to the server to convert it to JSON because that's the content type header you indicated:

data: JSON.stringify(data)
like image 105
Darin Dimitrov Avatar answered Feb 03 '26 16:02

Darin Dimitrov



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!