ListBox,DropDownList都是通過使用指定的 HTML 幫助器和窗體字段的名稱,傳回單選select 元素。
同屬于SelectExtensions 類
1、@Html.ListBox()
通過使用指定的 HTML 幫助器、窗體字段的名稱、指定的清單項和指定的 HTML 特性,傳回多選 select 元素
主要參數有
string name, //要傳回的窗體字段的名稱
IEnumerable<SelectListItem> selectList, // 一個用于填充下拉清單的 SelectListItem 對象的集合。
IDictionary<string, Object> htmlAttributes // 一個對象,其中包含要為該元素設定的 HTML 特性。可以設定寬度等樣式
@{
List<string> listBox=new List<string>();
listBox.Add("第一");
listBox.Add("第二");
listBox.Add("第三");
}
@{
List<string> listBoxSelectd=new List<string>();
listBoxSelectd.Add("第一");
listBoxSelectd.Add("第二");
}
例:綁定listBox資訊,并初始以“第二”為選中狀态,指定一個選中狀态
調用:
@Html.ListBox("listName", new SelectList(listBox,"第二"), new { style="width:200px"})
輸出:
<select id="listName" multiple="multiple" name="listName" style="width:200px">
<option>第一</option>
<option selected="selected">第二</option>
<option>第三</option>
</select>
用new MultiSelectList()可以指定傳回多個選中的值
@Html.ListBox("moreListName", new MultiSelectList(listBox, listBoxSelectd))
輸出:
<select id="moreListName" multiple="multiple" name="moreListName">
<option selected="selected">第一</option>
<option selected="selected">第二</option>
<option>第三</option>
</select>
擷取選中項:
在頁面送出的時候,用request或者FormCollection collection對象進行值的擷取
如Request["listName"]、collection["moreListName"] 擷取多個選擇值時,中間以","号隔開傳回
[email protected]()
通過使用指定的 HTML 幫助器、窗體字段的名稱、指定的清單項和指定的 HTML 特性,傳回多選 select 元素
常用方法:
@Html.ListBoxFor(mo => mo.name, new SelectList(Model.Students, "ID", "Name"),
new {style="width:200px"})
Model.Students:為輸出的list對象
ID,Name分别為對象中的兩個屬性
2、@Html.DropDownList()
傳回select的下拉清單框
使用例子:
@Html.DropDownList("ddlValue", new SelectList(new[] { "One", "Two" },"Two"),
new { style="width:200px"})
輸出:
<select id="ddlValue" name="ddlValue" style="width:200px">
<option>One</option>
<option selected="selected">Two</option>
</select>
@Html.DropDownListFor()
用法和@Html.ListBoxFor()類似,主要是針對強類型
@Html.DropDownListFor(mo => mo.name, new SelectList(Model.Students, "ID", "Name"),
new {style="width:200px"})
傳回下來清單框