Robert Ross Robert Ross - 2 months ago 9
C# Question

Iterating over a session variable in view

I am wondering how can an iterate over a session , to which I am assigning a list of string in an action method.
I want to display each of the elements in the session as links via the for loop.
Any help is appreciated.

Here is my index method :

public ActionResult Index()
Session["num"] = Posts;
//Posts = new List<string> { "element1", "element2", "element3" };
return View();

And here is my view :


@foreach (@item c in @Session["num"])



You will need to cast your session variable since it's an object.

Something like...

    var posts = Session["num"] as List<string>;
    if (posts != null) {
        foreach (var item in posts) {