MvcDropDownList 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(),"请选择")

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-29
  • 2022-12-23
  • 2021-12-22
  • 2021-07-06
  • 2021-08-06
猜你喜欢
  • 2022-12-23
  • 2022-01-24
  • 2021-06-02
  • 2022-12-23
  • 2021-07-19
  • 2021-12-16
  • 2021-05-09
相关资源
相似解决方案