2016-11-24 133 views
0

我喜試圖讓一個下拉列表中的控制器如何使用分組SelectListItem MVC

public ActionResult Index() 
    { 
     IEnumerable<GroupedSelectListItem> item; 
     item = new List<GroupedSelectListItem> { 
        new GroupedSelectListItem() { Value = "volvo", Text = "Volvo", GroupName = "Swedish Cars", GroupKey = "1", Disabled = true }, 
        new GroupedSelectListItem() { Value = "saab", Text = "Saab",GroupName = "Swedish Cars", GroupKey = "1" }, 
        new GroupedSelectListItem() { Value = "mercedes", Text = "Mercedes", GroupName = "German Cars", GroupKey = "2" }, 
        new GroupedSelectListItem() { Value = "audi", Text = "Audi", GroupName = "German Cars", GroupKey = "2",Selected = true }}; 
     ViewBag.item = item; 
     return View(); 
    } 

,並在視圖

<div class="form-group"> 
     <label for="class_id" class="col-sm-2 control-label">Classe</label> 
     <div class="col-sm-10"> 

    @Html.DropDownGroupList("Cars", ViewBag.item, "-- Select Car --", new Dictionary<string, object>() { { "data-val", "true" }, { "data-val-required", "The Car field is required." } }) 

     </div 

我試圖通過了IEnumerable到分組

與viewbag 視圖,但它不能正常工作 我是新的.net編程謝謝

+0

什麼是'GroupedSelectListItem'?和'Html.DropDownGroupList()' - 它們不是MVC的一部分。你使用什麼插件?而你使用'ViewBag'傳遞它是動態的,所以你需要投它 - '(IEnumerable )ViewBag.item' –

+0

我使用這個插件https://www.nuget.org/packages/DropDownList。 Optgroup.MVC/ –

+0

這是一個樣本http://bhaumikpatel.github.io/DDL.optgroup.MVC.Demo/ –

回答

0

簡單隻需添加模型,並用它像這樣

Index.cshtml

@model IList<GroupedSelectListItem> 

@{ 
    ViewBag.Title = "Index"; 

} 

@using (Html.BeginForm()) 
{ 
    @Html.DropDownGroupList("Cars",Model, "-- Select Car --", new Dictionary<string, object>() { { "data-val", "true" }, { "data-val-required", "The Car field is required." } }) 

} 

HomeController.cs

public class HomeController : Controller 
{ 
    // 
    // GET: /Home/ 

    public ActionResult Index() 
    { 
     var item = new List<GroupedSelectListItem> { 
    new GroupedSelectListItem() { Value = "volvo", Text = "Volvo", GroupName = "Swedish Cars", GroupKey = "1", Disabled = true }, 
    new GroupedSelectListItem() { Value = "saab", Text = "Saab",GroupName = "Swedish Cars", GroupKey = "1" }, 
    new GroupedSelectListItem() { Value = "mercedes", Text = "Mercedes", GroupName = "German Cars", GroupKey = "2" }, 
    new GroupedSelectListItem() { Value = "audi", Text = "Audi", GroupName = "German Cars", GroupKey = "2",Selected = true }}; 
     return View(item); 
    } 

    [HttpPost] 
    public ActionResult Index(FormCollection formCollection) 
    { 


     return View(); 
    } 

} 
相關問題