【问题标题】:Change SelectList of DropDownList更改 DropDownList 的 SelectList
【发布时间】:2015-05-15 22:59:08
【问题描述】:

我的视图中有 2 个 DropDownList 项目。 DropDownList1 的 SelectList 从数据库中获取一次,不再进一步更改。每次用户更改 DropDownList1 的选定索引时,DropDownList2 的 SelectedList 也必须更改。

这是我尝试实现此功能的方式:

@{
    var selectList1 = MyApp.Models.Model1.GetAll();
    Int32 selectedId = 0;
    @Html.DropDownListFor(s => selectedId, new SelectList(selectList1, 
                                                          "dataValueField1",
                                                          "dataTextField1") as SelectList, 
                          "Choose item...")
    var selectList2 =    MyApp.Models.Model2.GetItemsById(selectedId);
    @Html.DropDownListFor(model2 => model2.SelectedItem2, new  SelectList(selectList2, 
                                                                          "dataValueField2",
                                                                          "dataTextField2") as SelectList,
                          "Choose item2..")
}

我知道,每次更改 DropDownList1 的选定索引时,我都必须更新 selectList2 变量,然后再更新 DropDownList2。 那么,实现这种行为的最佳方法是什么?

【问题讨论】:

标签: c# jquery asp.net-mvc razor


【解决方案1】:

当名为 ddlBusinessAreaId 的下拉列表更改时,它会清空名为 ddlFunctionalAreaId 的下拉列表中的项目。然后它向 blah 控制器上存在的名为 GetFunctionalAreas 的方法发出 post 请求。然后它循环遍历结果并将它们作为项目添加到 ddlFunctionalAreaId 下拉列表中。

$('#ddlFunctionalAreaId').change(function () {            
        $('#BusinessOwner').val("");
        $.ajax({
            type: 'POST',
            url: 'GetBusinessOwner',
            dataType: 'json',
            data: { id: $('#ddlFunctionalAreaId').val() },

            success: function (businessOwner) {
                if (businessOwner != null) {
                    $("#BusinessOwner_UserName").val(businessOwner.UserName);
                    $("#BusinessOwner_DisplayName").val(businessOwner.DisplayName);
                }
            },
            error: function (ex) {
                //alert('Failed to retrieve Business Owner.' + ex);
            }
        })
    });


    $('#ddlBusinessAreaId').change(function () {
        $('#ddlFunctionalAreaId').empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("../../blah/blah/GetFunctionalAreas")',
            dataType: 'json',
            data: { id: $('#ddlBusinessAreaId').val() },

            success: function (functionalAreas) {
                $.each(functionalAreas, function (i, functionalArea) {
                    $("#ddlFunctionalAreaId").append('<option value="' + functionalArea.Value + '">' +
                         functionalArea.Text + '</option>');
                });
                $('#ddlFunctionalAreaId').trigger('change');

            },
            error: function (ex) {
                //alert('Failed to retrieve functional areas.' + ex);
            }
        })
    });

【讨论】:

  • 你需要添加一个jquery库的引用
【解决方案2】:

我必须使用 Jquery 来检测第一个字段中 .change() 的变化。编写一个控制器服务,通过 Ajax 方法更新第二个下拉列表。检查这个例子An ASP.NET MVC Cascading Dropdown List

【讨论】:

    【解决方案3】:

    您必须使用 jquery 来制作服务器端并将数据绑定到第二个下拉列表。这是示例

             @{
             ViewBag.Title = "Classic Cascading DDL";
              }
    
    @using (Html.BeginForm("IndexDDL", "Home", FormMethod.Post, 
    new { id = "CountryStateFormID", 
          data_stateListAction = @Url.Action("StateList") })) {
    
       <fieldset>
        <legend>Country/State</legend>
        @Html.DropDownList("Countries", ViewBag.Country as SelectList,
            "Select a Country", new { id = "CountriesID" })
        <div id="StatesDivID" >
            <label for="States">States</label>
            <select id="StatesID"  name="States"></select>
        </div>
        <p>
            <input type="submit" value="Submit" id="SubmitID" />
        </p>
        </fieldset>
      }
    

    c#

         public SelectList GetCountrySelectList() 
         {
           var countries = Country.GetCountries();
           return new SelectList(countries.ToArray(),
                        "Code",
                        "Name");
         }
    
      public ActionResult IndexDDL() 
      {
       ViewBag.Country = GetCountrySelectList();
       return View();
      }
    

    Javascript 函数

               $(function () { 
    
    $('#StatesDivID').hide(); 
    $('#SubmitID').hide(); 
    
    $('#CountriesID').change(function () { 
        var URL = $('#CountryStateFormID').data('stateListAction'); 
        $.getJSON(URL + '/' + $('#CountriesID').val(), function (data) { 
            var items = '<option>Select a State</option>'; 
            $.each(data, function (i, state) { 
                items += "<option value='" + state.Value + "'>" + state.Text + "</option>"; 
                // state.Value cannot contain ' character. We are OK because state.Value = cnt++; 
            }); 
            $('#StatesID').html(items); 
            $('#StatesDivID').show(); 
    
        }); 
    }); 
    
    $('#StatesID').change(function () { 
        $('#SubmitID').show(); 
    }); 
    });
    

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多