0

i need help for understand when use tempdata what happen. if i use tempdata in view , if two users synchronous go to the view , what happen for tempdata? I mean, whether the data is dropping, or whether the two tempdata will be different and will function properly.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203

2 Answers2

2

First of all the TempData is based on Sessions so every user has it's own session that's why it doesn't have any problem if two user use same page at a same time.

Here is a sample code how you can implement you have to add a Session Middleware to the ASP.NET Core Pipeline. Otherwise it always will be null. You will not get any error!

services.AddSession(); // Add in 'Startup.cs' file 'ConfigureServices' method

You also need a TempData Provider.

services.AddSingleton<ITempDataProvider, CookieTempDataProvider>(); // Add in 'Startup.cs' file 'ConfigureServices' method

Here it is a cookie provider which means all TempData stuff will be put into a cookie from request A and will be read again in request B.

Now you also have to use the Session registration:

app.UseSession(); // Add in 'Startup.cs' file 'Configure' method

Finally you your startup.cs look like this

Source

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.

    services.AddMvc();

    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
    services.AddSession();

    // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseDeveloperExceptionPage();

    app.UseStaticFiles();

    app.UseSession();

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

Now you can use the TempData to pass data from one action to another.

public class TempDataDemoController : Controller
{
    public IActionResult RequestA()
    {
        ViewData["MyKey"] = "Hello TempData!";

        return RedirectToAction("RequestB");
    }

    public IActionResult RequestB()
    {
        return Content(ViewData["MyKey"] as string);
    }
}
Muhammad Asad
  • 1,772
  • 16
  • 23
0

TempData in ASP.NET MVC can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.

TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects.

Please refer to this tutorial - https://www.tutorialsteacher.com/mvc/tempdata-in-asp.net-mvc

and this thread - Using Tempdata in ASP.NET MVC - Best practice