.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

My View on the Life cycle of a Fixed Cost Web Project 01st July, 2018

How to Deliver Accurate Project Status Reports 21st April, 2018

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.

There are no comments.

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

View Comments (0) ...
Navigation