1

Is it possible to use foreach in cshtml file, and use the Session variable?

I want to do something like this:

@foreach (var item in Session["Cart"])

Is it possible?

4
  • 1
    Why don't you just test it? Commented Jul 10, 2018 at 18:28
  • Depends. What exactly is stored in the Session["Cart"]? because that will determine what you can do. Is it an array, or List<[type]>, or an IEnumerable<[type]>? Please be more specific as to what the context is. Commented Jul 10, 2018 at 18:32
  • 1
    @MGoward List .. Commented Jul 10, 2018 at 18:32
  • Okay that makes more sense. Commented Jul 10, 2018 at 18:35

2 Answers 2

3
if(Session["Cart"] != null)
{
    foreach (var item in (Session["Cart"] as List<[type]>))
    {
       //do whatever you need to do
    }
}

So the answer is yes

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but I have a little problem now with this: i have model called "Products" (whis is the 'type') But it does not find it.. althought I do: @model List<SurffingSite.Models.Products>
Can I see more of the code? that would help me out
Here is the html file: pastebin.com/YY01j1LX , here is the model: pastebin.com/c20X6Ufs
Well it looks like it should be working. I am not sure what could be done. I would suggest asking another question and seeing if others can give you an answer. I am sorry I was not able to help you any more...
2

As long as the object stored in Session["Cart"] implements either IEnumerable (which includes arrays and legacy collections) or IEnumerable<T> (which includes generic collections), you can use it in a foreach loop.

public void MyActionMethod()
{
    var list = Session["Cart"] as IEnumerable<Products>;
    if (list == null) throw new Exception("Cart not found or cannot be enumerated.");

    return View(list.ToList());
}

And in your cshtml:

@model List<Products>

@foreach (var product in Model)
{
    //Do something with product
}

3 Comments

Thanks but I'm having a little problem with it. Would you mind looking at my problem I described in the comment at the verified answer (above)?
You should probably pass in the list from the controller (as the model). Then in your cshtml you'd use @foreach (var item in Model).
I guess it's kind of indirect solution.. That's exactly what I did to overcome this problem but I thought there is direct solution. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.