添加查询参数时,列表模型正确停止绑定

时间:2018-10-04 17:43:54

标签: jquery asp.net-core-mvc model-binding

我正在使用模式编辑器对话框来允许用户修改客户地址列表。当客户想要添加或删除地址时,我可以使用AJAX请求通过JQuery处理它。尽管实际上是通过剪切和粘贴对代码进行了少量更改,但是我的addAddr()函数仍按预期运行(控制器接收到地址列表),而我的delAddr()函数却无法正常运行(控制器即使模型包含多个地址,也会收到一个包含一个地址的列表。)有人可以在下面的代码中看到该错误吗?

控制器操作:

[HttpPost]
public async Task<IActionResult> AddCustomerAddress(List<CustomerAddress> Model)
{
    var newAddr = new CustomerAddress
    {
        CustomerID = Model[0].CustomerID,
        IsActive = true,
        IsPrimary = true
    };

    await _dbService.InsertCustomerAddressAsync(newAddr);

    return RedirectToAction(nameof(EditCustomerAddresses), new { Model[0].CustomerID });
}

[HttpPost]
public async Task<IActionResult> DeleteCustomerAddress(List<CustomerAddress> Model, [FromQuery]int Index)
{
    await _dbService.DeleteCustomerAddressAsync(Model[Index]);

    return RedirectToAction(nameof(EditCustomerAddresses), new { Model[0].CustomerID });
}

jQuery:

function addAddr() {
    var model = $('form#addr-editor').serialize();
    $.post('/Customer/AddCustomerAddress',
        model,
        function (data, status, jqXHR) {
            $('#modal-container').html(data);
            $.notify('New Address Activated - Save Changes After Editing', { position: "top-center" });
        }
    ).fail(function () {
        $.notify('Error adding Address.', { position: "top center" });
    });
}

function delAddr(index) {
    var model = $('form#addr-editor').serialize();
    $.post('/Customer/DeleteCustomerAddress?Index=' + index,
        model,
        function (data, status, jqXHR) {
            $('#modal-container').html(data);
            $.notify('Address Deleted Successfully', { position: "top center" });
        }
    ).fail(function () {
        $.notify('Error Deleting Address.', { position: "top center" });
    });
}

我的测试记录有六个地址。 “添加”操作将接收带有List<CustomerAddress>的{​​{1}}。 Delete操作可以正确接收索引,但是它将模型与Count = 6一起接收为List<CustomerAddress>。我知道的唯一区别是查询字符串中包含一个附加参数。我期望的行为是两个控制器动作都接收6个地址的列表。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

我终于弄清楚了这个问题-看来这是一个功能,而不是错误...将动作签名更改为类似这样的名称可以解决问题:

[HttpPost]
public async Task<IActionResult> DeleteCustomerAddress(List<CustomerAddress> Model, [FromQuery]int NotTheIndex)
{
    await _dbService.DeleteCustomerAddressAsync(Model[NotTheIndex]);

    return RedirectToAction(nameof(EditCustomerAddresses), new { Model[0].CustomerID });
}

这表明Index是保留的参数名称。当我在列表中获得一个条目且索引为2时,我实际上仅获得Model[2]

FromForm之前添加Model也可以解决问题:

public async Task<IActionResult> DeleteCustomerAddress([FromForm]List<CustomerAddress> Model, [FromQuery]int Index)