How you pass data from a Controller to a View determines the maintainability of your entire project. Professional .NET developers avoid "Magic Strings" and embrace **Strongly Typed ViewModels**.
A case-insensitive dictionary using string keys. ViewData["Title"] = "Home";. Requires type-casting on the View side.
A dynamic wrapper around ViewData. ViewBag.Title = "Home";. Easier to write, but no compile-time checking.
A ViewModel is a custom class created specifically for a View. It only contains the data that the View needs to display. This is the **Standard** for any enterprise application.
// 1. The ViewModel (The "Contract")
public class UserProfileViewModel {
public string FullName { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public List RecentLogins { get; set; }
}
// 2. The Controller (The "Mapper")
public IActionResult Profile(int id) {
var user = _db.Users.Find(id); // Domain Model
var viewModel = new UserProfileViewModel {
FullName = user.FirstName + " " + user.LastName,
Email = user.Email,
IsAdmin = user.Role == "Admin",
RecentLogins = user.Logins.Take(5).ToList()
};
return View(viewModel); // Strongly Typed!
}
TempData is used to pass data between two consecutive requests (e.g., from Redirect to Action). It uses Session/Cookies internally.
public IActionResult Save() {
TempData["Success"] = "Product saved successfully!";
return RedirectToAction("Index"); // Data survives this redirect!
}
The Post-Redirect-Get (PRG) pattern is mandatory for any form submission. Instead of returning a View after a POST, you **Redirect** to a GET action. This prevents the "Confirm Form Resubmission" dialog if the user hits refresh, ensuring your database doesn't get duplicate data. This is a non-negotiable standard for professional web apps.