c# - 枚举到下拉列表 MVC3 C#

标签 c# asp.net-mvc asp.net-mvc-3

我目前正在使用它来将枚举转换为 radio 控件,

public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression)
{
    var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    var sb = new StringBuilder();
    var enumType = metaData.ModelType;
    foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
    {
        var value = (int)field.GetValue(null);
        var name = Enum.GetName(enumType, value);
        var label = name;
        foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
        {
            label = currAttr.Name;
            break;
        }

        var id = string.Format(
            "{0}_{1}_{2}",
            htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
            metaData.PropertyName,
            name
        );
        var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
        sb.AppendFormat(
            "<label for=\"{0}\">{1}</label> {2}",
            id,
            HttpUtility.HtmlEncode(label),
            radio
        );
    }
    return MvcHtmlString.Create(sb.ToString());
}

但是当尝试将其调整为枚举到下拉列表时:

public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(
   this HtmlHelper<TModel> htmlHelper,
   Expression<Func<TModel, TProperty>> expression)
{
     var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

     var sb = new StringBuilder();
     var enumType = metaData.ModelType;
     sb.Append("<select name=\"" + metaData.PropertyName + "\" id=\"" + metaData.PropertyName + "\" > ");
     foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
     {
          var value = (int)field.GetValue(null);
          var name = Enum.GetName(enumType, value);
          var label = name;

          foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
          {
                label = currAttr.Name;
                break;
          }

          var id = string.Format(
                    "{0}_{1}_{2}",
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                    metaData.PropertyName,
                    name
                );
          var listitem = htmlHelper.DropDownListFor(expression, name, new { id = id }).ToHtmlString();
          sb.AppendFormat(
                    "<option value=\"{0}_{1}\">{2}</option> ",
                    id,
                    listitem,
                    HttpUtility.HtmlEncode(label)
                );
     }
     sb.Append("</select>");
     return MvcHtmlString.Create(sb.ToString());
}

我在 var listitem = htmlHelper.DropDownListFor 行中收到错误。基本上我没有在方法中提供正确的信息。谁能阐明这个问题?

最佳答案

您可以使用将枚举转换为选择列表的静态助手。

我在这里写了博客:

http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

助手(如果存在,这将获取描述属性的值):

public static class EnumHelper
{
    public static SelectList SelectListFor<T>(T? selected)
        where T : struct
    {
        return selected == null ? SelectListFor<T>()
                                : SelectListFor(selected.Value);
    }

    public static SelectList SelectListFor<T>() where T : struct
    {
        Type t = typeof (T);
        if (t.IsEnum)
        {
            var values = Enum.GetValues(typeof(T)).Cast<Enum>()
                             .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

            return new SelectList(values, "Id", "Name");
        }
        return null;
    }

    public static SelectList SelectListFor<T>(T selected) where T : struct 
    {
        Type t = typeof(T);
        if (t.IsEnum)
        {
            var values = Enum.GetValues(t).Cast<Enum>()
                             .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

            return new SelectList(values, "Id", "Name", Convert.ToInt32(selected));
        }
        return null;
    }

    public static string GetDescription<TEnum>(this TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        if (fi != null)
        {
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);

            if (attributes.Length > 0)
                return attributes[0].Description;
        }

        return value.ToString();
    }
}

此帮助程序将使您能够在两行内将枚举转换为选择列表。

在你的 Controller 中:

ViewBag.TypeDropDown = EnumHelper.SelectListFor(field);

在你看来:

@Html.DropDownList("TypeDropDown")

关于c# - 枚举到下拉列表 MVC3 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877547/

相关文章:

asp.net-mvc - 如何从 ASP.NET MVC 中的 View 中找出当前资源和 Controller 名称

asp.net-mvc-3 - 如何在 Asp.Net MVC3 中返回 Json 结果时填充 WebGrid

c# - 在 LINQ to Entities 上调用自定义(格式化)方法

c# - C# linq 是否有类似于 SummaryStatistics 的东西?

c# - 如何将元素移动到 div 中的左侧?

c# - MVVM ListBox 鼠标单击不起作用,但 MouseDoubleClick 起作用

c# - 将 MVC DropDownlistFor() 绑定(bind)到模型的导航属性

c# - ASP.NET MVC - FormsAuthentication.SetAuthCookie() 和 Roles IsUserInRole - 奇怪的行为

c# - 集成测试基于 ASP.NET MVC 的 api 的正确方法是什么?

c# - 如何设置MediaElement的位置?