2

I am using EnumDropDownListFor in ASP.NET MVC:

 @Model.PhoneNumberType

 @Html.EnumDropDownListFor(model => model.PhoneNumberType, new {@class = "form-control"})

This does not pre-select the value of the enum in the drop down list. If I just Display the enum value it will Show the right enum value. The DropDown is always set to the first value in the drop down, but not to the value of the enum field.

How can I configure EnumDropDownListFor to pre-select the drop down with the value of the enum field?

1 Answer 1

5

The only thing you should do, is to set the enum value when you are passing your model.

A little example (Test2 ll be selected by default) :

Model

    public class ModelTest
    {
        public EnumTest EnumTest { get; set; }
    }

    public enum EnumTest
    {
        Test1,
        Test2,
        Test3
    }

View :

@model WebApplication3.Models.ModelTest

<div>
    @Html.EnumDropDownListFor(model => model.EnumTest, new { @class = "form-control" })
</div>

Controller :

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        ModelTest model = new ModelTest {EnumTest = EnumTest.Test2};
        return View("View",model);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

But this means I would have to introduce a new entry into my enum called PleaseSelect no?
See this answer for a good way to set an empty default option (hint: use a nullable enum).
how do you get the selected value in the controllre out of this enum on POST

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.