NET Centric ComputingUnit 410 min read

ASP.NET Core MVC: Architecture, Controllers, Views, Models & Routing

Unit 4 of NET Centric Computing explores ASP.NET Core MVC architecture, its three core components (Model-View-Controller), request processing flow, routing mechanisms, and practical implementation of CRUD operations. It covers how to structure controllers, design views with Razor syntax, bind models, and handle HTTP me

Core Concepts of ASP.NET Core MVC

1. MVC Architecture: Model-View-Controller

ASP.NET Core MVC follows the Model-View-Controller (MVC) design pattern, which separates an application into three interconnected components:

classDiagram
    class Model {
        +Data logic
        +Business rules
        +Validation
    }
    class View {
        +UI presentation
        +Razor syntax
        +HTML/CSS rendering
    }
    class Controller {
        +Handles HTTP requests
        +Processes input
        +Returns View/Model
    }
    Model --> View : "Updates"
    View --> Controller : "Displays"
    Controller --> Model : "Queries"

How it works:

  • Model: Manages data, business logic, and validation (e.g., User class with properties like Name, Email).
  • View: Renders UI using Razor syntax (e.g., .cshtml files).
  • Controller: Acts as an intermediary, receiving HTTP requests, processing them, and returning responses (e.g., HomeController).

Real-world analogy: Think of a restaurant:

  • Model = Kitchen (prepares food/data).
  • View = Waiter (presents the dish/UI).
  • Controller = Order taker (handles customer requests).

2. Request Processing Flow

When a user visits a URL (e.g., https://example.com/Home/Index), ASP.NET Core follows this flow:

flowchart TD
    A["User Request"] --> B["Routing Component"]
    B --> C["Controller Action"]
    C --> D["Model Interaction"]
    D --> E["View Rendering"]
    E --> F["Response Sent"]

Key steps:

  1. Routing: Matches the URL to a controller/action (e.g., Home/Index → HomeController.Index()).
  2. Controller Execution: The action method processes the request (e.g., fetches data from a database).
  3. Model Binding: Converts HTTP data (e.g., form inputs) into strongly typed objects.
  4. View Rendering: Returns an HTML response (e.g., Index.cshtml).

Example (eSewa Payment System): When you pay a bill on eSewa, the flow is:

  1. You submit payment details (View → Controller).
  2. The system validates and processes the transaction (Model).
  3. A confirmation page is rendered (View).

3. Controllers and Actions

Controllers are C# classes that inherit from ControllerBase or Controller. Each method is an action that handles HTTP verbs (GET, POST, etc.).

Example: HomeController.cs

public class HomeController : Controller
{
    public IActionResult Index() // GET /Home/Index
    {
        return View(); // Renders Index.cshtml
    }

    [HttpPost]
    public IActionResult SubmitForm(FormModel model) // POST /Home/SubmitForm
    {
        if (ModelState.IsValid)
        {
            // Save to database (Model)
            return RedirectToAction("Success");
        }
        return View(model); // Re-renders with errors
    }
}

Key attributes:

Attribute Purpose Example
[Route] Custom URL mapping [Route("products/{id}")]
[HttpGet] Restricts to GET requests [HttpGet]
[HttpPost] Restricts to POST requests [HttpPost]
[FromBody] Binds JSON from request body [FromBody] User user

Real-world use in Daraz: When you add an item to cart on Daraz, a POST request is sent to CartController.AddItem(), which updates the cart (Model) and redirects to the cart page (View).


4. Views and Razor Syntax

Views are .cshtml files that combine HTML with C# code using Razor syntax. Key directives:

Syntax Purpose Example
@Model Access model data <h1>@Model.Title</h1>
@foreach Loop through collections @foreach(var item in Model.Items)
@Html.ActionLink Generate links to actions @Html.ActionLink("Home", "Index")
@using Import namespaces @using System.Linq

Example: Index.cshtml (Displaying a List)

@model IEnumerable<Product>
<h1>Products</h1>
<table>
    @foreach (var product in Model)
    {
        <tr>
            <td>@product.Name</td>
            <td>@product.Price</td>
        </tr>
    }
</table>

Real-world use in NEPSE: The NEPSE stock dashboard dynamically renders stock prices using Razor to loop through real-time data (@foreach (var stock in Model.Stocks)).


5. Models and Data Binding

Models define the data structure and validation rules. ASP.NET Core automatically binds HTTP data (e.g., form inputs) to model properties.

Example: Product.cs (Model)

public class Product
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Range(1, 1000)]
    public decimal Price { get; set; }
}

Data Binding Scenarios:

Source Binding Attribute Example
Query String [FromQuery] [FromQuery] int? page
Route Data [FromRoute] [FromRoute] int id
Form Data [FromForm] [FromForm] string name
JSON Body [FromBody] [FromBody] User user

