Shopping cart session state done right in ASP.NET MVC
Asked Answered
I

2

9

I'm implementing a simple session cart for unauthenticated users in ASP.NET MVC and I want to do it right.

In the past I have always stored the cart ID in the persistent Session["CartID"] store and as a cookie. Whenever I need to display the cart, I'll look up the user's cart items from my Carts and CartItems tables. But inside I know a more strongly-typed approach would be cleaner.

After Googling for the latest session MVC stuff, I found the term HttpSessionStateWrapper, which seems to be a testable way of dealing with sessions. But I have not found any good tutorials or standardised implementations. Maybe it's just a buzz-word and I should be sticking to Session["..."].

What is the right way to implement a shopping cart using sessions in the latest version of ASP.NET MVC?

Inessa answered 22/11, 2010 at 18:31 Comment(0)
D
4

Steve Sanderson, in his book Pro ASP.NET MVC 2 Framework, gives a nice example of a how to implement a shopping cart using session in ASP.NET MVC. If you don´t have the book, you can get an idea reading here. It is a very neat approach. The idea is to create a model binder that takes the shopping cart from the session. The actions that use the shopping cart will get the cart "injected" by the model binder. When you´re testing those methods, your tests should be responsible for passing the shopping cart to the action.

Dachy answered 22/11, 2010 at 19:5 Comment(1)
@Dachy I like this idea but isn't storing the whole cart in session a bad idea? I've deliberately avoided doing this in the past as we are told to keep session small, but if its getting the thumbs up im going for it. Great read too, thanks.Ring
H
0

MVC uses a testable and mockable abstraction of the HttpContext class called HttpContextBase. You don't need the wrapper at all and can still mock and unittest your controllers just fine.

First example I found on google: http://weblogs.asp.net/andrewrea/archive/2009/08/10/mocking-the-session-object-with-moq-inside-asp-net-mvc-and-having-a-clean-builder-method-for-session-values-in-the-controller.aspx

Hereunder answered 22/11, 2010 at 18:48 Comment(2)
That's just a mocking implementation for the session state with "dirty" code like int pageSize = Session["SpaceController!Index!PageSize"] == null ? 10 : Convert.ToInt32(Session["SpaceController!Index!PageSize"]); Is there a cleaner, strongly-typed way that's tried and tested?Inessa
How you mock is up to you. How you strongly type your session access is up to you. Session is reliant on string keys and stores objects. Your going to have to work with those at some point. I wanted to point out the major differences in Asp.net MVC.Hereunder

© 2022 - 2024 — McMap. All rights reserved.