Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET TempData persists between requests

I am using temp data as follow in my controllers - very simple, when there is a problem:

TempData("StatusMessage") = "You have no items set to Auto-Ship."

Then on every page I have a user control as follows:

<div class="error-container">
<%  If TempData.ContainsKey("ErrorMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<% End If%>
<%  If TempData.ContainsKey("StatusMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-status"><p><%=TempData("StatusMessage")%></p></div>
<% End If%>
<ul></ul>
</div>

Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.

I am not using any IoC, I did see the post with the same problems when using that.

like image 465
Slee Avatar asked Jan 23 '09 16:01

Slee


People also ask

Does TempData preserve data in the next request also?

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

Is TempData stored in session?

It is stored in session storage, but there is one crucial difference between TempData and Session : 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.

How long does TempData last in MVC?

ASP.net MVC will automatically expire the value of tempdata once consecutive request returned the result (it means, it alive only till the target view is fully loaded). Session will be expire after the session time out occurred.


1 Answers

The sole purpose of TempData is to persist until the next request. Stuff you do not want to persist until the next request should go into ViewData, instead.

Realistically, this means that TempData is only safe to use when redirecting. When not redirecting, the "next request" could be anything.

like image 147
Craig Stuntz Avatar answered Oct 20 '22 18:10

Craig Stuntz