Reputation: 3289
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
Upvotes: 0
Views: 68
Reputation: 510
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() });
And Then just add this on your view
@Html.EditorFor(m=>m.Condition,Model.conditionList)
I believe that will make things more easier.
Upvotes: 1
Reputation: 3966
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.
Upvotes: 2
Reputation: 3834
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();
}
}
Upvotes: 1