所有相关代码:
//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; }
}
"人"在Save方法中始终为null。这应该工作......感觉可能像设置问题?我需要在这里进行更改:
services.AddMvc(options =>
{
});
答案 0 :(得分:4)
您需要将要发送到服务器的数据进行字符串化,以将其转换为JSON,因为这是您指定的内容类型标题:
dt <- setDT(structure(list(File.Name = c("file1.xlsx", "file2.xlsx", "file3.xlsx")
, Split.ID = structure(c(1L, 1L, 1L)
, .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11","12", "13", "14", "15", "16", "17", "18", "19", "20"), class = "factor"))
, .Names = c("File.Name", "Split.ID")
, class = c("data.table", "data.frame"), row.names = c(NA, -3L)))
for(file in as.vector(dt[1:3,1])){
print(file)
}
for(i in letters[1:4]){print(i)}
答案 1 :(得分:0)
请尝试以下解决方案:
在Jquery文件中:
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);
// ...
}
您的Perso模型是:
public class CreateServicePostModel
{
public string Firstname{ get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
}