← All articles

ASP.NET MVC TempData Extension Methods

Strongly typed TempData extension methods for ASP.NET MVC: Put and Get generics so you stop using stringly typed keys and casting exceptions.

Donn Felker

Donn Felker

2010.02.25 · 1 min read

This is an sister class to some Session classes I wrote awhile back (which I never posted). I originally wrote these extension methods for the code camp eval system for Twin Cities Code Camp last year. But I needed it today at my client so I figured I’d post it here for future reference … and so you could use it.

public static class TempDataExtensions
{
public static void Put<T>(this TempDataDictionary tempData, T value) where T : class
{
tempData[typeof(T).FullName] = value;
}
public static void Put<T>(this TempDataDictionary tempData, string key, T value) where T : class
{
tempData[typeof(T).FullName + key] = value;
}
public static T Get<T>(this TempDataDictionary tempData) where T : class
{
object o;
tempData.TryGetValue(typeof(T).FullName, out o);
return o == null ? null : (T)o;
}
public static T Get<T>(this TempDataDictionary tempData, string key) where T : class
{
object o;
tempData.TryGetValue(typeof(T).FullName + key, out o);
return o == null ? null : (T)o;
}
}

The code above allows you to put values into TempData in a strongly typed fashion. You can then get the values back out (safely) without worrying about an exception being thrown (temp data will throw if the key is not found).

Usage:

var customer = new Customer();
TempData.Put(customer); // Strongly typed without key
TempData.Put("key1", customer); // Strongly typed with extra key
var tempDataCustomer = TempData.Get<Customer>(); // Get customer without key
var tempDataCustomerWithKey = TempData.Get<Customer>("key1"); // Get customer with key
Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading