2013-05-17 33 views
0

數據的名單我想有一個可以在視圖上視圖模型和下拉菜單中使用的模型數據的靜態列表。我希望能夠使用它以這種方式在我的控制器:靜態下拉列表中MVC

MaintenanceTypeList = new SelectList(g, "MaintenanceTypeID", "MaintenanceTypeName"), 

和訪問它在我的觀點是這樣的:

@Html.LabelFor(model => model.MaintenanceTypeID) 
@Html.DropDownListFor(x => x.MaintenanceTypeID, Model.MaintenanceTypeList, "-- Select --", new { style = "width: 150px;" }) 
@Html.ValidationMessageFor(x => x.MaintenanceTypeID) 

我目前使用的存儲庫模式對數據庫中的數據,但不希望將這些數據放入數據庫中,因爲它永遠不會改變。儘管我仍然希望它在模型中。基本上,我的下拉列表中應具備以下特徵:使用模型靜態列表的

Value    Text 
------------------------------------- 
Calibration   Calibration 
Prevent    Preventative Maintenance 
CalibrationPrevent PM and Calibration 

任何幫助或例子/ OOP認識

回答

1

您可以使用列表初始化:

public static SomeHelperClass{ 
    public static List<SelectListItem> MaintenanceTypeList { 
    get { 
    return new List<SelectListItem> 
     { new SelectListItem{Value = "Calibration", Text = "Calibration"} 
     ,new SelectListItem{ Value = "Prevent", Text = "Preventative Maintenance" } 
     ,etc. 
     }; 
    } 
    } 
} 

希望我沒有錯過某處的花括號。你可以谷歌「C#列表初始值設定程序」更多的例子。我不記得把我的頭實際收集到的一個SelectListCollection是什麼頂部,但我知道有一個允許列表,我往往只是有keyvaluepairs或其他東西的集合DropDownList中的過載,然後在我的查看我將其轉換爲SelectListItems:someList.Select(i => new SelectListItem { Value = i.Key, Text = i.Value })

注意,另一種選擇是把自己的價值觀枚舉。然後,您可以使用Description屬性上的每個枚舉值:

enum MaintenanceType { 
    [Description("Calibration")] 
    Calibration = 1, 

    [Description("Preventative Maintenance")] 
    Prevent = 2 
} 

然後,你可以做這樣的事情

Enum.GetValues(typeof(MaintenanceType)).Select(m=>new SelectListItem{ Value = m, Text = m.GetDescription()}).ToList() 

最後一行是有點偏離頭部的頂部,所以希望我沒有」不要犯錯誤。我覺得像一個枚舉更適合你想要做的事情。

+0

謝謝!我對你的第一個建議採取了非常類似的路線,所以我將其標記爲答案。我在這裏找到了解決方案:http://www.dotnetcurry.com/ShowArticle.aspx?ID=584 – steveareeno