Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net core Tempdata and redirecttoaction not working

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 ?

like image 640
BrilBroeder Avatar asked Jun 10 '19 14:06

BrilBroeder


People also ask

Can we use TempData in .NET core?

TempData in MVC is used to pass data from Controller to Controller or Controller to view and it is used to pass data that persists only from one request to the next. TempData requires Typecasting. And also check for Null value before reading the value from it.

Can TempData persist across action redirects?

TempData is used to pass data from current request to subsequent request (i.e., redirecting from one page to another). Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData by calling the method Keep () .

How do you use TempData in razor view?

Passing the data from Controller to View using TempDataGo to File then New and select “Project” option. Then create the ASP.NET web application project as depicted below. Then select “Empty” and tick “MVC” then click OK. The project is created successfully.

Can TempData be used to pass data from controller to view?

TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller. TempData stores the data temporarily and automatically removes it after retrieving a value. TempData is a property in the ControllerBase class.

Why is my tempdata empty after redirecttoaction()?

My issue was that, after filling in some TempData values and calling RedirectToAction (), TempData would be empty on the page that I was redirecting to. Per HamedH's answer here : If you are running ASP.NET Core 2.1, open your Startup.cs file and make sure that in your Configure () method app.UseCookiePolicy (); comes after app.UseMVC ();.

How do I redirect temp data to a post?

You can not redirect to a post. A redirect is alway a get. Also it looks like you using asp.net core, and the default implementation of temp data is to store it in a cookie. So you should be sure the data is small. As a cookie value is a string, this why tempdata is a string.

What is redirecttoactionresult in MVC?

[Microsoft.AspNetCore.Mvc.NonAction] public virtual Microsoft.AspNetCore.Mvc.RedirectToActionResult RedirectToAction (); The created RedirectToActionResult for the response. A POST request to an action named "Product" updates a product and redirects to an action, also named "Product", showing details of the updated product.

Why tempdata can't be stored in cookies?

By default, data should be stored in cookies only with the user's consent. If the user does not agree with the storing data in cookies, TempData cannot work. This behavior varies across versions of ASP NET Core. If you do not want to hold any sensitive data in cookies, you can obviously change the settings.


2 Answers

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"]);
like image 87
Chris Pratt Avatar answered Nov 03 '22 21:11

Chris Pratt


Another scenario where this type of error happened to me was upgrading from AspNetCore 2.2 to 3.0 - and, where I had AzureAD as an OpenID Connect provider - when it would try to process the AzureAD cookie, it threw an exception the TempDataProvider and complained that it could not serialize a type of Int64. This fixed:

    services.AddMvc()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());

https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

like image 44
David Barrows Avatar answered Nov 03 '22 23:11

David Barrows