Asp.Net core Tempdata and redirecttoaction not working

BrilBroeder picture BrilBroeder · Jun 10, 2019 · Viewed 9.6k times · Source

I have a method in my basecontroller class that adds data to tempdata to display pop-up messages.

protected void AddPopupMessage(SeverityLevels severityLevel, string title, string message)
{
    var newPopupMessage = new PopupMessage()
    {
        SeverityLevel = severityLevel,
        Title = title,
        Message = message
    };
    _popupMessages.Add(newPopupMessage);
    TempData["PopupMessages"] = _popupMessages;
}

If the action returns a view, this works fine. If the action is calling a redirectotoaction I get the following error.

InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type

Any thoughts ?

Answer

Chris Pratt picture Chris Pratt · Jun 10, 2019

TempData uses Session, which itself uses IDistributedCache. IDistributedCache doesn't have the capability to accept objects or to serialize objects. As a result, you need to do this yourself, i.e.:

TempData["PopupMessages"] = JsonConvert.SerializeObject(_popupMessages);

Then, of course, after redirecting, you'll need to deserialize it back into the object you need:

ViewData["PopupMessages"] = JsonConvert.DeserializeObject<List<PopupMessage>>(TempData["PopupMessages"]);