MVC :Razor 中DropDownListFor写法

页面中常用到DropDownLisFor,

今天在使用layui UI时,刚好遇到一个问题,于是在此作一个记录!

首先,看下它在MVC中的定义:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes);

  四种属性代表四重载:

  1. expression ,从前面的Expression<Func<TModel,TProperty>>表达式中,清楚知道它的用法就是获取某个属性的值(可以是字符串或者其它类型),如:
     model=>model.Username;

     

  2. IEnumerable<SelectListItem>,获取的是IEnumerable的SelectListItem选项,通常就是绑定DropDown(HTML中Select)下拉数据,如:
    ViewData["Username"]  as IEnumerable<SelectListItem>;

     

  3. optionLabel,DropDown默认选中项,这个就不用太多解释了;
  4. htmlAttributes,设置Html 常用属性,如 htmlAttributes: new { @id="UserId",@Value="123" @lay_search = ""} 
    htmlAttributes: new { @id="UserId",@Value="123" @lay_search = ""} 

     

简单介绍了下它的4重属性,其它扩展就不说了。

实例为:

@Html.DropDownListFor(model => model.UserName, (IEnumerable<SelectListItem>)ViewData["Username"],"请选择",htmlAttributes:new {@class="form-select" @lay_search=""})

 

下面,说下htmlAttributes重点注意项:(其实上面有标红色)

  1. htmlAttributes @标识属性有区分大小写的哦,比如上面的@Value 写成value就无效;
  2. @名称不支持"-" 横杠(破折号),要写成"_"下划线(这个就是我今天用layui时发现的问题)

 

 

posted @ 2020-07-31 11:28  Luckyfish小文  阅读(275)  评论(0编辑  收藏  举报