View Variables In .NET Core MVC

This series of articles will discuss View related issues of the MVC module,

Introduction

The previous article, View Variables in .NET MVC, planned to discuss View Variables for both .NET MVC and .NET Core MVC. However, after finishing the .NET MVC part, I realized that the article is too long if I add another part for .NET Core. Therefore, I separate that part into this new article. So, the content structure will be exactly the same as the previous one for .NET MVC.

This will be the contents of this article,

  • .NET Core MVC
    • Setup Environment for Code Testing
    • What ViewBag, ViewData, TempData, and Session are
    • How ViewBag, ViewData, TempData, and Session Work
      • ViewBag and ViewData
      • TempData
      • Session
    • Difference between .NET MVC and .NET Core MVC for View Variables
      • .NET MVC TempData supported by Session by Default
      • .NET Core MVC TempData supported by CookieTempDataProvider by default
      • .NET Core MVC TempData supported by Session after Session Enabled

A - Setup MVC Environment for Code Testing

Step 1 - Create a .NET Core MVC app

We use the current version of Visual Studio 2019 16.9.4 and .NET Framework 4.8 to build the app,

  • Start Visual Studio and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller) > Next.
  • In the Configure your new project dialog, enter Core MVC for Project name > Next
  • In the Additional Information dialog, select .NET 5.0 > Create

Step 2 - Add ViewBag, ViewData, TempData, and Session

In Controller, update HomeController/Index action,

public class HomeController: Controller {
    private readonly ILogger < HomeController > _logger;
    public HomeController(ILogger < HomeController > logger) {
        _logger = logger;
    }
    public IActionResult Index() {
        List < string > Student = new List < string > ();
        Student.Add("Jignesh");
        Student.Add("Tejas");
        Student.Add("Rakesh");
        this.ViewData["Student"] = Student;
        this.ViewBag.Student = Student;
        this.TempData["Student"] = Student;
        //this.Session["Student"] = Student;
        return View();
    }......
}

Note
Different from .NET MVC, where the Session State is supported by default, in .NET Core MVC, the Session State is not supported by default before we add it into the app. So, at this point, before we add the Session state, the Session will not work.  We will discuss this point, especially in Section D.

In View/Homw/Index.cshtml,

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<br>
<br>

<ul>
    <b>ViewBag</b>
    @foreach (var student in ViewBag.Student)
    {
        <li>@student</li>
    }
</ul>
<ul>
    <b>ViewData</b>
    @foreach (var student in ViewData["Student"] as List<string>)
    {
        <li>@student</li>
    }

</ul>
<ul>
    <b>TempData</b>
    @foreach (var student in TempData["Student"] as List<string>)
    {
        <li>@student</li>
    }
</ul>
@*<ul>
    <b>Session</b>
    @foreach (var student in Session["Student"] as List<string>)
    {
        <li>@student</li>
    }
</ul>*@

Note
The Session Variable in the view comments out, too.

The result,

View Variables In .NET Core MVC

B - What ViewBag, ViewData, TempData, and Session are

ViewBag, ViewData, TempData, and Session are the options to send value from controller to view or to other action method/pages.

1. They are the properties of Controller in MVC Core

Like .NET MVC, in .NET Core MVC, ViewBag, ViewData, TempData, and Session are the properties of the Controller Class.

However, different from .NET MVC, where ViewBag, ViewData, and TempData are the properties of ControllerBase class, which is the parent of the Controller Class; while the Session is the property of Controller class. In .NET Core MVC, they are opposite. ViewBag, ViewData, TempData belong to Controller class directly, 

View Variables In .NET Core MVC

While the Session (HttpContext) is the property of ControllerBase class,

View Variables In .NET Core MVC

2. Type

They are all the type of Dictionary with the string as key, except ViewBag is dynamic type:

  • ViewData --- public Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary ViewData { get; set; }
  • ViewBag --- public dynamic ViewBag { get; }
  • TempData --- public Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionary TempData { get; set; }
  • Session --- public Microsoft.AspNetCore.Http.HttpContext HttpContext { get; }

Note:

ViewBag is a wrapper over ViewData and allows to store and retrieve values using object-property syntax rather than key-value syntax used by dictionary objects. It does so using the dynamic data type feature of .NET.

