'Tempdata becomes null after redirect to another page
When the user successfully login, i'm storing the username in tempdata so i can use it in my _Layout:
TempData["username"] = model.Email.Split('@')[0];
TempData.Keep("username");
on my _Layout:
<li class="nav-item">
<h5 style="color:white"> Welcome, @TempData["username"]</h5>
</li>
this actually works on the first load, but if I go to another page, the tempdata turns to null and no username is displaying. How can i keep the username on my _layout?
Solution 1:[1]
Tempdata keep method work only for next request. If you want to store data in over all pages. Use MVC identity principal methodology to persist data overall page. Iprincipal
Solution 2:[2]
If you've recently changed your authentication to azure Ad and your application is load balanced. Please make sure, you've updated the load balancer to use sticky session. Without a sticky session, the response can come from any server which can result in null temp data.
Solution 3:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | user1501363 |
| Solution 3 |
