Dropdown onchange加载另一个下拉列表MVC4

时间:2014-10-28 12:07:35

标签: asp.net-mvc entity-framework asp.net-mvc-4

我在视图中填充了两个下拉列表(Category和SubCategory)。

我通过我的控制器这样做,我希望根据所选类别的项目填充SubCategory的Dropdown。

有任何建议如何做到这一点,是否有更好,更有效的方式来填充下拉菜单?

Controller:

public ActionResult Edit(int id)
    {
        EntryViewModel model = (from subcat in dc.SubCategory
                                join en in dc.Entry on subcat.SubCategoryId equals en.SubCategoryId
                                join cat in dc.Category on subcat.CategoryId equals cat.Id
                                where en.Id == id
                                select new EntryViewModel {
                                    Id = en.Id,
                                    Title = en.Title,
                                    Username = en.Username,
                                    Password = en.Password,
                                    Url = en.Url,
                                    Description = en.Description,
                                    CategoryId = cat.Id,
                                    CategoryName = cat.Name,
                                    SubCategoryId = subcat.SubCategoryId,
                                    SubCategoryName = subcat.Name
                                }).First();

        string selectedCat = (from cat in dc.Category
                           join en in dc.SubCategory on cat.Id equals en.SubCategoryId
                           where cat.Id == en.SubCategoryId
                           select cat.Name).First();

        ViewBag.SubjectNameCat = new SelectList(dc.Category, "Id", "Name", selectedCat);

        string selected = (from cat in dc.SubCategory
                           join en in dc.Entry on cat.SubCategoryId equals en.SubCategoryId
                           where en.Id == id
                           select cat.Name).First();

        ViewBag.SubjectName = new SelectList(dc.SubCategory, "SubCategoryId", "Name", selected);

        return View(model);
    }

查看:为简单起见,只显示下拉列表

<div class="editor-label">
        Category
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.CategoryId, (IEnumerable<SelectListItem>)ViewBag.SubjectNameCat,
               new { @class = "form-control" })
    </div>

    <div class="editor-label">
        SubCategory
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.SubCategoryId, (IEnumerable<SelectListItem>)ViewBag.SubjectName,
               new { @class = "form-control" })
    </div>

1 个答案:

答案 0 :(得分:0)

@PetarS尝试这个最适合我的强大插件。 https://github.com/rajkaimal/CascadingDropDown