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.,
Userclass with properties likeName,Email). - View: Renders UI using Razor syntax (e.g.,
.cshtmlfiles). - 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:
- Routing: Matches the URL to a controller/action (e.g.,
Home/Index→HomeController.Index()). - Controller Execution: The action method processes the request (e.g., fetches data from a database).
- Model Binding: Converts HTTP data (e.g., form inputs) into strongly typed objects.
- View Rendering: Returns an HTML response (e.g.,
Index.cshtml).
Example (eSewa Payment System): When you pay a bill on eSewa, the flow is:
- You submit payment details (View → Controller).
- The system validates and processes the transaction (Model).
- 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:
- User submits
Start="Thamel"andEnd="Kirtipur"(View →[FromForm]binding). - Controller validates and calls a routing API (Model).
- View renders the optimal path.
6. Routing in ASP.NET Core
Routing maps URLs to controller actions. Two types:
- Conventional Routing: Uses attribute routing (
[Route],[HttpGet]). - 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]bindsstart/endto 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
- You enter a phone number and amount (View →
POST /Recharge/Create). - Controller validates and processes the payment (Model).
- Receipt is generated (View).
In the Real World
eSewa Payments
- Idea Used: MVC architecture for secure transactions.
- How: The
PaymentControllerhandlesPOST /Payrequests, validates amounts (Model), and renders a confirmation page (View).
Daraz E-Commerce
- Idea Used: Routing and CRUD for product management.
- How:
/products/{id}routes toProductsController.Details(), while/cart/adduses[HttpPost]to update the cart (Model).
Ncell Mobile App
- Idea Used: Attribute routing for API endpoints.
- How:
/api/recharge?number=98XXXXXXXXbindsnumbervia[FromQuery]to process recharges.
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.
Khalti Payment Gateway
- Idea Used: Model validation for security.
- How:
[Required]attributes ensure fields likeamountandtransactionIdare never null.
Exam Tip
What Examiners Look For
- Architecture Clarity: Explain MVC separation with a diagram. Avoid mixing Model/Controller logic.
- Routing Precision: Know the difference between
[Route],[HttpGet], and conventional routing. Example:- ❌ Wrong:
GET /Home/Indexwithout[HttpGet]. - ✅ Correct:
[HttpGet]+[Route("home")].
- ❌ Wrong:
- Razor Syntax: Be able to write a loop (
@foreach) or conditional (@if) in a view. - CRUD Flow: Trace a
POSTrequest from View → Controller → Model → Database → Response. - 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.IsValidchecks 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:
- Request Flow:
- User submits a form (View) with
POST /User/Register. - Routing component directs it to
UserController.Register().
- User submits a form (View) with
- 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 } - Model Role:
UserModelclass with[Required]attributes validates input._userServicehandles database operations (e.g., hashing passwords).
- View Role:
Register.cshtmldisplays 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 ResultBased on the TU BIT syllabus for NET Centric Computing (BIT351), unit 4.
Discussion
Loading…