1

我有 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" })

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

4

2 回答 2

1

以下代码生成一个SelectListfrom 和enum

    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))
于 2013-07-15T16:47:30.113 回答
0

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

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();  
    }  
}  
于 2013-07-15T16:50:43.700 回答