Tutorials ASP.NET Core MVC Mastery
ViewModel Pattern
On this page
Mastering Data Passing & ViewModels (The Professional Journey)
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**.
Section 1: The "Dynamic" Ways (Weakly Typed)
1. ViewData (Dictionary)
A case-insensitive dictionary using string keys. ViewData["Title"] = "Home";. Requires type-casting on the View side.
2. ViewBag (Dynamic)
A dynamic wrapper around ViewData. ViewBag.Title = "Home";. Easier to write, but no compile-time checking.
Section 2: The "Expert" Way — The ViewModel Pattern
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.
Why use ViewModels?
- Decoupling: Your View doesn't need to know about your Database Entities (Domain Models).
- Type-Safety: Get IntelliSense and compile-time errors in your Razor code.
- Validation: Use **Data Annotations** directly on the ViewModel properties.
// 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!
}
Section 3: State Persistence with TempData
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!
}
Architect's Choice: PRG Pattern (12-Year Insight)
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.