I researched this problem on this site and found several similar questions. I tried all of the suggestions offered but apparently, there's something about my implementation or my understanding of the explanations that causes those solutions to not work. I would appreciate some guidance on how to fix this problem.
My project consists of the following ViewModel:
public SelectList MonthList { get; set; }
public SelectList ReverseMonthsLists()
{
var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });
for (int i = 1; i < stringViewOfDates.Count(); i++)
{
list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
}
var selectList = new SelectList(list);
return selectList;
}
public static IEnumerable<DateTime> GetDates()
{
DateTime startDate = new DateTime(2017, 6, 1).Date;
var currentDate = DateTime.Now.Date;
int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
if (numberOfMonthsToShow == 0)
numberOfMonthsToShow = 1;
var dates = new List<DateTime>(numberOfMonthsToShow);
for (int i = 0; i < numberOfMonthsToShow; i++)
{
dates.Add(currentDate);
currentDate = currentDate.AddMonths(-1);
}
return dates;
}
My Html view contains this statement:
@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")
What am I doning wrong that's causing my dropdown list to fill with nothing but "System.Web.Mvc.SelectListItem"?