【问题标题】:Posting data with ajax issue使用ajax问题发布数据
【发布时间】: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


【解决方案1】:

嗨,你不需要在 json 对象调用中指定你的模型的名称应该如下所示

$.ajax({
    type: 'POST',
    url: 'AddItem',
    data:  newItemVM ,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        $('#new-item').text(result.Quantity + 'Hello');
    }
});

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2017-07-14
    • 2019-01-07
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多