Similar toViewData and ViewBag,TempData isalso used to transfer data to views.However, it will be slightly different, that is,TempDatawill exist until it is read.That is, theViewBaguyuyyuuyandViewDataonly display data at the user’s access page, andTempDatacan be saved and displayed at a later page and it only disappears when the user has “read” it.

For example, the Book Management application has two Book Listing and Book Creation pages.

When the usercreates a new book, it will be sent to theBook Listpagewith a successful book creation message.At this point we will not be able to useViewBagorViewDatato save the message because the message is on another page (Action other).We will useTempDatato save the message on theCreate New Bookpageand display it on theManage Bookpage:

public class BookController : Controller
{
    // Trang Tạo mới Book
    public IActionResult Create()
    {
        // Logic tạo mới Book ...

        // Lưu message vo TempData
        TempData["StatusMessage"] = "Create book successfully";

        // Điều hướng sang trang Danh sch Book
        return RedirectToAction(nameof(Index));
    }

    // Trang Danh sch Book
    public IActionResult Index() 
    {
        // Logic hiển thị Book ...

        // Render View
        return View();
    }
}

 

In addition to the View of theBook Listpage,just display the message:

@TempData["StatusMessage"]

 

Another way is to create a property for the Controller and assign it theTempDataAttributeand then use that property to store the message:

public class BookController : Controller
{
    [TempData]
    public string StatusMessage { get; set; }

    ...
}

 

TempData Provider

There are two types ofTempData Provider:cookie-based(cookie-based) andsession-base(stored in Session).Choosing what kind of provider to use:

  • Whether or not theapplication needs to use theSession state, acookie-based providershould be used.
  • If the data stored in the TempData is large, use asession-based providerbecause the cookie can be restricted by the browser and will increase the cost of the request.

By default, ASP.NET Core 2 uses acookie-base provider, which passes through thesession-base provider andthen has to be configured in theStartup.csfile:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddSessionStateTempDataProvider();
    services.AddSession();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
    app.UseMvcWithDefaultRoute();
}

 

Leave a Comment

Close