Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value to session, giving object reference not set to an instance of an object exception in MVC

Problem Statement:

I'm trying to assign a value to session object in MVC Controller it is giving exception as Object reference not set to an instance of an object.

I'm having two controllers

  1. MainController
  2. SecondaryController

When I assign value to session in Main controller it is working fine.but if i assign same value in a Test() method in secondary controller,it is giving error.

What i'm doing wrong here???

Main Controller :

 public class MainController: Controller
     {
        SecondaryController secCont=new SecondaryController();
        public ActionResult Index(LoginModel loginModel)
          {

            if (ModelState.IsValid)
                {
                 Session["LogID"] = 10;
                  //This is working fine.
                  //Instead of this i want call secCont.Test(); method where value for session assigned, it is giving error.

                }
              return View(loginModel);

           }
     }

Secondary Controller :

 public class SecondaryController: Controller
   {
     public void Test()
     {
        Session["LogID"] = 10;
        // Giving Error as **Object reference not set to an instance of an object.**
      }

    }
like image 737
Vishal I P Avatar asked May 13 '14 10:05

Vishal I P


People also ask

How do I fix object reference not set to an instance of an object in MVC?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

How do you fix error object reference not set to an instance of an object?

To fix "Object reference not set to an instance of an object," you should try running Microsoft Visual Studio as an administrator. You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version.

What is object reference not set to an instance of an object?

The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.

What is object reference not set to an instance of an object in C#?

The error means that your code is trying to access/reference an object that is a null valued object that is not there in memory.


1 Answers

This is because Session variable is only available in Standard ASP.NET MVC Controller (main controller). In order to access session variables in secondary controller you should use

System.Web.HttpContext.Current.Session["LogID"] = 10;
like image 182
Atul Avatar answered Oct 16 '22 16:10

Atul