Reputation: 277
I'm learning ASP.NET MVC and I have some problem to understand and use session
the right way. Let me explain what I have done and what I want to achieve.
First I create a session with a list of Products in the Index method of the Home controller. I also add some default products into the list like this:
Session["ShoppingCart"] = new List<Products>() { new Products { ID = 1 }, new Products { ID = 2 } };
(My goal is to use this session later in other controllers to be able to add products, but for now I just want to do some testing.)
Then in the Shop controller I have an action method to show the content of the shopping cart. This is where I start to get lost in this wonderful world.
The thing that I can't solve is how I should treat the Session["ShoppingCart"] so that I can view the list of products that are in the list!? Should I have a view with an IEnumerable to be able to iterate it the list with razor?
Upvotes: 0
Views: 6268
Reputation: 1579
You can also do like the code given below
var list = Session["ShoppingCart"] as List<Products>;
I prefer to use the as keyword since there is no 100% guarantee that the Session will contain the list (due to application pool refresh, website being restarted, etc). Gives you that extra bit of defence to avoid a NullReferenceException.
Then do your process
if (list != null){
foreach(var item in list)
{
your custom code
}
}
hope this helps you
Upvotes: 1
Reputation: 477
you can code in view like this
List<Products> list = (List<Products>)Session["ShoppingCart"];
@foreach(var item in list)
{
do what ever
}
i hope i works for you.
Upvotes: 3
Reputation: 547
In this case the best you can do is to define a Shopping Cart class:
public class Cart{
IList<Products> Products {get; set;}
// any other properties that you would need or structure this in way to store quantities, prices per line and so on
}
Then and assuming that you don't have any problem storing that in session, you just access it like (and please note you always need to cast anything you get from Session):
var cart = (Cart) Session["ShoppingCart"];
// do any work you need on the cart object
Upvotes: 0