標籤:
一、非強型別:
Controller:
ViewData["AreId"] = from a in rp.GetArea()
select new SelectListItem {
Text=a.AreaName,
Value=a.AreaId.ToString()
};
View:
@Html.DropDownList("AreId")
還能夠給其加上一個預設選項:@Html.DropDownList("AreId", "請選擇");
二、強型別:
DropDownListFor經常使用的是兩個參數的重載,第一參數是產生的select的名稱,第二個參數是資料,用於將綁定資料來源至DropDownListFor
Modle:
public class SettingsViewModel
{
Repository rp =new Repository();
public string ListName { get; set; }
public IEnumerable<SelectListItem> GetSelectList()
{
var selectList = rp.GetArea().Select(a => new SelectListItem {
Text=a.AreaName,
Value=a.AreaId.ToString()
});
return selectList;
}
}
Controller:
public ActionResult Index()
{
return View(new SettingsViewModel());
}
View:
@model Mvc3Applicationtest2.Models.SettingsViewModel
@Html.DropDownListFor(m=>m.ListName,Model.GetSelectList(),"請選擇")
下拉框Html.DropDownList 和DropDownListFor 的經常用法