1

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 ?

1
  • You could always use javascript to update the value attribute of each option, (or write your own extension method) Commented Oct 2, 2017 at 7:51

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's a solution but it can be very surly if we have several enum in model, i prefer to write a helper extension
1

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(); } 
}

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.