Robert Ross Robert Ross - 21 days ago 6
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 :

<h2>Index</h2>

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

}

Answer

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) {
            ...
        }
    }
}