【问题标题】:Fill in a DropDownListFor with the Display tag in ASP.NET MVC3在 ASP.NET MVC3 中使用 Display 标签填充 DropDownListFor
【发布时间】:2013-11-27 19:15:00
【问题描述】:

我正在尝试为我的 ASP.NET MVC3 网站编写一个帮助程序,它将能够返回一个新的 SelectList,其中包含一个枚举的所有 Description 属性标记

例如,使用以下枚举:

public enum Test
{
    [Display(Name = "Membre 1")]
    Member1,

    [Display(Name = "Membre 2")]
    Member2
}

我希望能够用类似的内容填写DropDownListFor

@Html.DropDownListFor(m => m.MyTest, MyHelper(Test))

MyTestTest 变量)。

我希望我的DropDownList 包含:

  • 成员 1
  • 成员2
  • 我曾经使用过这个工作助手:

    public static string GetEnumDescription(this Enum value)
    {
        Type enumType = value.GetType();
        var enumValue = Enum.GetName(enumType, value);
        MemberInfo member = enumType.GetMember(enumValue)[0];
    
        var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
        var outString = ((DisplayAttribute)attrs[0]).Name;
    
        if (((DisplayAttribute)attrs[0]).ResourceType != null)
        {
            outString = ((DisplayAttribute)attrs[0]).GetName();
        }
    
        return outString;
    }
    

    ...但我无法在 SelectList 中使用它

    如何修改它以直接将其“合并”到我的 @Html.DropDownListFor 助手中?

    我在网上看到过一些帮手,尤其是herehere,但没有人适合我。有没有人能够分享一个 shortelegant 帮助器,它返回 Enum 成员的所有 Display 属性,以便将它们放入 DropDownListFor 中?

    【问题讨论】:

      标签: asp.net-mvc asp.net-mvc-3 enums helper html.dropdownlistfor


      【解决方案1】:

      以下是我使用的。这是我曾经在网上找到的东西的略微修改版本。我会在应得的地方给予信任,但我不记得我最初在哪里找到它:

      public static SelectList ToSelectList(this Enum enumeration)
      {
          var list = (from Enum d in Enum.GetValues(enumeration.GetType())
                      select new { Value = Enum.GetName(enumeration.GetType(), d), Text = d.GetDescription() }).ToList();
      
          var selectedValue = (int)Enum.Parse(enumeration.GetType(), Enum.GetName(enumeration.GetType(), enumeration));
      
          return new SelectList(list, "Value", "Text");
      }
      
      public static string GetDescription(this Enum en)
      {
          Type type = en.GetType();
          System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
      
          if (memInfo != null && memInfo.Length > 0)
          {
              object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
      
              if (attrs != null && attrs.Length > 0)
                  return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
          }
      
          return en.ToString();
      }
      

      在您看来,您会使用它:

      @Html.DropDownListFor(m => m.MyEnumProperty, Model.MyEnumProperty.ToSelectList())
      

      【讨论】:

      • 我只是尝试你的答案,因为它是第一个。我在 Tools\Helpers\AttributesHelperExtensions.cs 中为您创建了两个方法,这是一个静态类,我在其中编写了一些帮助程序。在我看来,ToSelectList() 无法识别...是否有一些使用或其他我忘记的东西?
      • 对不起。您还需要在视图顶部有一个 @using 指令,指向您的扩展程序。就像在 C# 代码中的其他任何地方一样,您必须让编译器知道在哪里可以找到该方法。
      【解决方案2】:

      对于实现 Enum 类型的数据,我认为最简单的方法是使用自定义 Enum 助手和模板。下面是我如何在我的项目中实现它们。

      1) 创建枚举助手

      public static class EnumHelper
          {
              public static IEnumerable<SelectListItem> GetItems(this Type enumType, int? selectedValue)
              {
                  if (!typeof (Enum).IsAssignableFrom(enumType))
                  {
                      throw new ArgumentException("Type must be an enum");
                  }
                  string[] names = Enum.GetNames(enumType);
                  IEnumerable<int> values = Enum.GetValues(enumType).Cast<int>();
      
                  IEnumerable<SelectListItem> items = names.Zip(values, (name, value) =>
                      new SelectListItem
                      {
                          Text = GetName(enumType, name),
                          Value = value.ToString(),
                          Selected = value == selectedValue
                      }
                      );
                  return items;
              }
              // Get Display Name
              private static string GetName(Type enumType, string name)
              {
                  string result = name;
                  DisplayAttribute attribute = enumType.GetField(name)
                      .GetCustomAttributes(false)
                      .OfType<DisplayAttribute>()
                      .FirstOrDefault();
                  if (attribute != null)
                  {
                      result = attribute.GetName();
                  }
                  return result;
              }
      
              public static string GetItemName(this Type enumType, int selectedValue)
              {
                  if (!typeof (Enum).IsAssignableFrom(enumType))
                  {
                      throw new ArgumentException("Type must be an enum");
                  }
                  var itemName = GetName(enumType, Enum.GetNames(enumType)[selectedValue]);
                  return itemName;
              }
          }
      

      2) 在共享文件夹中创建文件夹调用“DisplayTemplates”。

      3) 在“DisplayTemplates”内创建视图。视图如下所示:

      @using Demo.Web.Helper
      @{
          var itemName = typeof(Test).GetItemName((int)Model);
      }
      

      4) 在共享文件夹中创建 floder 调用“EditorTemplates”。

      5) 在“EditorTemplates”中创建视图。视图如下所示:

      @using Demo.Web.Helper
      @{
          var items = typeof (Test).GetItems((int?)Model);
      }    
      @Html.DropDownList("",items)
      

      到这里你已经完成了所有的助手和模板,可以使用了。当你想实现 Enum Type 数据时,只需像下面这样使用它:

      型号

      public class MyModel
      {
          public int Id { get; set; }
          //
          public Test Test { get; set; } 
      }
      

      查看

       @Html.DisplayFor(m => m.Test)
       or
       @Html.EditorFor(m => m.Test)
      

      希望对你有帮助。

      【讨论】:

      • 这也是我一直在寻找的。​​span>
      • 抱歉回答晚了。我真的很喜欢你的解决方案,但我已经实现了 Chris 的解决方案,它与我所做的最接近,并且需要较少的修改才能放入我自己的项目中。但是,我赞成您的回答;-) 再次感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多