ASP.NET TempData persists between requests
Asked Answered
B

2

9

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.

Brakeman answered 23/1, 2009 at 16:20 Comment(0)
G
23

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.

Gyimah answered 23/1, 2009 at 16:34 Comment(2)
so once I return a view that is actually part of the first request not the second, therefore I will see it the next time?Brakeman
I don't quite understand your question. If you set TempData and return a view, that view and the next request will see the TempData. Again, it is only safe to set TempData when returning a redirect result.Gyimah
C
0

would this be acceptable (removing the error once it has been shown):

<%  If TempData.ContainsKey("ErrorMessage") Then %>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<% 
    TempData.Remove("ErrorMessage")
End If
%>
Clipclop answered 23/1, 2009 at 16:35 Comment(1)
I don't know if it works, but it would certainly be a violation of the separation of concerns.Gyimah

© 2022 - 2024 — McMap. All rights reserved.