English 中文(简体)
MVC3 C#
原标题:enum to dropdownlist MVC3 C#

I m目前利用这一系统,将一 en变成无线电控制。

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线上,我发现了一个错误。 基本上,Im没有以这种方法提供正确信息。 是否有人对此问题有任何了解?

最佳回答

你们可以使用静态帮助器,把遗体列入选择名单。

我在此 about:

http://jnye.co/Posts/4/creating-a-dropdown-list- from-an-enum-in-mvc-and-c%23”rel=“nofollow”http://jnye.co/Posts/4/creating-a-dropdown-list- from-an-enum-in-mvc%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();
    }
}

This helper will enable you to convert an enum to a select list in just two lines.

阁下:

ViewBag.TypeDropDown = EnumHelper.SelectListFor(field);

In your view:

@Html.DropDownList("TypeDropDown")
问题回答
public enum test
    {
        a = 0,
        b = 1
    }

then, put below in Html Extension

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>";

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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签