Reputation: 2748
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 ?
Upvotes: 1
Views: 1316
Reputation: 2748
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);
}
Upvotes: 1
Reputation: 35222
You can create a SelectList
as Andy suggested or you can have a StateString
property with a getter like this:
public StateEnum State { get; set; }
public string StateString
{
get { return State.ToString(); }
}
or if State
is the string property, then bind StateEnum
in the EnumDropDownListFor
and change model to:
public StateEnum StateEnum { get; set; }
public string State
{
get { return StateEnum.ToString(); }
}
Upvotes: 1
Reputation: 3002
You can get all the values of the enum as strings by using Enum.GetNames
. You would then pass this list into the model and the dropdown would be created using @Html.DropDownListFor(x => x.Test, new SelectList(Model.Values))
.
You can see this in the following fiddle: https://dotnetfiddle.net/ynK4ss
Upvotes: 2