2011-11-24 68 views
1

問:如何從multiselect(selectList)創建optGroup?

模型(僞):

class Area { 
    string Name; 
    string Id; 
    string GroupId; // Want to group by this and display opt groups with my multiselect. 
} 

控制器:

ViewBag.AreaList = new SelectList(db.Areas.OrderBy(x => x.Name), "AreaId", "Name"); 

查看:

@Html.ListBox("AreaList", null) 

<script type="text/javascript"> 
$("#AreaId").multiselect({ 
    selectedText: "Selected: #", 
    minWidth: 210, 
    noneSelectedText: "", 
    selectedList: 1 
}); 
</script> 

我怎樣才能給出下面的一個multiselect內創建optGroups生成的HTML(示例):

<select> 
    <optgroup label="Group 1"> 
    <option value ="1">Option 1</option> 
    <option value ="2">Option 2</option> 
    </optgroup> 
    <optgroup label="Group 2"> 
    <option value ="3">Option 3</option> 
    <option value ="4">Option 3</option> 
    </optgroup> 
</select> 

回答

2
<select> 
@foreach (var group in Model.AreaList.select(new {group:GroupID}).Distinct()) 
{ 
    <optgroup>@group</optgroup> 
    @foreach(var item in Model.AreaList.Where(r=>r.GroupID == group)) 
    { 
     <option value="@id">@Name</option> 
    } 
}