Ali Hasan
Ali Hasan

Reputation: 1075

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>

Upvotes: 0

Views: 1974

Answers (2)

Robert Levy
Robert Levy

Reputation: 29083

The items in the list will be calculated dynamically when you do a foreach over that value. if it makes you feel better though, you can drop a .ToList in there

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

Upvotes: 3

Kristof Claes
Kristof Claes

Reputation: 10941

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>

Upvotes: 4

Related Questions