MVC3 Cascade DropDownList从数据库中预先选择值

时间:2011-09-04 17:18:52

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

我使用jQuery和AJAX实现了一个级联下拉列表。这在创建项目时工作正常,但我需要在编辑现有项目时从数据库中预先选择值。我尝试使用模型中预先选择的值创建一个SelectList,但这仅适用于第一个下拉列表。

如何制作显示项目区域和类别值的其他列表?

这是我的jQuery代码:

 <script type="text/javascript">
$(document).ready(function() {

    $("#ddlDeps").change(function() {
        var idArea = $(this).val();
        $.getJSON("/Admin/LoadAreasByDepartment", { id: idArea },
            function(depData) {
                var select = $("#ddlAreas");
                select.empty();
                select.append($('<option/>', {
                        value: 0,
                        text: "Выберите направление"
                    }));
                $.each(depData, function(index, itemData) {

                    select.append($('<option/>', {
                            value: itemData.Value,
                            text: itemData.Text
                        }));
                });
            });
    });


    $("#ddlAreas").change(function() {
        var idCategory = $(this).val();
        $.getJSON("/Admin/LoadCategoriesByArea", { id: idCategory },
            function(areaData) {
                var select = $("#ddlCategories");
                select.empty();
                select.append($('<option/>', {
                        value: 0,
                        text: "Выберите категорию"
                    }));
                $.each(areaData, function(index, itemData) {

                    select.append($('<option/>', {
                            value: itemData.Value,
                            text: itemData.Text
                        }));
                });
            });
    });
});

这是我的级联下拉列表代码:

   <p>
    @Html.DropDownListFor(model => model.DepartmentId, new SelectList(Model.DataContainer.Departments, "Id", "Name"),
                            "Выберите отдел", new {id = "ddlDeps"})
    @Html.ValidationMessageFor(model => model.DepartmentId)                                                    
</p>
<p>

    @{
        var areaSelectList = new SelectList(Enumerable.Empty<SelectListItem>(), "DepartmentId", "Title", Model.AreaId);
        var categorySelectList = new SelectList(Enumerable.Empty<SelectListItem>(), "AreaId", "Title", Model.CategoryId);
    }
    @Html.DropDownListFor(model => model.AreaId, areaSelectList,
                            "Выберите направление", new {id = "ddlAreas"})
    @Html.ValidationMessageFor(model => model.AreaId)             
</p>
<p>
    @Html.DropDownListFor(model => model.CategoryId, categorySelectList,
                            "Выберите категорию", new {id = "ddlCategories"})
</p>

1 个答案:

答案 0 :(得分:0)

在代码中替换它并尝试。

@{
        var areaSelectList = new SelectList(Model.DataContainer.Areas, "DepartmentId", "Title", Model.AreaId);
        var categorySelectList = new SelectList(Model.DataContainer.Categories, "AreaId", "Title", Model.CategoryId);
    }