枚举到下拉列表MVC3 C#

时间:2012-01-16 08:53:06

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

我目前正在使用它将枚举变成无线电控制,

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行中收到错误消息。基本上我没有在方法中提供正确的信息。任何人都可以解释这个问题吗?

3 个答案:

答案 0 :(得分:5)

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

我在这里写了博客:

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

帮助程序(如果存在,将获取description属性的值):

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();
    }
}

这个助手可以让你只用两行将枚举转换为选择列表。

在您的控制器中:

ViewBag.TypeDropDown = EnumHelper.SelectListFor(field);

在您看来:

@Html.DropDownList("TypeDropDown")

答案 1 :(得分:1)

public enum test
    {
        a = 0,
        b = 1
    }

然后,将下面的内容放在Html扩展

var options = Enum.GetValues(typeof(test))// u can pass type as parameter
.OfType<object>()
.Select(each => new {key = Enum.GetName(typeof(test), each), value = each})
.Select(each => string.Format("<option value=\"{1}\">{0}</option>", HttpUtility.HtmlEncode(each.key), each.value))
.Aggregate((cur, nex) => cur + nex);

return "<select name=...>"+options+"</select>";

答案 2 :(得分:0)


public class EnumExtensions
  {
    public static IEnumerable GetEnumSelectList()
    {
      return
        new SelectList(
          Enum.GetValues(typeof(T)).Cast().Select(
            x =>
            new
            {
              Value = x.ToString(),
              Text = x.ToString()
            }).ToList(),
        "Value",
        "Text");
    }
  }