I have a div in my master page that is only displayed if Session[“message”] contains data:
<%
if (!String.IsNullOrEmpty(Session["message"].ToString()))
{
%>
<div id="sessionMessage" class="sessionMessage"><%:Session["message"].ToString()%></div>
<%
}
%>
I use it to pass general info to users for both action success and failure.
I tested it on failures, and it works great. Just set the Session[“message”] in the catch block and return a new instance of the view:
{
//Invalid - redisplay with errors
Session.Add("message", "That object already exists. Please try again.");
return View(new DetailViewModel());
}
Problem: However, for the success cases, which involve a RedirectToAction, the Session[“message”] always gets cleared out by the time I get to the Master Page:
//Send message to view for user to see
Session.Add("message", "Object added.");
//Redirect to the details
return RedirectToAction("Details", new { id = viewModel.MyObject.ObjectId });
I considered switching to TempData, but it throws a nullreference error on initial page load. I assume this is because TempData is a member of the Controller class, and the Master Page has no controller per se?
It’s just fine to use
TempDatain a master page. But if theTempData["message"]doesn’t happen to contain anything, then calling.ToString()on it will give you a null reference exception.SessionandTempDatabehave identically in this respect. This principle difference is thatTempDatais cleared when you read it, andSessionis not. So you’re more likely to see the problem withTempData, but your code has the same potential bug with either one.