扩展htmlhelper.DropDownListFor 支持list数据源和option增加属性
2016-04-13 15:06
190 查看
mvc自带的DropDownListFor数据源必须是IEnumerable<SelectListItem>。并且option不支持增加自定义属性。在使用bootstrap-select组件的时候,发现不是很好用。所以扩展了一下。
当然,因为场景的问题,我不需要group,不需要selected,所以这部分没有完成,且相应的重载方法也没有写。只有一个core方法,算是一个半成品吧。
View Code
调用方式:
顺便介绍一下bootstrap-select组件。bootstrap框架下面的下拉选择组件,支持下拉搜索选择,关键字可自定义。上面的我的例子就是一个地址选择例子,使用地址的全拼,首字母拼音搜索
具体例子参考官方地址。有详细说明和demo
官方地址:http://silviomoreto.github.io/bootstrap-select
git地址:https://github.com/silviomoreto/bootstrap-select
官方例子截图:
当然,因为场景的问题,我不需要group,不需要selected,所以这部分没有完成,且相应的重载方法也没有写。只有一个core方法,算是一个半成品吧。
public static MvcHtmlString DropDownListForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, object>> expression, Func<TModel, IEnumerable<TProperty>> options, Func<TProperty, string> optionText, Func<TProperty, string> optionValue, string optionLabel = null, Func<TProperty, IDictionary<string, object>> optionHtmlAttributes = null, IDictionary<string, object> htmlAttributes = null) { var tagNameAttr = ExpressionHelper.GetExpressionText(expression); TagBuilder tag = new TagBuilder("select"); if (htmlAttributes != null) tag.MergeAttributes(htmlAttributes); tag.MergeAttribute("name", tagNameAttr, true); tag.GenerateId(tagNameAttr); StringBuilder optionsHtml = new StringBuilder(); var os = options(htmlHelper.ViewData.Model); if (optionLabel != null) { TagBuilder tag3 = new TagBuilder("option"); tag3.SetInnerText(optionLabel); optionsHtml.AppendLine(tag3.ToString(TagRenderMode.Normal)); } foreach (var item in os) { TagBuilder tag2 = new TagBuilder("option"); tag2.SetInnerText(optionText(item)); if (optionHtmlAttributes != null) tag2.MergeAttributes(optionHtmlAttributes(item)); tag2.MergeAttribute("value", optionValue(item), true); var oHtml = tag2.ToString(TagRenderMode.Normal); optionsHtml.AppendLine(oHtml); } tag.InnerHtml = optionsHtml.ToString(); return new MvcHtmlString(tag.ToString(TagRenderMode.Normal)); }
View Code
调用方式:
depInfos:List<>
@Html.DropDownListForEx(p => p.DepCode, p => depInfos, p => p.Name, p => p.Id, "请选择", p => new Dictionary<string, object>() { { "data-tokens", p.NamePinYin+" "+p.NameFirstPinYin } }, new Dictionary<string, object> { { "class", "selectpicker" }, { "data-live-search", true } })
顺便介绍一下bootstrap-select组件。bootstrap框架下面的下拉选择组件,支持下拉搜索选择,关键字可自定义。上面的我的例子就是一个地址选择例子,使用地址的全拼,首字母拼音搜索
具体例子参考官方地址。有详细说明和demo
官方地址:http://silviomoreto.github.io/bootstrap-select
git地址:https://github.com/silviomoreto/bootstrap-select
官方例子截图:
相关文章推荐
- html学习之路——第一天(1)
- 关于html中的height、innerHeight、outerHeight区别
- 绿色简单的学校登录html页面
- float标签详细解读
- HTML页面中启动Activity
- HTML 5 服务器发送事件
- HTML表单中get 和post 的区别
- C# 正则获取html内容
- 网页五--html插入表格
- html学习_canvas
- 在浏览器中显示TXT 文本中的换行(html/txt)
- HDU-1088-Write a simple HTML Browser
- HTML 5 Web Storage 使用
- HTML 5 Web Workers
- 屏幕大小改变或首次加载计算html根元素 fontsize
- HTML学习之表格表单及框架介绍
- Html标签中thead、tbody、tfoot的作用
- HTML学习之网页制作基础和常用标签及标签属性
- HTML 5 应用程序缓存
- HTML 5 Web 存储