For MVC v5.1 use Html.EnumDropDownListFor
@Html.EnumDropDownListFor(
x => x.YourEnumField,
"Select My Type",
new { @class = "form-control" })
For MVC v5 use EnumHelper
@Html.DropDownList("MyType",
EnumHelper.GetSelectList(typeof(MyType)) ,
"Select My Type",
new { @class = "form-control" })
For MVC 5 and lower
I rolled Rune's answer into an extension method:
namespace MyApp.Common
{
public static class MyExtensions{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
where TEnum : struct, IComparable, IFormattable, IConvertible
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name", enumObj);
}
}
}
This allows you to write:
ViewData["taskStatus"] = task.Status.ToSelectList();
by using MyApp.Common
I think this is what the model does in the MVC pattern. Why you don't use a typed view instead?
I believe you just make things more complicated by introducing yet another dependency between the controller and the view. I don't see any specific benefit in terms of line of code or something like that. You have to declare the existence of the variable, which you'd also do in the model class definition.
You don't get any significant advantage by doing so.
Best Answer
Just in header:
Then you can access your strongly typed model like this:
"Model" property is automatically cast to your type.