7. Passing Data to Views
There are three ways to send data from a controller to a view. The best one is a strongly typed model passed to View(). ViewData and ViewBag carry small extra values for the current request only. TempData survives one redirect, which makes it ideal for success messages after saving.
Key points
- Model: the main data, strongly typed. Preferred.
- ViewData and ViewBag: small extras such as a page title. ViewBag is a dynamic wrapper over ViewData.
- TempData: kept until it is read once, then removed. Useful after a redirect.
Example: ViewBag and TempData
// Controller
public IActionResult Index()
{
ViewBag.Title = "All Students";
return View(students);
}
[HttpPost]
public IActionResult Create(Student s)
{
// save the student...
TempData["Message"] = "Student saved";
return RedirectToAction("Index");
}
// View
<h2>@ViewBag.Title</h2>
<p>@TempData["Message"]</p>
Show explanation
ViewBag.Title is available only on the page that was returned. TempData["Message"] is still available after the redirect, then it disappears.