woggles woggles - 1 year ago 166
C# Question

MVC3 TempData exists when clicking back button

I'm using TempData to pass additional messages to show a notification accross requests:

public ActionResult Address()
TempData["NotificationType"] = "error";
TempData["NotificationMessage"] = "There was an error updating the address.";
return RedirectToAction("Index", "Home");

public ActionResult Index()

if (TempData["NotificationType"] != null && TempData["NotificationMessage"] != null)
model.NotificationMessage = TempData["NotificationMessage"].ToString();
model.NotificationType = TempData["NotificationType"].ToString();
return View();

Index View:

<div id="NotificationType" data-notification_type="@Model.NotificationType"/>
<div id="NotificationMessage" data-notification_message="@Model.NotificationMessage" />

<script type=text/javascript>
if($('#NotificationType').data('notification_type') == 'error'){
Notify('error', "Error!", $('#NotificationMessage').data('notification_message'));

I then display the error notification in the view and it works great.
My problem comes in after that if I click another link and then press the back button in the browser the notification displays again.

Is there a way to prevent the notification from redisplaying?

EDIT: Looks like its because its caching the index view as it doesn't hit a breakpoint in the action when I hit the back button.

Answer Source

Fixed this by preventing caching on the index view:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Index()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download