[英]adding a attributes to a custom html helper for drop down list
我在這里實現了該解決方案: http : //www.spicelogic.com/Journal/ASP-NET-MVC-DropDownListFor-Html-Helper-Enum-5
它只是從枚舉成員中創建一個下拉列表。 但是,我想將名稱與下拉列表相關聯,如下所示:
@Html.TextBox("username", Model.Username, new { id = "username" })
為了說明這一點,我想以這種方式使用它:
@Html.DropDownListFor(m => m.FavoriteColor, new { id = "username" } )
我怎樣才能做到這一點? 如何擴展EnumEditorHtmlHelper類的Extention方法?
這是EnumEditorHtmlHelper的定義:
namespace LojmanMVC.WebUI.Static
{
public static class EnumEditorHtmlHelper
{
/// <summary>
/// Creates the DropDown List (HTML Select Element) from LINQ
/// Expression where the expression returns an Enum type.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString MyEnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
where TModel : class
{
TProperty value = htmlHelper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(htmlHelper.ViewData.Model);
string selected = value == null ? String.Empty : value.ToString();
return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
}
/// <summary>
/// Creates the select list.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="selectedItem">The selected item.</param>
/// <returns></returns>
private static IEnumerable<SelectListItem> createSelectList(Type enumType, string selectedItem)
{
return (from object item in Enum.GetValues(enumType)
let fi = enumType.GetField(item.ToString())
let attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault()
let title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description
select new SelectListItem
{
Value = item.ToString(),
Text = title,
Selected = selectedItem == item.ToString()
}).ToList();
}
}
}
提前致謝。
您可以使用相同的方法執行此操作,但是它需要second parameter
third parameter
是SelectListItems
的collection
, third parameter
用於custom
屬性。
@Html.DropDownListFor(m => m.FavoriteColor, (IEnumerable<SelectListItem>)ViewBag.Colors, new {id="username" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.