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?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Alexander
  • 1,021
  • 6
  • 20
  • 38

1 Answers1

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);
    }
}
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
  • But this means I would have to introduce a new entry into my enum called PleaseSelect no? – J86 Mar 13 '17 at 13:13
  • See [this answer](https://stackoverflow.com/a/23085333/957950) for a good way to set an empty default option (hint: use a nullable enum). – brichins Aug 17 '17 at 16:40
  • how do you get the selected value in the controllre out of this enum on POST – Transformer Jan 09 '18 at 00:12