TempData - "object reference not set to an instance of an object" when refreshing the page

851 Views Asked by At

I have a strange error. I'm using tempData to send a value from one controller to the other. It works perfectly fine when the program is running, I can call the function multiple times and temp data works as expected.

The problem occurs if I refresh the webpage. I receive this error:

 object reference not set to an instance of an object

Here's my code where I'm adding a value, id, to TempData:

    public IActionResult Details(int? id)
        {
            TempData["ID"] = id;
        }

and here's my code where I use the value in TempData, in a separate controller:

   public async Task<IActionResult> Index(string SubjectName, int CourseID)
        {
          
            //professor id
            int professorID = (int)TempData["ID"];
}

is there a way to save the values I store in temp data even when refreshing the page?

Any tips/suggestions would be appreciated.

1

There are 1 best solutions below

0
On

Turns out you can actually call the "keep" function so that any value you put in TempData lasts for more than one call.

In my second controller where I access the value in TempData, all I had to put in was this line of code:

     TempData.Keep("ID");
     int professorID = (int)TempData["ID"];

And the value will remain in the dictionary even when clicking refresh.