Anup
Anup

Reputation: 9738

MVC - DropDownListFor Enum - Set Default Value

My Dropdown works properly with following code :-

@Html.DropDownListFor(model => model.StopMonth, Enum.GetNames(typeof(Models.InputMonths)).Select(e => new SelectListItem { Text = e }), new { @class = "form-control"})

public enum InputMonths
    {
        January,
        February,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    }

But when it is displayed in View, I need DropDown to display ---Select Month--- as default value. So that i can check required validation in jQuery Script.

How to do this?

Upvotes: 0

Views: 4640

Answers (1)

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11544

First add value to your enum

public enum InputMonths {
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    .
    .
    .        
}

Then decorate your Model with:

[Required]
[Range(1, 12, ErrorMessage = "Select a month"))]
public StopMonth StopMonth { get; set; }

And finally:

@Html.DropDownListFor(
    model => model.StopMonth,
    Enum.GetNames(typeof(Models.InputMonths))
        .Select(e => new SelectListItem { Text = e }),
    "-- Select a month --",
    new { @class = "form-control"})

Upvotes: 2

Related Questions