为什么我的Html.DropDownList给我一个填充了" System.Web.Mvc.SelectListItem"的列表。字符串?

时间:2017-07-07 11:48:21

标签: c# asp.net asp.net-mvc asp.net-mvc-4 viewmodel

我在这个网站上研究了这个问题,发现了几个类似的问题。我尝试了所提出的所有建议,但显然,我的实施或我对导致这些解决方案不起作用的解释的理解。我将很感激如何解决这个问题。

我的项目包含以下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;
}

我的Html视图包含以下声明:

@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")

我做错了什么导致我的下拉列表中只有&#34; System.Web.Mvc.SelectListItem&#34;?

2 个答案:

答案 0 :(得分:2)

Html.DropDownList的第二个参数需要IEnumerable<SelectListItem>,而不是SelectList

尝试将视图模型上的方法更改为:

    public IEnumerable<SelectListItem> 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] });
        }

        return list;
    }

您实际上可以将其简化为:

    public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem {  Selected = index == 0, Text = dateString, Value = dateString})
            .ToList();
        return selectListItems;
    }

答案 1 :(得分:0)

您是否尝试设置数据和文本字段?

ASP.NET MVC Dropdown List From SelectList

var selectList = new SelectList(list, "Value" , "Text");