MVC3 Cascade DropDownList pre-select values from database

I’ve implemented a cascade dropdown list using jQuery and AJAX. This works fine on creating item, but I need to pre-select values from database when I edit existing item. I’ve tried to create a SelectList with pre-selected value from model, but that worked on the first dropdownlist only.

How can I make other lists showing item Area and Category values?

Here’s my jQuery code:

 <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
                        }));
                });
            });
    });
});

And this is my cascasing dropdownlist code:

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

newest questions tagged jquery – Stack Overflow

About Admin