Skip to main content
 首页 » 编程设计

c#之更改 DropDownList 的 SelectList

2024年02月06日19jpfss

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

请您参考如下方法:

当名为 ddlBusinessAreaId 的下拉列表更改时,它会清空名为 ddlFunctionalAreaId 的下拉列表的项目。然后它向 blah Controller 上存在的名为 GetFunctionalAreas 的方法发出发布请求。然后循环遍历结果并将它们作为项目添加到 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); 
            } 
        }) 
    });