Ask
Ask

Reputation: 3726

Storing list in TempData throwing exception

I am trying to store a list in TempData in .net core 2.1. The issue is it doesn't give any error when it's storing the list in tempdata but after return statement, it always throws an exception and throw me to the error section of ajax call. While debugging the error message in ajax call, it just says "error" Here is the controller code:

 IList<Product> productList = new List<Product>
 {
     new Product{ProductId=Guid.NewGuid().ToString(),Name="142525"},
     new Product{ProductId=Guid.NewGuid().ToString(),Name="122555"},
     new Product{ProductId=Guid.NewGuid().ToString(),Name="125255"}
 };

 TempData["Products"] = productList;
 return Json(productList);

Ajax Request:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: '@Url.Action("Index", "Product")',
        success: function (result) {
             alert('All ok');
        },
        error: function (result, err) {
            debugger;
            alert('Something went wrong');
        }
    }); 
}); 

And here is startup file code:

 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
 services.AddSession();

And

    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseCookiePolicy();
    app.UseSession();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    }); 

I have also tried moving app.UseCookiePolicy after app.UseMvc but still no luck. This is Microsoft official doc link https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1#tempdata and I have already tried everything mentioned here. What am I doing wrong?

Upvotes: 0

Views: 1161

Answers (1)

Edward
Edward

Reputation: 29966

Your issue is caused by that TempData did not support complex type.

You could try to serialize the object to string and save it in TempData.

TempData["Products"] = JsonConvert.SerializeObject(productList);

Upvotes: 3

Related Questions