MVC - DropDownListFor枚举 - 设置默认值

时间:2014-09-20 05:44:36

标签: asp.net-mvc asp.net-mvc-4 enums

我的下拉列表可以正常使用以下代码: -

@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
    }

但是当它在View中显示时,我需要DropDown将---Select Month---显示为默认值。 这样我就可以在jQuery Script中检查所需的验证。

怎么做?

1 个答案:

答案 0 :(得分:2)

首先为你的枚举增加值

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

然后用:

装饰你的模型
[Required]
[Range(1, 12, ErrorMessage = "Select a month"))]
public StopMonth StopMonth { get; set; }

最后:

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