狐狸.fox 2018-07-03 21:01 采纳率: 0%
浏览 6

发布带有Ajax问题的数据

I am trying to pass object to HttpPost method with ajax.

This is my ajax method:

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');
    }
});

}

This is the HttpPost method in C#

[HttpPost]
    public async Task<IActionResult> AddItem(NewItemVM newItemVM)
    {
        return Json(newItemVM);
    } 

This is NewItemVM class:

public class NewItemVM
{
    public string Description { get; set; }
    public int Quantity { get; set; }
    public double ItemTaxFreePrice { get; set; }
}

The problem is that the parameters in newItemVM object are allways null.

Can somebody tell me what am I missing out? Tnq!

  • 写回答

1条回答 默认 最新

  • ℡Wang Yan 2018-07-04 06:29
    关注

    hi you don't need to specify the name of the your model in json object call should be like below

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

报告相同问题?