将数组传递给JSON对象以及要在ajax中使用的其他变量

时间:2016-12-27 09:44:29

标签: c# arrays json ajax asp.net-mvc

这是我第一次使用JSON对象将数组传递给ajax。正如您在我的代码中看到的那样,我不确定如何正确地将数组传递给JSON对象以供ajax读取。当它传递给Controller时,参数中的items变量为空。

查看Javasript

var itemprice = [];
//Populate itemprice. This will be used to check if the newly added item is already existing
$('#tblItem tbody tr td:nth-child(5)').each(function () {
    itemprice.push($(this).text());
});

var json = {
    item: $('#item').val(),
    itemtypeid: $('#itemtype option:selected').val(),
    itempromocount: $('#tblItem tbody tr #tditem_promo').length,
    items: itemprice //I'm not sure how to pass an array to Controller
};

$.ajax({
    url: '/Items/CheckItems',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(json),
    contentType: 'application/json; charset=utf-8',
    cache: false,
    async: true,
    success: function (response) {
        ...
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Error! " + xhr.status);
    }
});

控制器

public JsonResult CheckItems(string itemtypeid, int itempromocount, string items)
{
    //itemtypeid and itempromocount has value but items don't have
}

1 个答案:

答案 0 :(得分:1)

控制器中的

items是一个字符串列表:

public JsonResult CheckItems(string itemtypeid, int itempromocount, List<string> items)
{
    //itemtypeid and itempromocount has value but items don't have
}