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 =>
{
});
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)
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