【问题标题】:Binding drop down list from Enum in c#在c#中从枚举绑定下拉列表
【发布时间】:2013-12-16 22:49:08
【问题描述】:

我有 Enum 类,我必须在 asp.net MVC4 中绑定下拉列表(使用 Razor 视图引擎)。我可以绑定下拉列表并可以在视图中显示。但我无法在编辑模式下显示所选项目。请任何人帮助我。我有以下代码

我的 ViewModel 类

public class UserViewModel
    {
 public string AccountId { get; set; }
        [Required]
        [Display(Name="First Name")]
        public String FirstName { get; set; }
        [Display(Name="Middle Name")]
        public String MiddleName { get; set; }
        [Required]
        [Display(Name="Last Name")]
        public String LastName { get; set; }
        public String UserRoles { get; set; }
} 

而枚举类是,

 public enum UserType // Office User Types
    {
        Officer = 1,
        Administrator = 2,
        Recruiter = 3
    }

我在我的控制器中使用以下代码,

Dictionary<string, string> rolename = Enum.GetValues(typeof(UserType))
   .Cast<UserType>()
   .Select(v => v.ToString())
   .ToDictionary<string, string>(v => v.ToString());
            ViewBag.Roles = rolename;
   return View();

我的观点是,

 @Html.DropDownListFor(model => model.UserRoles,new SelectList(ViewBag.Roles, "Key", "Value",Model.UserRoles.ToString()), new { id = "UserRoles" })

请帮助我我的错误是什么以及如何在编辑模式下在下拉列表中显示所选值。

【问题讨论】:

  • 你的模型中的UserRoles会不会是“Officer”、“Administrator”等,下拉的键是1、2、3等?

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


【解决方案1】:

以下代码从enumenum 生成一个SelectList

    public static IEnumerable<SelectListItem> EnumToSelectList(System.Type type)
    {
        var output = new List<SelectListItem>();
        foreach (int item in Enum.GetValues(type))
        {
            var si = new System.Web.Mvc.SelectListItem();
            si.Value = item.ToString();

            DisplayAttribute attr =(DataAnnotations.DisplayAttribute)
                type.GetMember(Enum.GetName(type, item))
                .First().GetCustomAttributes(typeof(DataAnnotations.DisplayAttribute), false)
                .FirstOrDefault();
            si.Text = (attr == null) ? Enum.GetName(type, item) : attr.Name;
            output.Add(si);
        }
        return output;

    }

从代码中可以看出,它还使用数据注释DisplayAttribute 来帮助防止enum 名称中的名称不是“用户友好的”。

这也可以抽象为HtmlHelper 的扩展,虽然不是必需的。

    public static IEnumerable<SelectListItem> EnumToSelectList(
        this HtmlHelper helper, 
        System.Type type)
    {
        return EnumToSelectList(type);
    }

用法很简单:

@Html.DropDownListFor(model => model.UserRoles, 
    Html.EnumToSelectList(typeof(UserType))

【讨论】:

    【解决方案2】:

    我创建了一个枚举助手,它可以从枚举中为您提供所需的选择列表。如果您有一个,它还将自动处理您选择的值。看看吧。

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

    如果您执行以下操作,它可能会解决您的问题:

    //In the controller
    ViewBag.DropDownList = EnumHelper.SelectListFor(myEnumValue);
    
    //In the view
    @Html.DropDownList("DropDownList") 
    
    /// OR
    @Html.DropDownListFor(m => m.DropDownList, ViewBag.DropDownList as IEnumerable<SelectListItem>)
    

    上面利用了这个助手

    public static class EnumHelper  
    {  
        //Creates a SelectList for a nullable enum value  
        public static SelectList SelectListFor<T>(T? selected)  
            where T : struct  
        {  
            return selected == null ? SelectListFor<T>()  
                                    : SelectListFor(selected.Value);  
        }  
    
        //Creates a SelectList for an enum type  
        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;  
        }  
    
        //Creates a SelectList for an enum value  
        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;  
        }   
    
        // Get the value of the description attribute if the   
        // enum has one, otherwise use the value.  
        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();  
        }  
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多