2014-10-28 22 views
0

我在我的視圖中填充兩個下拉列表(Category和SubCategory)。Dropdown onchange加載另一個下拉列表MVC4

我正在通過我的控制器做到這一點,我希望子類別的下拉列表根據類別中選定的項目進行填充。

任何建議如何做到這一點,是否有更好,更有效的方式來填充下拉?

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

查看:Shownig只是下拉爲了簡單列表

<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

谷歌[MVC級聯下拉列表(https://www.google.com.au/search?q=mvc+cascading+dropdownlist&oq=mvc+cascading+drop&aqs=chrome.1.69i57j0j69i60j0l3.6405j0j7&sourceid=chrome&espv=2&es_sm = 122&即= UTF-8)。如何做到這一點有很多例子。作爲附註,你的'SelectList'代碼的最後一個參數是毫無意義的。所選下拉列表的值將是'model.CategoryId'和'model.SubCategoryId'的值 – 2014-10-28 12:22:29

回答

相關問題