2012-06-16 42 views
2

我在我的模型中有這個數組屬性,並希望在我的視圖中看到它作爲下拉列表。這裏的數組屬性:如何在我的視圖中顯示數組模型屬性作爲列表?

public string[] weekDays = new string[5] { "monday", "Tuesday", "Wednesday", "Thursday", "Friday" }; 

public string[] WeekDays 
{ 
    get { return weekDays; } 
} 

我已經找了幾個小時沒有簡單的解釋或例子。請幫忙。

回答

1

下面是我解決它的方法。

@{ 
    var wekdys = new Enrollment(); 
    @Html.DropDownList("weekDays", wekdys.WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString() })) 
} 

這讓我有foreach循環

3

您可以使用DropDownList() html幫手。

Html.DropDownList("weekDays", 
        Model.WeekDays.Select(s => new SelectListItem { Text = s })) 

如果你想讀選定的值,你可以使用DropDownListFor()幫手。

Html.DropDownListFor(model => model.SelectedWeekDay, //a property to assign the value 
           Model.WeekDays.Select(s => new SelectListItem { Text = s, Value = s })) 
+0

這個工作以外的一個DropDownList:@ Html.DropDownList( 「平日」,item.WeekDays.Select(S =>新SelectListItem {文本= S。 ToString(),Value = s.ToString()})) – CloudyKooper

+0

這工作:@ Html.DropDownList(「weekDays」,item.WeekDays.Select(s => new SelectListItem {Text = s.ToString(),Value = s .ToString()}))但只在foreach循環內的表中,但不在循環外。我無法使用item.WeekDays.Select或Model.Enrollments.Select訪問weekDays屬性。我如何使foreach循環之外的下拉列表? – CloudyKooper

+0

如果這就是你的意思,你仍然可以在lambda表達式中訪問Model實例。 –

相關問題