Search code examples
c#.netasp.net-mvc-3tempdata

TempData Wrapper


Because I use same keys for TempData over and over again, I would like to make it easier to keep track of these keys. It would be great if eventually I could write something like this:

MyTempData.Message = "my message";

instead of

TempData["Message"] = "my message";

Solution

  • Sounds like you want a strongly typed TempData. One way to go about that is writing a Extension Method on Controller to do it:

    public static class ControllerExtensions
    {
      public string GetMessage(this Controller instance)
      {
        string result = instance.TempData["Message"] as string;
        if (result == null)
        {
          result = "some default value or throw null argument exception";  
        }
        return result;
      }
    
      public void SetMessage(this Controller instance, string value)
      {
        instance.TempData["Message"] = value;
      }
    }