Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

ASP.NET MVC TempData Extension Methods

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