更改下拉列表的SelectList

本文关键字:SelectList 下拉列表 | 更新日期: 2023-09-27 17:49:15

我的视图中有2个下拉列表项。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..")
}

我知道,我必须更新selectList2变量每次当DropDownList1的选定索引被改变,并在此之后更新DropDownList2。那么,实现这种行为的最佳方式是什么呢?

更改下拉列表的SelectList

当名为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来检测更改.change()在第一个字段。编写一个Controller服务,通过Ajax方法更新第二个下拉列表。检查这个示例:一个ASP。. NET MVC级联下拉列表

必须使用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(); 
}); 
});