I am trying something which is starting to get weird but in principle it sounds normal. Basically I have a MasterPage in my ASP.NET application that takes care of showing the usual Login/Logout box in all pages. When the user is logged in, the usual "Welcome {Name}" appears.
The logged-in user details come from the Session.
Now I have a profile page where the user can change his/her name, which is all normal. As part of the Page Postback after editing, I update the Session with the new User Details.
What I would like to see happening is that the "Welcome" message would show the new Name if the user changed it.
I have digged a bit in the lifecycle and indeed given that the Session is accessed in the Page_Load but then updated in the UpdateButton_Click, the Welcome message is already updated before the Session is changed.
Does anyone have any idea on how to force a refresh for the Master Page or maybe there is something else I need to consider in terms of design?
I have also tried putting the Login/Logout box into a UserControl but things did not change.
Here are more details as requested:
MasterPage on PageLoad (accountMenuTitle is just a Label):
var loggedInUser = (Customer) Session["LoggedInUser"];
accountMenuTitle.InnerHtml = loggedInUser.Name;
ProfilePage Button_Click:
var updatedCustomer = update_Customer_Profile(txtFirstName.Text,
txtLastName.Text, txtAlternateEmail.Text, ... etc. etc.);
Session["LoggedInUser"] = updatedCustomer;
So when I click the button in the profile page, the page reloads, the logged-in User is updated in the Session but the Master Page Load already happened and the label shows the old name.
The solution I implemented in the end relies on the Master Page exposing a method for updating itself.
Master Page:
public void UpdateLoginPanel()
{
if (Session["LoggedInUser"] == null) // logged out
{
accountMenuTitle.InnerHtml = "Log in";
}
else // logged in
{
var loggedInUser = (Customer) Session["LoggedInUser"];
accountMenuTitle.InnerHtml = loggedInUser.Name;
}
}
In the Profile page aspx file, you can expose your Master Page like this:
<%@ MasterType VirtualPath="~/CustomerPortal.Master" %>
Then in the codebehind button click:
var updatedCustomer = update_Customer_Profile(txtFirstName.Text,
txtLastName.Text, txtAlternateEmail.Text, ... etc. etc.);
Session["LoggedInUser"] = updatedCustomer;
Master.UpdateLoginPanel();
I'm still a bit undecided if this is cleaner than Malcolm's answer to be honest :/