We already finished:
✅ Module 1: .NET Core & ASP.NET
Now moving to:
✅ Module 2: ASP.NET MVC
2.1 What is MVC?
-
MVC stands for Model–View–Controller → It is a design pattern used to separate application logic, UI, and data handling.
-
Components:
-
Model: Represents data & business logic. (e.g.,
Employee
class, database entities). -
View: UI layer that displays data to the user. (e.g.,
.cshtml
Razor files). -
Controller: Handles user requests, interacts with Model, and returns View/JSON.
-
2.2 Benefits of MVC
-
Separation of Concerns → Clear distinction between UI, business logic, and data.
-
Testability → Easy to test Models and Controllers.
-
Scalability → Easy to extend features without affecting other layers.
-
Code Reusability → Reusable Views & Models.
2.3 ASP.NET MVC Lifecycle
-
Request received → Routed to Controller.
-
Controller action executes → Interacts with Model.
-
Model data prepared → Passed to View.
-
View rendered → HTML sent to browser.
2.4 Controllers
-
Controllers handle requests and responses.
-
Example:
public class EmployeeController : Controller
{
public IActionResult Index()
{
var employees = new List<string> { "John", "Mary", "David" };
return View(employees);
}
}
2.5 Models
-
Represent application data.
-
Example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
2.6 Views (Razor Engine)
-
Views use Razor syntax (
@
) for dynamic HTML. -
Example:
@model List<string>
Employee List
@foreach(var emp in Model)
{
- @emp
}
2.7 State Management in MVC
-
TempData → Stores data for a single request.
-
ViewBag → Dynamic object (weakly typed).
-
ViewData → Dictionary (key-value, weakly typed).
-
Strongly Typed Models → Best practice.
2.8 Validation in MVC
-
Done using Data Annotations in Model.
-
Example:
public class Student
{
[Required]
public string Name { get; set; }
[Range(18, 60)]
public int Age { get; set; }
}
-
Razor helper:
@Html.ValidationMessageFor(model => model.Name)
2.9 Routing in MVC
-
Conventional Routing: Defined in
Startup.cs
orRouteConfig
. -
Attribute Routing: Defined on controller methods with
[Route()]
.
📌 Summary for Module 2:
-
MVC = Model + View + Controller (separation of concerns).
-
Know difference between ViewData, ViewBag, TempData.
-
Be ready to write a simple MVC app (Controller → Model → View).