Robert Ross Robert Ross - 1 year ago 73
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"])


Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download