我正在尝试向方法发送Ajax请求,但请求始终为空,下面是我的代码: Ajax请求,请求成功到达C#方法但对象始终为null。
$(document).ready(function () {
$("#SubmitProduct").click(function () {
var ProductName = $("#ProductName").val();
var ProductPrice = $("#ProductPrice").val();
var Category = $("#Categories").val();
var Data = { ProductName: ProductName, ProductPricd: ProductPrice, Category: Category };
//console.log("product name: " + ProductName);
//console.log("Product Price: " + ProductPrice);
//console.log("Category : " + Category);
//console.log("data : " + Data.ProductName);
//The above log are logging data successfully.
$.ajax({
type: "POST",
url: "/Products/SubmitProduct",
contentType: "application/json",
cache: false,
data: JSON.stringify(Data),
success: function (data)
{
alert("Success");
},
error: function (data)
{
console.log(data);
},
complete: function () {
}
});
});
});
下面的日志显示了结果并且很好(参数具有预期的值)。
//console.log("product name: " + ProductName);
//console.log("Product Price: " + ProductPrice);
//console.log("Category : " + Category);
//console.log("data : " + Data.ProductName);
以下是C#方法:
[HttpPost]
public async Task <IActionResult> SubmitProduct([FromBody] Products product)
{
return Content("OK");
}
以下是产品类别:
[Table("Products")]
public class Products
{
[Key]
public Guid ProductId { get; set; }
[Column(TypeName ="varchar(25)")]
[Required(ErrorMessage ="Product Name is required..")]
[StringLength(25, MinimumLength = 2, ErrorMessage = "Product name must be between 2 and 25 characters...")]
public string ProductName { get; set; }
[Required(ErrorMessage ="ProductName price is required...")]
[Range(0.001,1000000.000,ErrorMessage = "Price should be between 0.01 and 1000000.000")]
[Column(TypeName="decimal(10,3)")]
public decimal ProductPricd { get; set; }
[Required(ErrorMessage = "Product Image is required...")]
[NotMapped]
public IFormFile ProductImage { get; set; }
[Required(ErrorMessage = "Image Name is required...")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Image Name must be between 3 and 50")]
[Column(TypeName = "varchar(100)")]
public string ImageName { get; set; }
[ForeignKey("CategoryId")]
[Required]
public ProductsCategories Category { get; set; }
[ForeignKey("UserId")]
[Required]
public string UserId { get; set; }
// Navigation property
public ApplicationUsers User { get; set; }
[Column(TypeName ="varchar(3)")]
public string IsDeleted { get; set; } = "0";
}
请求成功到达方法,但对象为空,有什么帮助吗?
我尝试了下面的ajax,但对象也是空的
$.ajax({
type: "POST",
url: "/Products/SubmitProduct",
contentType: "application/json",
data: JSON.stringify({
ProductId: "some-guid-value",
ProductName: "Product Name",
ProductPrice: 10.99,
// Other properties here
}),
success: function (data) {
alert("Success");
},
error: function (data) {
console.log("Error: " + data.status + " - " + data.responseText);
}
});