Explain ViewBag, ViewData, TempData
ViewBag
- ViewBag is a dynamic property that allows you to pass data from a controller to a view. It's a dynamic object, meaning you can add properties to it on the fly without defining them beforehand. It's commonly used when you need to pass a small amount of data from a controller action to a corresponding view.
- We can add any type of data to the ViewBag – strings, integers, objects, etc.
Example : Controller File
using Microsoft.AspNetCore.Mvc;
namespace Test.UI.Controllers
{
public class ConceptsController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Hello, ViewBag!";
return View();
}
}
}
Example : View File
@{
ViewData["Title"] = "Index";
}
<h1>@ViewBag.Message</h1>
ViewData
- ViewData is a dictionary-like container that allows you to pass data from a controller to a view. Unlike ViewBag, ViewData is a dictionary of key-value pairs, and you need to explicitly cast data types when retrieving them in the view. It provides a way to pass data from the controller to the view without using strongly-typed models.
Example:Controller File
using Microsoft.AspNetCore.Mvc;
namespace Test.UI.Controllers
{
public class ConceptsController : Controller
{
public IActionResult Index()
{
ViewData["Message"] = "Hello, ViewData!";
return View();
}
}
}
Example:View File
@{
ViewData["Title"] = "Index";
}
<h1>@ViewData["Message"]</h1>
TempData
- TempData is a dictionary-like object used to pass data from the current request to the next request. Unlike ViewData and ViewBag, which are used to pass data from a controller to a view during the same request, TempData persists data for the subsequent request only. After the next request, the data stored in TempData is automatically removed.
- @Model is used to display the data retrieved from TempData
Example:Controller File
using Microsoft.AspNetCore.Mvc;
namespace Test.UI.Controllers
{
public class ConceptsController : Controller
{
public IActionResult Index()
{
TempData["Message"] = "Hello, TempData!";
return View();
}
public IActionResult NextPage()
{
string message = TempData["Message"].ToString();
return View("NextPage", message);
}
}
}
Example:View File (Next Page/Method)
@{
ViewData["Title"] = "NextPage";
}
<h1>@Model</h1>
Difference between- ViewBag, ViewData, TempData
Feature |
ViewBag |
ViewData |
TempData |
Usage |
Dynamic property |
Dictionary |
Dictionary |
Scope |
Current request |
Current request |
Next request |
Data Removal |
Not required, lasts for the current request |
Not required, lasts for the current request |
Automatically removed after the next request |
Type Safety |
No compile-time checking |
No compile-time checking |
No compile-time checking |
Storage Mechanism |
In memory |
In memory |
By default, in session (can be configured to use cookie-based temp data provider) |
Example |
ViewBag.Message = "Hello, ViewBag!"; |
ViewData["Message"] = "Hello, ViewData!"; |
TempData["Message"] = "Hello, TempData!"; |