Html.DropDownList()賦預設值:
頁面代碼如下:
<%
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem { Text = "啟用", Value = "0",Selected = true},
new SelectListItem { Text = "禁用", Value = "1" } };
%>//list儲存dropdownlist的預設值
<%=Html.DropDownList("state",list,Model.state) %> //state為實體的屬性,預設選中"啟用"
Html.DropDownList()從資料庫讀取值:
頁面代碼如下:
<%= Html.DropDownList("Category", ViewData["Categories"] as SelectList,"--請選擇--",new { @class = "my-select-css-class" } )%>
Controllers代碼:
public ActionResult Create()
{
List<Category> categories = categoryService.GetAll();
ViewData["Categories"] = new SelectList(categories, "Id", "Name");
return View();
}
public static string DropDownList(this HtmlHelper htmlHelper, string name)
{
IEnumerable<SelectListItem> selectData = htmlHelper.GetSelectData(name);
return htmlHelper.SelectInternal(null, name, selectData, true, false, null);
}
第一種方式:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "001", Value = "1", Selected = false });
items.Add(new SelectListItem() {Text = "002", Value = "2", Selected = false });
ViewData["items"] = items;
簡化後:
var items = new List<SelectListItem>()
{
(new SelectListItem() {Text = "001", Value = "1", Selected = false}),
(new SelectListItem() {Text = "002", Value = "2", Selected = false})
};
將items值給ViewData:
ViewData["items"] = items;
在aspx中這樣使用:
<%= Html.DropDownList("items") %>
產生的程式碼中,items將作為<select>標籤的name和id值。
public static string DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
{
return htmlHelper.DropDownList(name, selectList, null);
}
使用方法:
<%= Html.DropDownList("items", new List<SelectListItem>
{
(new SelectListItem() {Text = "001", Value = "1", Selected = false}),
(new SelectListItem() {Text = "002", Value = "2", Selected = false})
})%>
在這裡,不需要ViewData傳入值,第一個參數items作為標籤的name和id的值。items也可以是任意的字串。
public static string DropDownList(this HtmlHelper htmlHelper, string name, string optionLabel)
{
IEnumerable<SelectListItem> selectData = htmlHelper.GetSelectData(name);
return htmlHelper.SelectInternal(optionLabel, name, selectData, true, false, null);
}
使用方法和第一種原型相同,string optionLabel作為一個預設的空的選項。這樣可以完成加入不需要選取任何選項的情境。