Hello i am trying to  add an object to TempData and redirect to another controller-action. I get error message 500 when using TempData.
public IActionResult Attach(long Id)
{
    Story searchedStory=this.context.Stories.Find(Id);
    if(searchedStory!=null)
    {
        TempData["tStory"]=searchedStory;  //JsonConvert.SerializeObject(searchedStory) gets no error and passes 
        return RedirectToAction("Index","Location");
    }
    return View("Index");
}
public IActionResult Index(object _story) 
{             
    Story story=TempData["tStory"] as Story;
    if(story !=null)
    {
    List<Location> Locations = this.context.Locations.ToList();
    ViewBag._story =JsonConvert.SerializeObject(story);
    ViewBag.rstory=story;
    return View(context.Locations);
    }
    return RedirectToAction("Index","Story");
}
P.S Reading through possible solutions I have added  app.UseSession() to the Configure method and services.AddServices() in the ConfigureServices method but to no avail.Are there any obscure settings i must be aware of?
P.S adding ConfigureServices and UseSession
ConfigureServices
 public void ConfigureServices(IServiceCollection services)
            {
                services.AddOptions();
                services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
                services.AddMvc();
                services.AddSession();
            }
Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
                You have to serialize the object before assigning it to TempData as core only support strings and not complex objects.
TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);
and retrieve the object by deserializing it.
var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
                        You are missing  services.AddMemoryCache(); line in your ConfigureServices() method. Like this:
        services.AddMemoryCache();
        services.AddSession();
        services.AddMvc();
And after that TempData should be working as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With