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 =>
{
});
您需要对要发送到服务器的数据进行字符串化,以将其转换为JSON,因为这是您指示的内容类型标头:
data: JSON.stringify(data)
Please Try This Solution :
var data = {firstname : 'ali', lastname: 'alavi', age: 31};
var formData = new FormData();
formData.append('data',JSON.stringify(data));
$.ajax({
type: "POST",
url: controllerUrl, //something like ~/[ControllerName]/[ActionName]
data: formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
if (data.success)
// ...
else
// ...
},
error: function () {
// log error ...
}
});
using Newtonsoft.Json;
.
.
.
[HttpPost]
public JsonResult CreateServicesPost(string data)
{
var personModel = new PersonModel();
personModel = JsonConvert.DeserializeObject<PersonModel>(data);
// ...
}
public class CreateServicePostModel
{
public string Firstname{ get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.