📜  如果存在 TempData[] c# (1)

📅  最后修改于: 2023-12-03 14:53:22.826000             🧑  作者: Mango

TempData[] in C#

The TempData[] feature in ASP.NET Core is a special dictionary object that helps us to persist data between requests. We can use it to store data when we redirect from one action to another action.

How to use TempData[]

We can use TempData[] with the help of the following steps:

  1. First, we need to set data in the TempData[] dictionary object.
  2. Then, we can retrieve the data from TempData[] in the redirected action using the TempData[] object.
  3. We can remove TempData[] data after accessing it in the redirected action.
Set data in TempData[]

Example:

public IActionResult Index()
{
    TempData["Message"] = "Hello World!";
    return RedirectToAction("About");
}
Retrieve data from TempData[]

Example:

public IActionResult About()
{
    var message = TempData["Message"];
    return View();
}
Remove TempData[] data

Example:

public IActionResult About()
{
    var message = TempData["Message"];
    TempData.Remove("Message");
    return View();
}
Conclusion

TempData[] enables us to store data temporarily in a dictionary object that can persist between requests. We can use it to pass data from one action to another action in a controller. It is an essential tool for any ASP.NET Core developer.