【发布时间】:2018-12-12 06:01:29
【问题描述】:
我正在尝试使用 ajax 将对象传递给 HttpPost 方法。
这是我的 ajax 方法:
function addItem(invoiceID) {
var newItemVM = {
Description : $('#item-description').val(),
Quantity : $('#item-quantity').val(),
ItemTaxFreePrice : $('#item-tax-free-price').val()
};
$.ajax({
type: 'POST',
url: 'AddItem',
data: JSON.stringify({ newItemVM: newItemVM }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$('#new-item').text(result.Quantity + 'Hello');
}
});
}
这是 C# 中的 HttpPost 方法
[HttpPost]
public async Task<IActionResult> AddItem(NewItemVM newItemVM)
{
return Json(newItemVM);
}
这是 NewItemVM 类:
public class NewItemVM
{
public string Description { get; set; }
public int Quantity { get; set; }
public double ItemTaxFreePrice { get; set; }
}
问题是 newItemVM 对象中的参数始终为空。
谁能告诉我我错过了什么?咳咳!
【问题讨论】:
-
您是否尝试过硬创建简单的 newItemVM 对象?例如
{ Description: 'desc', Quantity: 0, ItemTaxFreePrice:0 } -
请注意,只需
data: newItemVM,并删除contentType选项 -
C# 代码是在 Webapi 还是在 MVC 中?
-
并筛选传递给 ajax 调用的对象并对其进行控制台
-
C#代码在MVC中
标签: c# asp.net ajax asp.net-mvc post