ASP.NET TempData persists between requests

血红的双手。 提交于 2019-11-30 06:01:05

问题


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.


回答1:


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.




回答2:


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
%>


来源:https://stackoverflow.com/questions/473520/asp-net-tempdata-persists-between-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!