Simply said, ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.
By default, the TempData saves its content to the session state.
ASP.NET MVC TempData vs Sessions
This is a very common question asked – When do I use TempData Vs Session in my ASP.NET MVC app?
The answer lies in your usage. TempData is available only for a user’s session, so it persists only till we have read it and gets cleared at the end of an HTTP Request. A scenario that fits the usage of TempData, is when data needs to persist between two requests – a redirect scenario. Another scenario I can think of is to return an error message after a POST operation fails.
Show me an Example
Let’s see a scenario where TempData fits well. We are assuming that we are in a page that saves Customer data
[HttpPost] public ActionResult DoSomething(Customer c) { // write your logic here to save Customer Data TempData["custdetails"] = string.Format("Customer Address{0}", c.Address); return RedirectToAction("Index"); }
Here’s some razor code in your template, that be used in any view (in our case Index)
<div> @if (TempData["custdetails"] != null) { <p>@TempData["custdetails"]</p> } </div>
Why did we use TempData above?
When an action returns a RedirectToAction result, a HTTP redirect occurs. ViewBag cannot be used in this scenario since it is a redirect and it won’t be able to hold data beyond the current HTTP Request. Similarly with Sessions, we would have to do some maintenance work to remove it and it’s kind of an overkill just to be used to pass data. TempData fits best in this scenario as data can be preserved in the TempData property (dictionary) of the controller for the duration of that single HTTP redirect request. Once the Data is read in the view to which the user has been redirected, it gets deleted.
Tweet
2 comments:
"TempData is available only for a user’s session, so it persists only till we have read it and gets cleared at the end of an HTTP Request. A scenario that fits the usage of TempData, is when data needs to persist between two requests"
Sorry, but the two sentences contradict each other.
Can you show example of Tempdata.peek between view and partial view to pass data. And i want to clear tempdata.peek if redirects 2 another 3rd view.
Post a Comment