2014-09-20 113 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