In case you want to preserve some data 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)
// Add CookieTempDataProvider after AddMvc and include ViewFeatures.
// using Microsoft.AspNetCore.Mvc.ViewFeatures;
What you should 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.