首页 > 解决方案 > 使用模型中的元素列表在循环上处理 JQuery .change()

问题描述

我有一个视图,其中有下拉级联元素如果您在下拉列表中选择一个元素,它将获得一个列表并使用结果元素填充另一个下拉列表。如果我只有一对级联下拉列表,它可以工作,但是,如果我添加多个级联下拉列表,它就不起作用,它只是将元素添加到第一个依赖下拉列表,我知道这是因为禁止使用相同的 ID,但是,我不知道如何使它成为可能。(有多个级联下拉菜单)

Ajax 代码如下:

  $(document).ready(function () {

        $("#CC").change(function () {
            $("#CustomerId").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCustomersByCC")',

                dataType: 'json',

                data: { id: $("#CC").val() },


                success: function (states) {


                    $.each(states, function (i, CustomerId) {
                        $("#CustomerId").append('<option value="' + CustomerId.Value + '">' +
                            CustomerId.Text + '</option>');

                    });
                },
                error: function (ex) {
                    alert('Error getting cost centers' + ex);
                }
            });
            return false;
        })
    });

在我看来:

     @model List<FlexCart.Data.Context.OrderItem>
     @for (int i = 0; i < Model.Count(); i++)
     {
     @Html.DropDownListFor(model => model[i].CCId,
     IEnumerable<SelectListItem>)ViewBag.CCIds, 
     htmlAttributes: new { id = "CC", @class = "form--control"})

     @Html.DropDownListFor(model => model[0].CustomerId,
     new SelectList(string.Empty, "Value", "Text"), 
     htmlAttributes: new { id = "CustomerId", @class = "form-control"})
     }

标签: jqueryajaxasp.net-mvcrazordropdown

解决方案


您应该使用相对选择器。jQueryclosestfind方法会派上用场。

首先,将每一行包装在一个容器 div 中。同时删除Id选择器,因为重复Id的 s 是无效的。为两个下拉菜单提供一个 css 类,我们稍后将用于相对选择器。

@for (int i = 0; i < Model.Count(); i++)
{
   <div class="item-row">

       @Html.DropDownListFor(model => model[i].CCId, ViewBag.CCIds as List<SelectListItem>,
                                     new { @class = "ccid form--control" })

       @Html.DropDownListFor(model => model[0].CustomerId,
                                    new SelectList(string.Empty, "Value", "Text"),
                                    new { @class = "customer form-control" })

   </div>
}

现在,在您的更改事件中

$(document).ready(function () {

    $("SELECT.ccid").change(function() {
        var val = $(this).val();
        var $customer = $(this).closest(".item-row").find("SELECT.customer");

        $customer.empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetCustomersByCC")',
            data: { id: val },
            success: function(states) {
                var options = '';
                $.each(states, function(i,c) {
                    options+= '<option value="' + c.Value + '">' + c.Text + '</option>';
                });
                $customer.append(options);
            },
            error: function(ex) {
                alert('Error getting cost centers' + ex);
            }
        });
    });

});

选择$(this).closest(".item-row")器为我们提供了包装器 div,.find("SELECT.customer")并将在该容器 div 中提供客户选择元素。


推荐阅读