You can use this example.....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Profile.Data.Enum
{
public enum EfficiencyType
{
Good = 1,
Excelent = 2,
Better = 3
}
}
extension method is....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Profile.Web.HtmlHelper
{
public static class EnumDropDownList
{
public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement)
{
var typeOfProperty = modelExpression.ReturnType;
if (!typeOfProperty.IsEnum)
throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty));
var enumValues = new SelectList(Enum.GetValues(typeOfProperty));
return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement);
}
}
}
and the html is....
@Html.DropDownListFor(model => model.EfficiencyType, new SelectList(Enum.GetValues(typeof(EfficiencyType)), Model.EfficiencyType), "--Select--")
I found a way simpler solution for this here:
http://coding-in.net/asp-net-mvc-3-method-extension/
using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace EnumHtmlHelper.Helper
{
public static class EnumDropDownList
{
public static HtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> modelExpression, string firstElement)
{
var typeOfProperty = modelExpression.ReturnType;
if(!typeOfProperty.IsEnum)
throw new ArgumentException(string.Format("Type {0} is not an enum", typeOfProperty));
var enumValues = new SelectList(Enum.GetValues(typeOfProperty));
return htmlHelper.DropDownListFor(modelExpression, enumValues, firstElement);
} } }
One line in razor will do it:
@Html.DropDownListFor(model => model.State, new SelectList(Enum.GetValues(typeof(MyNamespace.Enums.States))))
You can also find code for doing it with an extension method in the linked article.