コントローラー内で月の日の選択リストを作成する構文に問題があります。月と年は機能しましたが、for ループが問題を引き起こしています。
ビジュアルスタジオが私に与えているエラーは、「無効な初期化子メンバー宣言子」と「現在のコンテキストにDaysという名前が存在しません」です。
ビューモデル
public class DateSearchViewModel
{
public int SelectedMonth { get; set; }
public IEnumerable<SelectListItem> Months { get; set; }
public int SelectedDay { get; set; }
public IEnumerable<SelectListItem> Days { get; set; }
public int SelectedYear { get; set; }
public IEnumerable<SelectListItem> Years { get; set; }
}
コントローラ
[ChildActionOnly]
public ActionResult _Header()
{
var DateVM = new DateSearchViewModel
{
//Set selected value of month.
SelectedMonth = 5,
Months = new List<SelectListItem>
{
new SelectListItem {Text = "Jan", Value = "1"},
new SelectListItem {Text = "Feb", Value = "2"},
new SelectListItem {Text = "Mar", Value = "3"},
new SelectListItem {Text = "Apr", Value = "4"},
new SelectListItem {Text = "May", Value = "5"},
new SelectListItem {Text = "Jun", Value = "6"},
new SelectListItem {Text = "Jul", Value = "7"},
new SelectListItem {Text = "Aug", Value = "8"},
new SelectListItem {Text = "Sep", Value = "9"},
new SelectListItem {Text = "Oct", Value = "10"},
new SelectListItem {Text = "Nov", Value = "11"},
new SelectListItem {Text = "Dec", Value = "12"},
},
//Set selected value of Day.
SelectedDay = 13,
Days = new List<SelectListItem>
{
for (var i = 1; i <= 31; i++)
{
Days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString()});
}
},
//Set selected value of Year.
SelectedYear = 2010,
Years = new List<SelectListItem>
{
new SelectListItem {Text = "2009", Value = "2009"},
new SelectListItem {Text = "2010", Value = "2010"},
new SelectListItem {Text = "2011", Value = "2011"},
new SelectListItem {Text = "2012", Value = "2012"},
}
};
return PartialView(DateVM);
}
ビューモデル:
@Html.DropDownListFor(x => x.SelectedMonth, Model.Months) / @Html.DropDownListFor(x => x.SelectedDay, Model.Days) / @Html.DropDownListFor(x => x.SelectedYear, Model.Years)