(C# ASP.NET Core) When and how to use TempData

TempData can be used to pass data from one razor page to another. Although QueryString and Session variables can be used to achieve the same objective, yet TempData provides a briefer and cleaner way, and most importantly, it is built into the ASP.NET framework. The most attractive feature of TempData is that the data is automatically cleared away after a first read/extract operation - whenever it takes place. The tutorial ends with a walkthrough where TempData is saved in one page and used for showing a message on a second page. The message appears only once.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

Consider this scenario

  1. A user enters his login id, password and posts a form.
  2. An authentication code runs and finds that his subscription expires in 2 months.
  3. We want to show a temporary warning message on his home page. The message is to be shown just once.

How to implement this?

What options do we have?

Query String: The classic approach could be to pass a query string and read it there. You might want to avoid this option if you do not want to have an un-tidy URL.

Session: Another option would be to store the message in a session variable, and read it on the next page, and immediately clear the variable. This approach will require you to add some code.

Video Explanation with a Working Example

Please watch the following youtube video:

What is TempData?

TempData is used to hold data, but the data is automatically cleared away after it is read/extracted. Any next read fails. The "read" operation can take place even on the next page or some subsequent next page. The data continues to "stay" untill it is read/extracted.

A TempData variable is created in the backing class by marking it with the attribute [TempData].

public class IndexModel : PageModel
{

  [TempData]
  public String Message { get; set; }

  // any function where the variable is set 
  void fx()
  {

    Message = "hello";

  }

}

TempData can be read in the same manner as we read ViewData and Session. The following snippet shows a read operation.


// some razor page 

@if (TempData.ContainsKey("Message"))
{
<p style="color:red">

  <span>@TempData["Message"]</span>

</p>
}

How to prevent TempData from being cleared

A read operation can be followed by a Keep to prevent deletion like so


// some razor page 

@if (TempData.ContainsKey("Message"))
{
<p style="color:red">

  <span>@TempData["Message"]</span>

  // prevent the variable from being cleared  
  @TempData.Keep("Message")

</p>
}

Another alternative is to use the Peek method. It reads the data without clearing it. We can think of Peek as an integrated read and Keep.


// some razor page 

@if (TempData.ContainsKey("Message"))
{
<p style="color:red">

  <span>@TempData.Peek("Message")</span>

</p>
}

TempData vs ViewData vs Session

ViewData is available only within a page but not in another razor page.

TempData is available throughout the application session till you read it, unless, of course if you haven't used Keep/Peek.

Session variables are available throughout the application session, unless specifically cleared away.

Walkthrough on TempData

We will create a simple application of two pages - Index and Page2.

A user will "dummy login" through the Index page and a message "Your subscription expires in 2 months" will be stored in a TempData variable. This variable will be read and displayed on Page2.cshtml razor page. We shall verify that the message disappears after the page refresh.

Step 1 of 2: Walkthrough on TempData

Create a simple asp.net core application and add a razor page called Index. This page is a sort of login page.

// razor page index.cshtml 

@page

@model MySession.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>Login</h1>

<form method="post">

  Login ID: <input type="text" name="userID" required />

  <br /><br />

  Password: <input type="password" name="userPwd" required />

  <br /><br />

  <input type="submit" />


  <div>Type anything for this tutorial</div>

</form>


The above form is posted and handled by OnPost, where it is assumed that some login process takes place and finds that the subscription of the user is about to expire in 2 months. Then this message is stored in a TempData variable.

// index.cshtml.cs file 
using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System;

namespace MySession.Pages
{

  public class IndexModel : PageModel
  {

    // This property stores data 
    // until it's read in another request. 
    [TempData]
    public String Message { get; set; }

    // OnPost handler 
    public IActionResult OnPost(String userID, String userPwd)
    {

      // after login. . . 
      // user is authenticated 
      // but his subscription expires 
      // in 2 months 

      // set the TempData 
      Message = "Your subscription expires in 2 months";

      // Message will be available on Page2 
      // because it is marked TempData 
      return RedirectToPage("./Page2");

    }

  }

}

Step 2 of 2: Walkthrough on TempData

Next add another page called Page2 and write the following markup to display the TempData variable we created above.

// razor page page2.cshtml 

@page

@model MySession.Pages.Page2Model

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>
  Welcome !
</h1>

@if (TempData.ContainsKey("Message"))
{
<p style="color:red">

  <span>@TempData["Message"]</span>

</p>
}

<h3>Page content</h3>

Run the project to verify that the message is shown on Page2, and also verify that a form refresh causes the message to disappear.

How does TempData work behind the scenes?

TempData uses cookies and session to implement the boilerplate behind TempData. For more details please refer the MSDN documentation.


This Blog Post/Article "(C# ASP.NET Core) When and how to use TempData" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.