Im having some trouble with my syntax creating a select list for days in a month inside of my controller. I got the Months and Years working but the for loop is causing me some trouble.
The errors visual studio is giving me is: “Invalid initializer member declarator” and “The name Days does not exist in the current context.”
ViewModel
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; }
}
Controller
[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);
}
ViewModel:
@Html.DropDownListFor(x => x.SelectedMonth, Model.Months) / @Html.DropDownListFor(x => x.SelectedDay, Model.Days) / @Html.DropDownListFor(x => x.SelectedYear, Model.Years)
You can’t put a loop in an initializer:
So instead just instantiate it and use the loop later: