11
Posted on: February 25, 2010 at 13:16

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





7 COMMENTS

  • Pingback: ASP.NET MVC Archived Blog Posts, Page 1

  • Pingback: Asp.net MVC Session State Extension Method

  • Pingback: ASP.NET MVC Extensions Methods « A Programmer with Microsoft tools

  • http://www.air-jordan-13.com air jordan 13

    Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
    Gucci sweaters
    If its common it might be difficult to get, however, be creative and you can usually find something.

  • http://wolfbyte.myopenid.com/ Mike Minutillo

    Good stuff

    You should be able to get rid of the “where T : class” by replacing the return line with “return o == null ? default(T) : (T)o;”. Then you can store integers and strings and so on :)

  • http://pulse.yahoo.com/_QS2EFZPGQHGJ3MGXLCEWZXMEP4 Nigrila Forever

    GREAT SITE FOR PROGRAMMING AND HOW TO PROTECT THE RIGHT TO FORM. Thank you for being there

    http://aplusa.org.uk/

  • Mike Vanderkley

    Thank you very much for this. I used the code as is regardless of Mike Minutillo’s comment.