In a previous post, I wrote about solving the form resubmission confirm issue that many developers run into when building web applications. In ASP.NET MVC, we have many tools at our disposal to pass information from one method to another, the most common being the TempDataProvider. In this short but enlightening post, we’ll take a look at how we can use a new feature in ASP.NET Core to clean up our usages of TempData.

What Is TempData

TempData is a temporary data storage mechanism that is only guaranteed to hold data for the lifetime of an HTTP request. The context of that data is also isolated to the request, meaning only the client who initiated the call has access to that information. In most cases, ASP.NET stores TempData in-memory, but there are other less volatile storage implementations.

TempData is accessible in ASP.NET MVC controllers, Razor Pages, and Razor Page Models, and our values are retrievable through the dictionary-like interface. Each value is stored utilizing a key and boxed to an object.

var value = (string)TempData["my-awesome-key"];

When recalling a value, we are required to cast the object back to its original type. More can be read about TempData at the Microsoft Docs.

TempData Attribute

In the latest version of ASP.NET, we now have access to a TempDataAttribute. This attribute can decorate properties on our controllers, Razor Pages, and Razor Pages models. Let’s take a look at an example.

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    [TempData]
    public string Name { get; set; }

    public void OnGet()
    {
        if (string.IsNullOrEmpty(Name))
        {
            Name = "Who are you?";
        }
    }

    public RedirectToPageResult OnPost()
    {
        Name = "Khalid Abuhakmeh";
        return RedirectToPage("Index");
    }
}

Note that Name is a string and that we decorated it with the TempData attribute. When the ASP.NET pipeline creates our page model, it will detect the attribute and set the value of our property.

Let’s implement the Razor Page.

@page @model IndexModel @{ ViewData["Title"] = "Home page"; }

<div class="text-center">
  <h1 class="display-4">@Model.Name</h1>
  <form asp-page="Index" method="post">
    <button type="submit">Submit</button>
  </form>
</div>

When we submit the form, we can see the value update on our web page.

TempDataAttribute usage

We can also alter the key that provides value for our property for ultimate flexibility.

[TempData(Key = "Cool")]
public string Name { get; set; }

Conclusion

TempData is a powerful abstraction that solves many problems. With the addition of the TempDataAttribute we can clean up our code from magic strings and potential spelling errors. While not an earth-shattering addition to the stack, we can all agree its the little things that matter.