【发布时间】:2018-10-17 22:17:27
【问题描述】:
我正在尝试使用 ajax 帖子将代表模型的 javascript 对象发布回控制器。但是,模型始终显示为 null。
有问题的型号如下
public class Product
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name is required and must not be empty.")]
[StringLength(200, ErrorMessage = "Name should not exceed 200 characters.")]
public string Name { get; set; }
public DateTime Created { get; set; }
[Required(ErrorMessage = "Price is required and must not be empty.")]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
ajax 调用看起来像这样
$('#btnSaveNewProduct').click(function (e) {
e.preventDefault();
var form = $('#frmNewProduct');
if (form.valid()) {
var data = { // to be replaced with form values
Name: 'Bob',
Price: 34
};
//ajax call to save product
$.ajax({
type: "POST",
url: "@Url.Action("AddProduct", "Admin")",
contentType: "application/json",
dataType: "json",
data: data,
success: function (response) {
alert('done');
},
error: function (response) {
alert(response);
}
});
}
});
控制器方法如下所示
[HttpPost]
public JsonResult AddProduct([FromBody] Product product)
{
bool success = false;
// save product
success = true;
return new JsonResult(success);
}
任何见解将不胜感激。
【问题讨论】:
-
data: "json", data: data? -
data: "json"-> 'dataType: "json"` -
我还建议您查看 AJAX 助手。这是一篇关于它们的 C# Corner 帖子:https://www.c-sharpcorner.com/article/Asp-Net-mvc-ajax-helper/.
-
@CodeBreaker 这些在 ASP.NET Core 中已弃用
-
试试
data: JSON.stringify(data),
标签: c# jquery ajax asp.net-core