Hot Posts

Module 2

Document

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

  1. Separation of Concerns → Clear distinction between UI, business logic, and data.

  2. Testability → Easy to test Models and Controllers.

  3. Scalability → Easy to extend features without affecting other layers.

  4. Code Reusability → Reusable Views & Models.


2.3 ASP.NET MVC Lifecycle

  1. Request received → Routed to Controller.

  2. Controller action executes → Interacts with Model.

  3. Model data prepared → Passed to View.

  4. 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 or RouteConfig.

  • 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).