下拉框Html.DropDownList 和DropDownListFor 的常用方法

 一、非強類型:
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(),"請選擇")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章