Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 353
Dmitry Efimenko Avatar asked Jun 08 '12 21:06

Dmitry Efimenko


2 Answers

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;
  }
}
like image 124
Erik Philips Avatar answered Sep 23 '22 23:09

Erik Philips


Pretty low-tech option, but if you just want to track the keys you're using, you could just create some constants:

public static class TempDataKeys
{
    public const string Message = "Message";
    public const string Warning = "Warning";
    public const string Error = "Error";
    // etc
}

then:

TempData[TempDataKeys.Message] = "Some message";
like image 22
David Avatar answered Sep 23 '22 23:09

David