[RESOLVED]Session Variable alternative

Suppose I have a database keeping track of maintenance issues relating to cars. I have a database that keeps track of the issues by make of car. In my "old" ASP.Net Forms website, I used Session Variables to SET the current car model. So if I set the
current model to FORD, when I would go to the Open Issues page, I’d see the issues only related to FORD automobiles.

I’m not sure if this is enough information, but…what would be a good way of handling this in MVC?

What I’m looking for is something like this:

1. User logs into the application

2. User is presented with a series of car model buttons. Once clicked, the application is SET to the model for the button he clicked.

3. Now, anywhere the user goes in the application, there is an ability to use FORD as a parameter for any queries that need to run.

Thanks in advance for any thoughts!

Although the Session isn’t generally recommended to be used within MVC Applications (as many believe that since it’s stateful and MVC aims to be stateless, they simply don’t mix), that doesn’t mean that people don’t use it.

Based on your requirements, a Cookie would likely be a solid option and would be available throughout your application. After the user selects a particular car model, simply create a cookie and store it in the Request to store the value :

// Create a cookie that expires in 7 days that will store the Model of your Car
HttpCookie cookie = new HttpCookie("Model");
cookie.Value = YourCarModelValue;
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);

Then you could just check to see if the Cookie exists prior to executing your query and use it’s value :

// Attempt to retrieve your cookie
HttpCookie cookie = Request.Cookies.Get("Model");

// Check if the cookie exists
if(cookie != null)
{
       // It exists, so use it's value in a query via cookie.Value
       var model = cookie.Value;
}
else
{
       // No model was selected or available, do something here
}

A few other alternatives for storage besides Session and Cookies might be :

  • Using available temporary storage like the ViewData, TempData or ViewBag, although these would be required to be passed along.
  • Using actual persistent storage like a database, which would most likely be complete overkill.

MVC is presentation framework, everything else web related stays the same so you can still use the session.

Thanks Rion! I really was trying to get away from the Session Variables. This looks like the route I’ll take. 

Thanks again for the quick response.

Leave a Reply