Search code examples
asp.net-mvc-2asp.net-4.0tempdata

TempData["message"] isn't reliable-- what am I doing wrong?


I'm using TempDate["Message"] to show little update banners as the user does things on my site like this:

[AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admins")]
public ActionResult Delete(int id)
{
    _Repo.DeletePage(id); // soft-delete

    TempData["Message"] = "Page deleted!";
    return RedirectToAction("Revisions", "Page", new { id = id });
}

Then in my master page I have this:

<%-- message box (show it only if it contains a message) --%>
<% string Message = (TempData["Message"] ?? ViewData["Message"]) as string; 

   if(!string.IsNullOrEmpty(Message)){
       %>
       <div id="message"><%:Message %></div>
   <% }

   TempData["Message"] = null; ViewData["Message"] = null; %>

I hit both TempData and ViewData because I read somewhere that TempData should be used for redirects and ViewData should be used otherwise.

The issue is: often the message won't show up right away. Sometimes it takes a click or two to different parts of the site for the message to show up. It's very strange.

Any ideas?


Solution

  • You should verify all places where you use TempData["Message"] in your code. Corresponds to ASP.NET MVC does browser refresh make TempData useless? you can read TempData["Message"] only once (see also http://forums.asp.net/p/1528070/3694325.aspx). During the first uage of TempData["Message"], the TempData["Message"] will be deleted from the internal TempDataDictionary.

    Probably it would be better to use TempData["Message"] only inside of Revisions action of the Page controller and not inside of master page or inside a View.