MVC Pattern in ASP.NET Core

Separate concerns. Controllers handle requests, Models handle data, Views handle UI.

60-Second Version: MVC = Restaurant. Model = Cook + Ingredients, Controller = Waiter taking orders, View = Plated dish customer sees. Waiter never cooks. Cook never serves.

1. Why MVC? Stop Spaghetti Code

Old ASP.NET WebForms: 1.aspx file = UI + DB + logic. Designer breaks SQL. Can't test. Can't scale teams. Prerna changes button color, crashes database call.

MVC fix: 3 files, 3 jobs. Frontend team edits Views. Backend team edits Models. Easy to test each piece.

2. Request Flow: GET /products

Browser: GET /products
    โ†“
Routing: Matches "{controller=Product}/{action=Index}"
    โ†“
ProductController.Index(): var products = _db.Products.ToList();
    โ†“
return View(products); // Looks for Views/Product/Index.cshtml
    โ†“
View: @model List<Product> โ†’ foreach โ†’ <table>
    โ†“
Browser: Gets final HTML. No C# visible.

3. Build It: Your First Page in 3 Files

Goal: Show "Welcome TechStore" at /home/welcome

File 1: Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;

namespace TechStore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Welcome()
        {
            ViewBag.Message = "Welcome TechStore";
            return View(); // Finds Views/Home/Welcome.cshtml
        }
    }
}
File 2: Views/Home/Welcome.cshtml
@{
    ViewData["Title"] = "Welcome";
}

@ViewBag.Message

Your first MVC page works!

Convention: HomeController + Welcome() = Views/Home/Welcome.cshtml. ASP.NET finds it automatically.

File 3: Model? Not needed yet

No database data = no Model. Controller โ†’ View is valid MVC. We'll cover Models in the next tutorial: Models & ViewModels.

Run it: dotnet run โ†’ Go to /home/welcome. You did MVC.
Beginner Trap: Kunal puts SqlConnection in View. Crash on deploy. Fix: Views = HTML only. No DB, no business logic. Controller asks Model for data.

Quick Check ๐Ÿง 

Next: Controllers & Actions - Parameters, IActionResult types, filters, and async patterns.

Comments on MVC Pattern (0)

No comments yet. Be the first to share your thoughts!