mvc自帶的DropDownListFor資料源必須是IEnumerable<SelectListItem>。并且option不支援增加自定義屬性。在使用bootstrap-select元件的時候,發現不是很好用。是以擴充了一下。
當然,因為場景的問題,我不需要group,不需要selected,是以這部分沒有完成,且相應的重載方法也沒有寫。隻有一個core方法,算是一個半成品吧。

1 public static MvcHtmlString DropDownListForEx<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
2 Expression<Func<TModel, object>> expression, Func<TModel, IEnumerable<TProperty>> options,
3 Func<TProperty, string> optionText, Func<TProperty, string> optionValue, string optionLabel = null,
4 Func<TProperty, IDictionary<string, object>> optionHtmlAttributes = null, IDictionary<string, object> htmlAttributes = null)
5 {
6
7 var tagNameAttr = ExpressionHelper.GetExpressionText(expression);
8 TagBuilder tag = new TagBuilder("select");
9 if (htmlAttributes != null)
10 tag.MergeAttributes(htmlAttributes);
11 tag.MergeAttribute("name", tagNameAttr, true);
12 tag.GenerateId(tagNameAttr);
13
14 StringBuilder optionsHtml = new StringBuilder();
15 var os = options(htmlHelper.ViewData.Model);
16 if (optionLabel != null)
17 {
18 TagBuilder tag3 = new TagBuilder("option");
19 tag3.SetInnerText(optionLabel);
20 optionsHtml.AppendLine(tag3.ToString(TagRenderMode.Normal));
21 }
22
23 foreach (var item in os)
24 {
25 TagBuilder tag2 = new TagBuilder("option");
26 tag2.SetInnerText(optionText(item));
27 if (optionHtmlAttributes != null)
28 tag2.MergeAttributes(optionHtmlAttributes(item));
29 tag2.MergeAttribute("value", optionValue(item), true);
30 var oHtml = tag2.ToString(TagRenderMode.Normal);
31 optionsHtml.AppendLine(oHtml);
32 }
33
34 tag.InnerHtml = optionsHtml.ToString();
35 return new MvcHtmlString(tag.ToString(TagRenderMode.Normal));
36 }
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
官方例子截圖: