How to access objects inside a List, saved in a Session. ASP.NET MVC 3
asp.net-mvc-3, session
Solution
it's as simple as reading back the value from your session varable and cast it to the original type, then do whatever you want
example:
@{
if(Session["list"]!= null)
{
var listBackFromSession = (List<Carrito>)Session["list"];
// do what you want
}
}
My recommendation is to use the more elegant way of ViewBag.
a quote from official asp.net mvc website about Viewbag:
New "ViewBag" Property
MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)
Further more, This is a good article to read about the different ways you have in MVC in order to preserve data: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
example:
var list = new List<Carrito> {
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};
// use ViewBag
ViewBag.myList = list;
then inside your view, read them back like this:
var myList = (List<Carrito>)ViewBag.myList;
// your code
Problem
So I have this code: ``` var list = new List<Carrito> { new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio } }; Session["list"] = list; return View(); ``` Then I load the view but I don't know how to print the the content that is inside the session. Any ideas? This is the code I use inside the view but doesn't work: ``` @foreach(var item in (IEnumerable<object>)Session["list"] ) { <p>@item.ProductId</p> } ```