一、非強類型:
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(),"請選擇")