Karl Karl - 23 days ago 4
ASP.NET (C#) Question

How to add a default item to an EnumDropDownList in MVC?

I'm new to MVC, and am having trouble with something that would have been a piece of cake for me in webforms. So I've got a department dropdownlist, and the departments are found in an enum. So the dropdownlist in my view looks like this:

<div class="form-group">
@Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.Department, "Select a Department", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
</div>
</div>


Adding the "Select a Department" text does include that option in the dropdownlist, but when the page loads, rather than that option being selected, the first department in the enum is selected. How do I make it so that the "default" option is selected when the page loads?

I'm sure my next question would then be how to validate that some other item got selected (ie, required field validation).

Thanks!

Answer

Your model property is probably not Nullable. That means it will always be initialized to the first value of the enum.

If your model property looks like this:

public MyEnum { get; set; }

Change it to this:

[Required] //Require one of the values is selected i.e. value is not null
public Nullable<MyEnum> { get; set; }

This is a very general problem related to requiring value types have a value set. An easy way is to make it Nullable and check it is not null. As otherwise the value type will just have its default value.

Comments