2014-09-20 112 views
0

我的下拉正常工作与下面的代码: -MVC - DropDownListFor枚举 - 设置默认值

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

但是,当它显示在视图中,我需要下拉菜单显示---Select Month---为默认值。 这样我就可以在jQuery Script中检查所需的验证。

如何做到这一点?

+0

是'StopMonth'可空? – 2014-09-20 05:47:15

+0

是的。可以将'null'设置为'StopMonth'。 – Anup 2014-09-20 05:51:12

+1

您可以使用具有第三个参数的过载为“--Select month--”[请参阅文档](http://msdn.microsoft.com/en-us/library/ee703567(v = vs.118))。 ASPX)。不确定,但我认为你还需要设置'SelectList'的'Value'和'Text'属性 – 2014-09-20 05:56:37

回答

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"}) 
+0

Thankx ..!很容易。! – Anup 2014-09-23 04:56:16