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();
}
}
In your model add a List like:
\n private List conditionList= Enum.GetValues(typeof(Condition)) \n .Cast() \n .Select(e => new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }); \n
And Then just add this on your view
\n@Html.EditorFor(m=>m.Condition,Model.conditionList) \n
I believe that will make things more easier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.