Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Persist data using session variable in mvc3 razor view?

I am working in MVC3 Application with Razor. In my Account controller after validating the user, i am getting the user ClientID from Database. Here i want to persist ClientID in Session variable. which was using across the all controller and Razor view.

I have no idea as to what is the best way to implement this.OR How to persist data in the session variable. And how to use persisted data in the session variable in across the controller.

Thanks for your help..

like image 583
user10489 Avatar asked Jul 25 '12 06:07

user10489


1 Answers

I usually write a Session wrapper that allows me easy access to it in the future:

public class SessionData
{
    const string ClientId_KEY = "ClientId";

    public static int ClientId
    {
        get { return HttpContext.Current.Session[ClientId_KEY] != null ? (int)HttpContext.Current.Session[ClientId_KEY] : 0; }
        set { HttpContext.Current.Session[ClientId_KEY] = value; }
    }
}

After that you can access it from anywhere like this:

int clientId = SessionData.ClientId;

If you want you can use whole objects in Session like this.

Or you can set it like so: SessionData.ClientId = clientId;

like image 161
Dmitry Efimenko Avatar answered Sep 23 '22 21:09

Dmitry Efimenko