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?
if(Session["Cart"] != null)
{
foreach (var item in (Session["Cart"] as List<[type]>))
{
//do whatever you need to do
}
}
So the answer is yes
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
}
@foreach (var item in Model).
Session["Cart"]? because that will determine what you can do. Is it an array, orList<[type]>, or anIEnumerable<[type]>? Please be more specific as to what the context is.