Asp.net MVC Session State Extension Method

There are a few implementations of the conical wizard out there using Asp.net MVC.  SessionsI’m working on a project where we are needing one such wizard and we’re trying out using session state, not session skate, to keep the models that make up the larger data set persisted for the user until the final submission.

This will allow the user to go back to any of the stages and edit the information if needed.  There are are options but for now we’re testing driving this approach.

Inspired (dang near a complete duplicate) by Donn Felker’s ASP.NET MVC TempData Extension Methods I created one that uses HttpSessionStateBase.

    public static class SessionStateExtensions
    {
        public static void Put<T>(this HttpSessionStateBase httpSession, T value) where T : class
        {
            httpSession[typeof (T).FullName] = value;
        }

        public static void Put<T>(this HttpSessionStateBase httpSession, string key, T value) where T : class
        {
            httpSession[typeof (T).FullName + key] = value;
        }

        public static T Get<T>(this HttpSessionStateBase httpSession) where T : class
        {
            var o = (T) httpSession[typeof (T).FullName];
            return o == null ? null : o;
        }

        public static T Get<T>(this HttpSessionStateBase httpSession, string key) where T : class
        {
            var o = (T) httpSession[typeof (T).FullName + key];
            return o == null ? null : o;
        }
    }

One Comment

  1. Donn says:

    Nice! I created the _exact_ same thing for Session use at a previous client. It worked great. Good stuff.

Leave a Reply