문제

I am trying to build a drop down list using enum. I tried the following, but do not know how to display it in view. I am using MVC framework

 public enum Condition
        {
            And,
            Or,
            Not,
        }

 private List<Condition> userTypes = Enum.GetValues(typeof(Condition)).Cast<Condition>().ToList();

       public List<Condition> UserType
       {
           get
           {
               return userTypes;
           }
           set
           {
               userTypes = value;
           }
       }

Is the above code right to display a simple drop down list? And how do I pass in it view to display drop down list. Thanks

도움이 되었습니까?

해결책

in your Action :

ViewData["ddl"] = userTypes.Select(t => new SelectListItem { Text = t.ToString(), Value = ((int)t).ToString() });

in your aspx :

<%=Html.DropDownList("ddl", ViewData["ddl"] as IEnumerable<SelectListItem>)%>

Rest of this is alright.

다른 팁

You suppose to return string list from property UserType not Condition type. Secondly property must is of readonly since enum is constant and user won`t going to change it. Lastly don't use variable, property itself handle this.

public List<string> UserType
{
   get
   {
      return Enum.GetNames(typeof(Condition)).ToList();
   }
}
  1. In your model add a List like:

     private List conditionList= Enum.GetValues(typeof(Condition))
                        .Cast()
                        .Select(e => new SelectListItem { Value = ((int)e).ToString(), Text      = e.ToString() }); 
    
  2. And Then just add this on your view

    @Html.EditorFor(m=>m.Condition,Model.conditionList)    
    

I believe that will make things more easier.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top