我的语法在我的控制器内创建一个月内几天的选择列表时遇到了一些问题。我得到了几个月和几年的工作,但是 for 循环给我带来了一些麻烦。
Visual Studio 给我的错误是:“Invalid initializer member declarator”和“名称 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)