您的位置:首页 > Web前端 > HTML

扩展htmlhelper.DropDownListFor 支持list数据源和option增加属性

2016-04-13 15:06 190 查看
mvc自带的DropDownListFor数据源必须是IEnumerable<SelectListItem>。并且option不支持增加自定义属性。在使用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

官方例子截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: