Frage

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

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top