0

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?

Username displaying

Username not display

3 Answers3

0

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

0

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.

-1

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>
Marco
  • 22,856
  • 9
  • 75
  • 124