0

The goal

There is a shopping cart in my application and I need to check if it is empty or not.

The problem

Look:

@if (Session["ProductsSummary"] == null)
{
    // Do something
}

As you can see, this piece of code checks if the session is null. When I add something to my cart — for the first time —, I create a session (called ProductsSummary) and store something in it (some information about the product that was added).

When I remove this item from Shopping Cart (or ProductsSummary — as you wish), I remove it from the session, but the session still alive. In other words, the session isn't null anymore, but is empty.

What I need is simple: how can I check if a session is empty?

Technical details

I'm using C#.NET + MVC 4 + Razor Engine.

Just to knowledge

I'm working with KnockoutJS.

Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96
  • That's going to depend on what your `ProductsSummary` class looks like. – Sven Jun 25 '13 at 13:21
  • 2
    That belongs in the controller. – SLaks Jun 25 '13 at 13:21
  • @SLaks Seriously? I was doing that in the view. I need an interface behavior. – Guilherme Oderdenge Jun 25 '13 at 13:23
  • 1
    Assuming this is something you want on every page (so it's in your layout file), you can do this without any problems, but the clean way is to have a [base viewmodel](http://stackoverflow.com/questions/13225315/pass-data-to-layout-that-are-common-to-all-pages) or use `RenderPartial`. Can you confirm that, @SLaks ? – user247702 Jun 25 '13 at 13:37
  • @Stijn: I would probably recommend a child action. – SLaks Jun 26 '13 at 14:03

2 Answers2

1

Something like this?

@if (!string.IsNullOrEmpty(Session["ProductsSummary"] as string))
{

}
1

If you wan't to remove your "ProductSummary" object, you can simply do Session.Remove("ProductSummary"). If you'd like to completely invalidate the Session, so that another one is created on a subsequent request, you can call Session.Abandon().

I believe you're slightly misunderstanding what the session is. Session is a key/value store. Session["ProductSummary"] = foo; doesn't create a new session, it adds your object to the existing Session.

Technically you shouldn't be checking if it is empty. Other code in your application should be able to expect to store data in the session. Controller.TempData, for example, stores data in the Session and consumes it in a subsequent request.

drch
  • 3,040
  • 1
  • 18
  • 29