0

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!

Karl
  • 189
  • 2
  • 3
  • 16

2 Answers2

1

This answer shows how to do the selected value and validation: Html.EnumDropdownListFor: Showing a default text

With validation in MVC, you typically do this with an attribute in the model e.g. [Required]

Community
  • 1
  • 1
TeamTam
  • 1,598
  • 11
  • 15
  • Also a helpful response! The response from juunas, however, was excatly what I needed. – Karl Nov 12 '16 at 18:04
1

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.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • Looks like a winner - thanks! I had it set to [Required], but didn't have the Nullable<>. – Karl Nov 12 '16 at 18:02