I am trying to use mvc TempData[]
to send an error message to another controller with the redirect:
Controller 1:
TempData["Message"] = "A password reset email has been sent to " + user.Email +
". This link in only valid for 24 hours.";
return RedirectToAction("Edit", "Users", new { id = userId });
I then have the following helper class situated at the constructor of Controller 2:
public UsersController()
{
NotificationHelper.GetViewDataNotifications(this);
}
Here is the helper class:
public static void GetViewDataNotifications(ControllerBase controller)
{
var message =controller.TempData["Message"] ?? "";
controller.ViewBag.Message = message;
var errorMessage = controller.TempData["ErrorMessage"] ?? "";
controller.ViewBag.ErrorMessage = errorMessage;
var infoMessage= controller.TempData["InfoMessage"] ?? "";
controller.ViewBag.InfoMessage = infoMessage;
var warningMessage = controller.TempData["WarningMessage"] ?? "";
controller.ViewBag.WarningMessage = warningMessage;
}
I then expect for the ViewBag
items to be populated by the time I get to Edit
Action
:
public async Task<ActionResult> Edit(int? id)
{
...
return View();
}
However in my helper class the TempData always seems to be null. What am I missing here?
Is there some factor to the TempData[]
that I am not aware of, such as its only valid in the same controller or its only valid for a single action?
You are trying to access TempData in the controller's constructor when it's still empty. At this point the controller isn't even fully constructed yet, much less initialized.
You should extract the TempData values inside your actions. TempData is initialized at least three steps after controller construction but before authorization and model binding.
This document describes the controller lifecycle in detail. While you can overrideone of the steps between TempData initialization (CreateTempDataProvider
) and the actual action, there isn't much point to it.