.NET Daily

ASP.NET Core. Best way to Keep Variables between Page Requests

Introduction

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.


LATEST POSTS

How to solve: An expression tree may not contain a dynamic operation – ASP.NET Core 06th July, 2019

How to use DbContext Scaffold to add only selected tables – ASP.NET Core 01st July, 2019

Web Development

ASP.NET Core. Best way to Keep Variables between Page Requests

Posted on .

In case you want to keep variables between page requests, ASP.NET CORE MVC and ASP.NET MVC provides a more elegant solution than the classic ViewState. It is called TempData.

The usage of it is pretty straightforward. The example from below shows how I assign a variable to preserve the sort state of a column in a list table:

TempData["SortOrder"] = _sortOrder;

If you use ASP.NET Core, make sure you register the right services first:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // Add CookieTempDataProvider after AddMvc and include ViewFeatures.
    // using Microsoft.AspNetCore.Mvc.ViewFeatures;
    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}

To Keep in Mind

  • If you only want to preserve this data between requests, I advice to not use server session nor browser cookies for this. Both options should be used with responsibility because of their broader scope they are having.
  • However, the values inside TempData dictionary are preserved until the value is read or until the user session is lost.

More about this topic in the official documentation page.

Darius

Darius

Darius Dumitrescu is a creative Senior CMS Consultant with in depth .NET knowledge, focused on Web Development and Architecture Design.

Comments
  • user

    AUTHOR Salah

    Posted on 10:12 am April 22, 2019.
    Reply

    Very bad solution, Tempdata is saved in a session variable.

  • This site uses Akismet to reduce spam. Learn how your comment data is processed.

    View Comments (1) ...
    Navigation