ASP.NET Core MVC Mastery

ViewModel Pattern

2 Views Updated 5/4/2026

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.

Senior Warning: Use ViewData/ViewBag only for small, global data (like Page Titles). Never use them to pass complex lists or database objects. It makes debugging impossible!

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.

ASP.NET Core MVC Mastery
1. Core Framework
Introduction to ASP.NET Core MVC
MODULE 1: INTRODUCTION & ENVIRONMENT SETUP
Microsoft Web Stack Overview Evolution of ASP.NET Environment Setup
2. View Engine
Layouts & Partial Views in Razor
MODULE 2: .NET CORE FUNDAMENTALS
Core Concepts Project Structure Startup Flow Middleware Pipeline
MODULE 3: ASP.NET CORE BASICS
Creating Project CLI Commands wwwroot & Static Files
MODULE 4: MVC FUNDAMENTALS
MVC Architecture Dependency Injection (DI) Service Lifetimes
MODULE 5: DATA PASSING TECHNIQUES
ViewData vs ViewBag TempData ViewModel Pattern
MODULE 6: ROUTING
Conventional vs Attribute Routing Custom Constraints
MODULE 7: VIEWS & UI
Razor View Engine Layouts & Sections View Components
MODULE 8: ACTION RESULTS
ViewResult JsonResult RedirectResult
MODULE 9: HTML HELPERS
Form Helpers Custom HTML Helpers
MODULE 10: TAG HELPERS
Built-in Tag Helpers Custom Tag Helpers
MODULE 11: MODEL BINDING
FromQuery vs FromRoute Complex Binding
MODULE 12: VALIDATION
Data Annotations Remote Validation Fluent Validation
MODULE 13: STATE MANAGEMENT
Cookies & Sessions TempData
MODULE 14: FILTERS & SECURITY
Action Filters Authorize Filters Anti-forgery
MODULE 15: ENTITY FRAMEWORK CORE (DEEP DIVE)
DbContext Migrations LINQ Relationships
MODULE 16: DESIGN PATTERNS
Repository Pattern Unit of Work Clean Architecture
MODULE 17: FILE HANDLING
File Upload/Download PDF/Excel Generation
MODULE 18: ADVANCED ASP.NET CORE
Request Lifecycle Bundling & Minification Deployment
MODULE 19: PERFORMANCE & BEST PRACTICES
Caching Strategies Async Programming Secure Coding
MODULE 20: RAZOR PAGES (BONUS)
Razor Pages vs MVC
MODULE 21: REAL-WORLD PROJECTS (🔥 MUST DO)
E-Commerce Web Application Employee Management System