C - How ViewBag, ViewData, TempData, and Session Work

This part, they are similar to what they are in .NET MVC, we just repeat the conclusion and skip the analysis, and then we open another session D to discuss the difference between .NET MVC and .NET Core MVC.

1. ViewBag and ViewData

They can be used to pass data from controller to view, one way only in the same request.

View Variables In .NET Core MVC

View Variables In .NET Core MVC

The difference between ViewBag and ViewData,

  • ViewData
    • If passing string into ViewData then no need to typecast
    • If the passing object in ViewData then you need to typecast it but before that, you need to check if it is not null
  • ViewBag
    • ViewBag's a dynamic type so not necessary to typecast

2. 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. i.e., It can be retrieved once, and only once. Finally, we should mention,

  • TempData saves into the session so on the expiration of session data loss;
  • TempData removes a key value once accessed, you can still keep it for the subsequent request by calling TempData.Keep() method.
  • TempData is usually used to pass error messages or something similar.

3. Session

  • Session stores data into session
  • The session is not similar to TempData to access but you can read as many time as you want
  • The session never becomes null until or unless session timeout or session expires.
  • The session is not a good practice to use. Used very frequently or store big data, it hits performance

D - Difference between .NET MVC and .NET Core MVC for View Variables

1. The cookie-based TempData provider is used by default to store TempData in cookies.

We know that in .NET MVC TempData is stored in Session state by default. This means the web application must have sessions enabled. However, in .NET Core MVC, the session state is not enabled by default. Luckily, .NET Core 2.0+ provides two TempData providers - Cookie-based and Session State-based while the cookie-based provider is used by default.

TempData providers --- MS

The cookie-based TempData provider is used by default to store TempData in cookies.

The cookie data is encrypted using IDataProtector, encoded with Base64UrlTextEncoder, then chunked. The maximum cookie size is less than 4096 bytes due to encryption and chunking. The cookie data isn't compressed because compressing encrypted data can lead to security problems such as the CRIME and BREACH attacks. For more information on the cookie-based TempData provider, see CookieTempDataProvider.

2. Configure the TempData provider[ref]

The cookie-based TempData provider is enabled by default.

To enable the session-based TempData provider, use the AddSessionStateTempDataProvider extension method. Only one call AddSessionStateTempDataProvider is required.

In Startup.cs,

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddMvc()
         .AddSessionStateTempDataProvider();
    services.AddSession();
}

 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ......

    app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapRazorPages();
    });
}

3. Verifications

.NET MVC

Run the app with F12 tools and locate the cookies option. The following figure (Firefox) shows the cookie used by TempData for storing the values. In Firefox, after the app running, type fn F12, under Storage/Cookies, Click the link, you will See: Name: ASP.NET_SessionID (if you run a different app, you probably need to right-click the link and delete all existing cookies),

View Variables In .NET Core MVC

Click ASP.NET_SeccionId, on the right, you will see the TampData is supported by Session (by default) for .NET MVC,

View Variables In .NET Core MVC

.NET Core MVC: for default TempData Provider,

Repeat the process above for the .NET Core MVC app,

View Variables In .NET Core MVC

TempData is supported by CookieTempDataProvider by default for .NET Core MVC,

View Variables In .NET Core MVC

.NET Core MVC: with Session State

Repeat the process above for the .NET Core MVC app with Session enabled,

View Variables In .NET Core MVC

TempData is supported by Session for .NET Core MVC after configuration to enable Session and using SessionStateTempDataProvider,

View Variables In .NET Core MVC

Summary

This article actually discussed .NET MVC ViewBag, ViewData, TempData, and Session. We will leave .NET Core MVC for the same discussion in the next article.

  • .NET Core MVC
    • Setup Environment for Code Testing
    • What ViewBag, ViewData, TempData, and Session are
    • How ViewBag, ViewData, TempData, and Session Work
      • ViewBag and ViewData
      • TempData
      • Session
    • Difference between .NET MVC and .NET Core MVC for View Variables
      • .NET MVC TempData supported by Session by Default
      • .NET Core MVC TempData supported by CookieTempDataProvider by default
      • .NET Core MVC TempData supported by Session after Session Enabled

Reference

Session and Colkie: