Introduction
This tip presents an example of TempData
to persist data in between the request.
TempData
is used to pass data from current request to subsequent request (i.e., redirecting from one page to another). Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData
by calling the method Keep ()
.
In real-time scenarios, we need to keep the value in TempDate
object after request completion also.
In that scenario, we have two overloaded methods to retain value after current request completion.
Void Keep()
Void Keep(string Key)
Now, we will see them one at a time with proper examples.
Using the Code
1. Void Keep()
In Visual Studio intelligence will tell like ‘Marks all keys in the dictionary for retention’ i.e., it will hold all the items in TempData
. When calling this method within the current action ensures that all the items in TempData
are holding not removing at the end of the current request.
Example
We will do these in two ways either view level or action method in controller level:
View-Level
@model SampleTempDataProject.Models.UserModel;
@{
Layout="~/Views/Shared/_Layout.cshtml";
ViewBag.Title=”TempData Example”;
Var tempDataUserPersist= (User) TempData[“User”];
TempData.Keep();
}
Action -Controller Level
First, we need to include the model:
using SampleTempDataProject.Models.UserModel;
public ActionResult Index()
{
Var UserList= db.User.ToList();
TempData[“User”]= UserList;
TempData.Keep();
return View();
}
2 . Void Keep(string Key)
In Visual Studio intelligence will tell like ‘Marks the specified key in the dictionary for retention’ i.e., it will hold specified item in TempData
. When calling this method within the current action ensures that specified item in TempData
is holding not removing at the end of the current request.
Example
We will do these in two ways either view level or action method in controller level.
View-Level
@model SampleTempDataProject.Models.UserModel;
@{
Layout="~/Views/Shared/_Layout.cshtml";
ViewBag.Title=”TempData Example”;
Var tempDataUserPersist= (User) TempData[“User”];
TempData.Keep("User");
}
Action -Controller Level
First, we need to include the model:
using SampleTempDataProject.Models.UserModel;
public ActionResult Index()
{
Var UserList= db.User.ToList();
TempData["User"]= UserList;
TempData.Keep("User");
return View();
}
If you want to access the TempData
:
[HttpPost]
public ActionResult Index()
{
Var UserPersist= TempData["User"];
TempData.Keep("User");
return View();
}
Points of Interest
I really like this very much. Initially, I faced this kind of storing data problem in tempdata
. After I got this, it was perfect for me. Hope you enjoyed this article, and hope it is helpful for you. Thanks for your support. Cheers...
I sincerely thank my supporters.
History