I have an enum like :
public enum StateEnum
{
Updated = 0,
Pending = 1,
Failed = 2
}
The helper function @Html.EnumDropDownListFor(model => Model.State, "States")
is rendering :
<select id="State" name="State">
<option value="0">Updated</option>
<option value="1">Pending</option>
<option value="2">Failed</option>
</select>
My question is : how to have an enum string value in the option
value attribute instead of the integer ? Like :
<select id="State" name="State">
<option value="Updated">Updated</option>
<option value="Pending">Pending</option>
<option value="Failed">Failed</option>
</select>
(it would be more user-friendly in the next page Url)
I could rewrite the Html.EnumDropDownListFor
function in a htmlhelper extensions, but there is no better solution ?
With Andy's anwser, i wrote a helper but not sure it's the best way to do that. If any body have a better solution
public static MvcHtmlString EnumDropDownListWithStringFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes)
{
var selectListItem = Enum.GetNames(Nullable.GetUnderlyingType(typeof(TEnum))).Select(p => new SelectListItem() { Value = p, Text = p }).ToList();
return SelectExtensions.DropDownListFor(htmlHelper, expression, selectListItem, optionLabel, htmlAttributes);
}