Worked Example: Kathmandu Traffic Route Planner Imagine a web app where users input a start/end location. The flow:

  1. User submits Start="Thamel" and End="Kirtipur" (View → [FromForm] binding).
  2. Controller validates and calls a routing API (Model).
  3. View renders the optimal path.

6. Routing in ASP.NET Core

Routing maps URLs to controller actions. Two types:

  1. Conventional Routing: Uses attribute routing ([Route], [HttpGet]).
  2. Attribute Routing: More flexible (e.g., [Route("api/products/{id}")]).

Example: Custom Route Configuration

// Startup.cs
public void Configure(IApplicationBuilder app)
{
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Route Table Example:

URL Path Controller.Action Notes
/Home/Index Home.Index() Default route
/Products/5 Products.Details(5) Route with ID parameter
/api/users Users.Index() API endpoint

Real-world use in Pathao: When you request a ride on Pathao, the URL might be: /ride/request?start=lat1,lon1&end=lat2,lon2

  • [FromQuery] binds start/end to the controller.

7. CRUD Operations in MVC

Create, Read, Update, Delete (CRUD) operations are the backbone of web apps. Example for a Product controller:

Operation HTTP Method Action Method Example Use Case
Create POST Create(Product model) Adding a new product to Daraz
Read GET Details(int id) Viewing a product on eSewa
Update PUT/PATCH Edit(int id, Product model) Editing a profile on Facebook
Delete DELETE Delete(int id) Removing a cart item on Daraz

Example: ProductsController.cs (Partial)

[HttpPost]
public IActionResult Create(Product product)
{
    if (ModelState.IsValid)
    {
        _db.Products.Add(product);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(product);
}

Real-world trace: Ncell Recharge

  1. You enter a phone number and amount (View → POST /Recharge/Create).
  2. Controller validates and processes the payment (Model).
  3. Receipt is generated (View).

In the Real World

  1. eSewa Payments

    • Idea Used: MVC architecture for secure transactions.
    • How: The PaymentController handles POST /Pay requests, validates amounts (Model), and renders a confirmation page (View).
  2. Daraz E-Commerce

    • Idea Used: Routing and CRUD for product management.
    • How: /products/{id} routes to ProductsController.Details(), while /cart/add uses [HttpPost] to update the cart (Model).
  3. Ncell Mobile App

    • Idea Used: Attribute routing for API endpoints.
    • How: /api/recharge?number=98XXXXXXXX binds number via [FromQuery] to process recharges.
  4. NEPSE Stock Dashboard

    • Idea Used: Razor views for dynamic data rendering.
    • How: @foreach (var stock in Model.Stocks) loops through real-time stock prices fetched via Model.
  5. Khalti Payment Gateway

    • Idea Used: Model validation for security.
    • How: [Required] attributes ensure fields like amount and transactionId are never null.

Exam Tip

What Examiners Look For

  1. Architecture Clarity: Explain MVC separation with a diagram. Avoid mixing Model/Controller logic.
  2. Routing Precision: Know the difference between [Route], [HttpGet], and conventional routing. Example:
    • ❌ Wrong: GET /Home/Index without [HttpGet].
    • ✅ Correct: [HttpGet] + [Route("home")].
  3. Razor Syntax: Be able to write a loop (@foreach) or conditional (@if) in a view.
  4. CRUD Flow: Trace a POST request from View → Controller → Model → Database → Response.
  5. Real-World Mapping: Relate concepts to apps like eSewa (validation), Daraz (routing), or NEPSE (dynamic views).

Common Pitfalls

  • Forgetting [HttpPost] for form submissions (leads to 405 errors).
  • Not validating models (causes runtime errors).
  • Hardcoding routes instead of using [Route] attributes.
  • Ignoring ModelState.IsValid checks in controllers.

Sample Exam Question & Answer

Question: "Explain how ASP.NET Core MVC handles a POST /User/Register request. Include the role of the Model, View, and Controller, and show the C# code for the controller action."

Model Answer:

  1. Request Flow:
    • User submits a form (View) with POST /User/Register.
    • Routing component directs it to UserController.Register().
  2. Controller Action:
    [HttpPost]
    public IActionResult Register(UserModel model)
    {
        if (ModelState.IsValid)
        {
            _userService.Register(model); // Model logic
            return RedirectToAction("Login");
        }
        return View(model); // Re-renders with validation errors
    }
    
  3. Model Role:
    • UserModel class with [Required] attributes validates input.
    • _userService handles database operations (e.g., hashing passwords).
  4. View Role:
    • Register.cshtml displays the form and error messages (@Html.ValidationSummary()).

Visual Trace:

sequenceDiagram
    User->>+View: Submits POST /User/Register
    View->>+Controller: Register(UserModel)
    Controller->>Model: Validates & Saves
    Model-->>-Controller: Success/Failure
    Controller-->>-View: Redirect or Re-render
    View-->>-User: Shows Result

Based on the TU BIT syllabus for NET Centric Computing (BIT351), unit 4.

Discussion

Loading…