Search code examples
c#asp.net.netasp.net-mvcviewbag

Generic list not showing in ViewBag


I'm not able to assign a generic list to ViewBag. Here is my code:

var m = from i in Enumerable.Range(0, 12)
        let now = DateTime.Now.AddMonths(i)
        select now.ToString("MMMM") + " " + now.Year.ToString();

ViewBag.b = m;

I am getting this when I output the ViewBag value:

System.Linq.Enumerable.WhereSelectEnumerableIterator<int,string>

Solution

  • You can cast it to a list like this:

    var m = (from i in Enumerable.Range(0, 12)
             let now = DateTime.Now.AddMonths(i)
             select now.ToString("MMMM") + " " + now.Year.ToString()).ToList();
    ViewBag.b = m;
    

    And then in your view:

    @{
        var myList = ViewBag.b as List<string>;
    }
    
    <ul>
        @foreach (var item in myList)
        {
            <li>@item</li>
        }
    </ul>