Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Session Variable in MVC

I have declared Session variable in "Global.asax" file as,

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            int temp=4;
            HttpContext.Current.Session.Add("_SessionCompany",temp);
        }

And want to use this Session Variable into My Controller's action as,

 public ActionResult Index()
        {
            var test = this.Session["_SessionCompany"];
            return View();
        }

But I am Getting Exception While accessing the Session Variable. Please help me on this that How can I access the Session Variable into my controller's Action.

I am getting an Exception like "Object Reference not set to an Insatance of an object" in Application_Start in Global.asax on line

HttpContext.Current.Session.Add("_SessionCompany",temp);
like image 236
Rahul Avatar asked Dec 03 '13 11:12

Rahul


People also ask

How can use session value in MVC view?

The Session value will be displayed using Razor Syntax in ASP.Net MVC. In the below example, a string value is set in the Session object in Controller and it is then displayed in View using Razor Syntax.

What is session variable in MVC?

Sessions values can be stored for the duration of the visitor's session on your site. Most cases, they are stored in server memory. You can configure session to store either in State server or in SQL Server. In ASP.NET MVC, you can create and access session variables using HttpContext. Current.

How session data is handled in MVC?

ASP.NET MVC provides three ways (TempData, ViewData and ViewBag) to manage session, apart from that we can use session variable, hidden fields and HTML controls for the same. But like session variable these elements cannot preserve values for all requests; value persistence varies depending the flow of request.


1 Answers

The thread that starts the Application is not the request thread used when the user makes a request to the web page.

That means when you set in the Application_Start, you're not setting it for any user.

You want to set the session on Session_Start event.

Edit:

Add a new event to your global.asax.cs file called Session_Start and remove the session related stuff from Application_Start

protected void Session_Start(Object sender, EventArgs e) 
{
   int temp = 4;
   HttpContext.Current.Session.Add("_SessionCompany",temp);
}

This should fix your issue.

like image 67
Phill Avatar answered Sep 21 '22 18:09

Phill