Passing TempData value from controller to controller

Refer to following code;

TempData["error"] = true;
return RedirectToAction("YourViewName", "YourControllerName);       

On Redirect, TempData will become NULL. To solve this, try string test first;

On first controller method, set this;
TempData["error"] = "There is an error"

On a second controller method, get this;
var message = TempData["error"]

if you can see the message in second controller, no need to make any configuration changes. The problem is with your complex object serialization/deserialization

If TempData string (shown above) doesn’t work, then you need to make these configuration changes.

builder.Services.Configure<CookieTempDataProviderOptions>(options =>
{
    options.Cookie.Name = "TEMPDATA";
    //you have to avoid setting SameSiteMode.Strict here 
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.IsEssential = true;
   
});

We can pass values as query string in RedirectToAction method but we don’t want to show sensitive data in URL. So the alternate is to pass it as TempData that is using session at the backend or simply use Session.

Here is a simple comparison;

Maintains data betweenViewData/ViewBagTempDataHiddenFieldsSession
ControllerToControllerNOYESNOYES
ControllerToViewYESNONOYES
ViewToControllerNONOYESYES

If you like to store/retrieve complex objects between controllers using TempData, use this extension method;

Reference

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-8.0#tempdata

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.cookietempdataprovideroptions.cookie?view=aspnetcore-7.0

FavoriteLoadingAdd to favorites

Author: Shahzad Khan

Software developer / Architect