Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Holding value between multiple pages

I'm working on rewriting an MVC application that currently utilizes cookies to hold data between multiple pages such as a date. I have tried to come up with an option that would hold the data in the controller by using something like this:

public DateTime HoldDate {get; set;}

The problem that I'm facing is that this is overwritten on each page load. I have also considered using Vue to store the variable and then sending the date to the controller on page load, but I'm not sure how to perform this.

Any help is appreciated and thank you in advance!

like image 538
Dominik Willaford Avatar asked Feb 13 '20 20:02

Dominik Willaford


2 Answers

You can use TempDataDictionary to pass data from the controller to the view and back. It's a Dictionary, so you can access it with a key:

TempData["HoldDate"] = new DateTime(2020, 2, 13);

When you read data normally from TempData, it is automatically marked for deletion with the next HTTP request. To avoid that, since you want to pass this data around, use the .Peek() method, which lets you read the data but does not mark it for deletion.

var date = TempData.Peek("HoldDate");
like image 177
Nathan Miller Avatar answered Oct 20 '22 00:10

Nathan Miller


If you need data to persist during the entire user session, you can use Session. For example user id or role id.

if(Session["HoldDate"] != null) 
{
    var holdDate= Session["HoldDate"] as DateTime;
}

If you need data only persist a single request - TempData. Good examples are validation messages, error messages, etc.

if (TempData.ContainsKey("HoldDate"))
{
    var holdDate = TempData["HoldDate"] as DateTime;
}

TempData and Session, both required typecasting for getting data and check for null values to avoid run time exception.

like image 2
Pavel Shastov Avatar answered Oct 20 '22 02:10

Pavel Shastov