0

I use TempData for user messages.

When I try to do this, it tells me TempData does not exist in the current context.

public class ServerMessage
{
    public void appendAlertMessage(string message, ServerMessageClass messageClass)
    {
        if(TempData["alertMessage"] == null) 
            TempData["alertMessage"] = message;
        else 
            TempData["alertMessage"] += "\n" + message;

        if(TempData["alertClass"] != ServerMessageClass.Error)
            TempData["alertClass"] = messageClass;

    }
}

public class ServerMessageClass
{
    public const string Success = "success";
    public const string Warning = "warning";
    public const string Error = "error";
}

Is there an alternative way to do this?

Emwat
  • 116
  • 1
  • 15

2 Answers2

0

I believe you are getting a compilation error. TempData is a property of ControllerBase. So you cannot use it outside of a controller class.

Refer to this link:

https://msdn.microsoft.com/en-in/library/system.web.mvc.controllerbase.tempdata(v=vs.118).aspx

From my understandings, it is OK to keep this checking inside the Controller. You can use a private method in the controller but that is not a good practice.

SamGhatak
  • 1,487
  • 1
  • 16
  • 27
0

TempData only exists within the context of the Controller itself.

You may need to consider explicitly inheriting from the Controller class to expose it or consider building your message in your class setting the TempData to the value being returned (i.e. the message).

Ignore The Following (It was just an idea, but isn't supported)

If you are planning on editing it or making changes to it, you could consider passing it in as a reference via the ref keyword and updating it that way :

 // Calling the method (assumingly from your Controller)
 ServerMessage.AppendAlertMessage(string message, ServerMessage messageClass, ref TempData);

Then you should be able to access it within your method :

public void appendAlertMessage(string message, ServerMessageClass messageClass, ref TempDataDictionary tempData)
{
      // Update the TempData using tempData["foo"] = message, etc.
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • It's telling me "A property, indexer or dynamic member access may not be passed as an out or ref parameter" – Emwat Apr 28 '16 at 14:23
  • It was just a thought, but that makes sense. Yeah, you'll probably need to just use your class to actually "build" your messages and then return them and set the `TempData` accordingly. Otherwise, you'll need to explicitly inherit from the `Controller`. – Rion Williams Apr 28 '16 at 14:27