时间: 2020-11-22|60次围观|0 条评论

 
一、非强类型:

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

转载于:https://www.cnblogs.com/mfrbuaa/p/4078834.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/98631404

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《下拉框Html.DropDownList 和DropDownListFor 的经常用法
   

还没有人抢沙发呢~