将属性添加到自定义html帮助器以获取下拉列表

时间:2016-01-12 16:13:35

标签: asp.net-mvc enums extension-methods

我在这里实施了解决方案: 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();
    }
}

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用相同的方法执行此操作,但需要second parameter collection SelectListItemsthird parameter适用于您的custom属性。

@Html.DropDownListFor(m => m.FavoriteColor, (IEnumerable<SelectListItem>)ViewBag.Colors, new {id="username" })