MVC3级联下拉列表从数据库中预选值

本文关键字:数据库 级联 下拉列表 MVC3 | 更新日期: 2023-09-27 18:07:23

我使用jQuery和AJAX实现了一个级联下拉列表。这在创建项目上很好,但是当我编辑现有项目时,我需要从数据库中预先选择值。我试图创建一个SelectList与预选值从模型,但这只在第一个下拉列表工作。

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

这是我的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
                        }));
                });
            });
    });
});

这是我的cascascasingdownlist代码:

   <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>

MVC3级联下拉列表从数据库中预选值

将此替换为您的代码并尝试。

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