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
air jordan 13 says
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.
Mike Minutillo says
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 🙂
Nigrila Forever says
GREAT SITE FOR PROGRAMMING AND HOW TO PROTECT THE RIGHT TO FORM. Thank you for being there
http://aplusa.org.uk/
Mike Vanderkley says
Thank you very much for this. I used the code as is regardless of Mike Minutillo’s comment.
Terence Mak says
Thank you so much for your tutorial! but I have a question, why the extension class need to be in static?