Petrus Theron
Petrus Theron

Reputation: 28837

Shopping cart session state done right in ASP.NET MVC

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?

Upvotes: 9

Views: 11433

Answers (2)

uvita
uvita

Reputation: 4124

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.

Upvotes: 4

John Farrell
John Farrell

Reputation: 24754

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

Upvotes: 0

Related Questions