更改DropDownList的{Select 44}

时间:2015-05-15 22:59:08

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

我的视图中有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。 那么,实现这种行为的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

当名为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);
            }
        })
    });

答案 1 :(得分:1)

我必须使用Jquery来检测第一个字段中的更改 .change()。编写一个Controller服务,通过Ajax方法更新第二个下拉列表。请查看此示例An ASP.NET MVC Cascading Dropdown List

答案 2 :(得分:1)

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