How can I keep TempData when browser refresh but null if user leave the page

Viewed 417

Is there anyways to keep TempDate if browser or page refresh but null or reset if user leaves to another page then go back.

I am able to Keep TempData using TempData.Keep() but I want to reset it if user go to another page and come back.

var projectId= TempData["projectId"];
    TempData.Keep("projectId");
2 Answers

TempData is designed to have a life span only in between the current and the next request. You'd have to re-store it on every request (or call .Keep()) to make it available on the subsequent request. You would be better of using a Session object or retrieving it from your user identity.

However you can "keep" your TempData object, if you call .Keep() after calling it (displaying counts towards calling).

<li class="nav-item">                   
     <h5 style="color:white"> Welcome, @TempData["username"]</h5>
     @TempData.Keep("username")
</li>

Yet another way to circumvent this, is to use .Peek():

<li class="nav-item">                   
     <h5 style="color:white"> Welcome, @TempData.Peek("username").ToString()</h5>
</li>

I suggest using Session instead:

Session["projectId"] = projectId;
var projectId = Session["projectId"];
Related