I would like to use TempData in my .net core mvc application. I followed the article from https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#tempdata
I always get NULL Here is my code:
public async Task<ActionResult> Index(RentalsFilter filter)
{
TempData["test"] = "ABC";
return View();
}
public ActionResult Create()
{
var abc = TempData["test"].ToString();
return View();
}
TempData in MVC is used to pass data from Controller to Controller or Controller to view and it is used to pass data that persists only from one request to the next. TempData requires Typecasting. And also check for Null value before reading the value from it.
ASP.NET MVC - TempData TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller. TempData stores the data temporarily and automatically removes it after retrieving a value.
Had similar issue due to GDRP (https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1). If you want have it up and running without worring about GDPR you can just disable it. The config below also uses cookies (default) instead of session state for TempData.
Startup.cs
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<CookieTempDataProviderOptions>(options =>
{
options.Cookie.IsEssential = true;
});
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy(); // <- this
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Did you configure TempData as said in the doc:
in ConfigureServices method add:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
services.AddSession();
And in Configure method you should add:
app.UseSession();
The answer that worked for me (for asp.net Core 2.2) was
in Startup.Configure() app.UseCookiePolicy(); should be after app.UseMVC();
Which someone above has linked to in the comments from this stackoverflow answer
This is in addition to having
app.UseSession() (in Configure)
and
services.AddSession() (in ConfigureServices)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With