4 Asp Net Core Architecture And Mvc Pattern

NET Centric Computing · Unit 4

ASP.NET Core Architecture and MVC Pattern

Exam-focused notes for ASP.NET Core Architecture and MVC Pattern (NET Centric Computing, BIT351): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

ASP.NET Core Architecture and MVC Pattern in short

ASP.NET Core is the Microsoft framework for building web sites and web APIs. The MVC pattern splits an application into three parts, which keeps large projects organized and easy to test.

ASP.NET Core Architecture and MVC Pattern: notes

ASP.NET Core architecture overview

ASP.NET Core is an open source, cross platform framework that runs on Windows, Linux and macOS. It is a rewrite of the older ASP.NET and is fast and modular.

Main parts of the architecture:

  • Host: starts the app, sets up configuration, logging and dependency injection.
  • Web server: Kestrel is the built in server. It can sit behind IIS, Nginx or Apache.
  • Middleware pipeline: a chain of components that handle each request and response in order. Examples are static files, routing, authentication and authorization.
  • Endpoints: MVC controllers, Razor Pages, minimal APIs and SignalR hubs.
  • Services and configuration: built in dependency injection, and settings from appsettings.json and environment variables.

A request enters the server, passes through each middleware, reaches the endpoint, and the response travels back through the same middleware.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();         // register services

var app = builder.Build();

app.UseStaticFiles();                               // middleware
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

The order of middleware matters. For example, authentication must come before authorization.

MVC pattern components

MVC stands for Model, View, Controller. It separates data, display and request handling.

PartJob
ModelHolds data and business rules. Often talks to the database.
ViewShows data to the user. In ASP.NET Core it is a .cshtml file with Razor.
ControllerReceives the request, uses the model, and picks a view or a result.

Flow of a request:

  • The browser sends a request such as /Books/Details/3.
  • Routing selects the BooksController and its Details action.
  • The action asks the model for the book with id 3.
  • The controller passes the model to a view.
  • The view creates HTML, and the response goes to the browser.

Advantages: clear separation of concerns, easy unit testing of controllers, several views for one model, and teams can work in parallel.

// Model
public class Book { public int Id { get; set; } public string Title { get; set; } }

// Controller
public class BooksController : Controller
{
    public IActionResult Details(int id)
    {
        var book = new Book { Id = id, Title = "C# Basics" };
        return View(book);                 // sends the model to Views/Books/Details.cshtml
    }
}
@model Book
<h2>@Model.Title</h2>

What this unit covers

  • ASP.NET Core architecture overview
  • MVC pattern components
  • Controllers and action methods
  • Action results
  • URL routing and features
  • View rendering with HTML
  • Razor templating engine

MVC pattern components

2081 · 10 marks

What are the tasks of ASP. NET web forms? Explain the MVC pattern of ASP.NET.[10]

Show solved answer

ASP.NET Web Forms and MVC Pattern


Part 1: Tasks of ASP.NET Web Forms

ASP.NET Web Forms is a web application framework that provides an event-driven programming model for building dynamic web pages. The major tasks of ASP.NET Web Forms are:

1. Page Rendering

  • Web Forms handle the rendering of HTML pages to the client browser.
  • The .aspx file contains the UI markup and the code-behind file (.aspx.cs) contains the logic.
  • The framework automatically generates HTML from server controls.

2. Event Handling

  • Web Forms support an event-driven model similar to Windows Forms.
  • Events like Button_Click, Page_Load, TextChanged, etc. are handled on the server side.
  • The framework manages the round-trip between client and server for event processing.

3. State Management

  • Web Forms manage ViewState to preserve the state of controls across postbacks.
  • Other state management techniques include Session, Application, Cookies, and QueryString.
  • ViewState is stored as a hidden field in the HTML page.

4. Data Binding

  • Web Forms provide powerful data binding capabilities.
  • Controls like GridView, DataList, Repeater, and DropDownList can be bound to data sources.
  • Supports binding to databases, XML, collections, and other data sources.

5. Validation

  • Web Forms include built-in validation controls such as:
    • RequiredFieldValidator
    • RangeValidator
    • RegularExpressionValidator
    • CompareValidator
    • CustomValidator
  • Both client-side and server-side validation are supported.

6. User Authentication and Authorization

  • Web Forms integrate with ASP.NET membership and role providers.
  • Controls like Login, LoginView, CreateUserWizard simplify authentication tasks.
  • Forms-based authentication is commonly used.

7. Session and Application Management

  • Web Forms manage user sessions and application-level data.
  • Session object stores user-specific data across multiple requests.
  • Application object stores data shared across all users.

8. Master Pages and Themes

  • Web Forms support Master Pages for consistent layout across multiple pages.
  • Themes and Skins allow uniform styling of controls throughout the application.

9. Postback Mechanism

  • Web Forms use a postback mechanism where form data is submitted back to the same page.
  • The IsPostBack property is used to distinguish between the first load and subsequent postbacks.

10. Code-Behind Model

  • Web Forms separate UI design (.aspx) from business logic (.aspx.cs).
  • This promotes cleaner code organization and maintainability.

Part 2: MVC Pattern of ASP.NET

What is MVC?

MVC (Model-View-Controller) is a software architectural pattern that separates an application into three interconnected components. ASP.NET MVC is Microsoft's implementation of this pattern for building web applications.

+------------------+       +------------------+       +------------------+
|      MODEL       |<----->|   CONTROLLER     |<----->|      VIEW        |
|                  |       |                  |       |                  |
| - Data           |       | - Request Handler|       | - UI Display     |
| - Business Logic |       | - Coordinates M&V|       | - Presentation   |
| - Data Access    |       | - Action Methods |       | - Razor Templates|
+------------------+       +------------------+       +------------------+
                                    ^
                                    |
                               HTTP Request
                               from Browser

The Three Components

1. Model

  • The Model represents the data and business logic of the application.
  • It is responsible for:
    • Retrieving data from the database
    • Validating data
    • Storing and updating data
    • Representing the application's data structure
  • In ASP.NET MVC, models are typically C# classes that represent entities.
  • Example:
public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
}

2. View

  • The View is responsible for displaying the data (UI presentation layer).
  • It receives data from the Controller and renders it as HTML.
  • In ASP.NET MVC, Views use Razor syntax (.cshtml files).
  • The View should contain no business logic -- only presentation logic.
  • Example:
@model Student
<h2>Student Details</h2>
<p>Name: @Model.Name</p>
<p>Email: @Model.Email</p>
<p>Age: @Model.Age</p>

3. Controller

  • The Controller acts as the intermediary between Model and View.
  • It handles incoming HTTP requests, processes them, interacts with the Model, and returns the appropriate View.
  • Controllers contain Action Methods that respond to user requests.
  • Example:
public class StudentController : Controller
{
    public ActionResult Index()
    {
        Student student = new Student
        {
            StudentId = 1,
            Name = "Ram Sharma",
            Email = "[email protected]",
            Age = 20
        };
        return View(student);
    }
}

How MVC Works: Request Flow

The flow of a request in ASP.NET MVC is as follows:

Step 1: User sends HTTP Request (e.g., /Student/Index)
           |
           v
Step 2: Routing Engine maps URL to Controller and Action Method
           |
           v
Step 3: Controller's Action Method is invoked
           |
           v
Step 4: Controller interacts with Model (fetch/update data)
           |
           v
Step 5: Controller passes Model data to View
           |
           v
Step 6: View renders the HTML using the Model data (Razor engine)
           |
           v
Step 7: Rendered HTML response is sent back to the browser

Advantages of the MVC Pattern in ASP.NET

AdvantageReason
Separation of concernsData, presentation and request handling live in three different places
TestabilityControllers and models are plain classes, so they can be unit tested without a browser
Full control of the markupThere is no view state and no server control identifiers, so the HTML is exactly what the developer wrote
Clean URLsRouting maps readable URLs onto controllers and actions
Parallel developmentOne team can work on views while another works on models and controllers

Conclusion

ASP.NET Web Forms hides HTTP behind an event-driven, control-based page model, with postback, view state and the code-behind file doing the work, which makes a page quick to build but harder to test and heavier on the wire. ASP.NET MVC replaces that with three explicit roles: the Model holds the data and business rules, the View renders it with Razor, and the Controller receives the routed request, drives the Model and selects the View. The request flow above shows the whole cycle, and it is the reason MVC gives clean URLs, testable code and complete control over the generated markup.

Open this answer on its own page →

2081.1 · 5 marks

Describe the MVC pattern in ASP.NET. [5]

MVC (Model-View-Controller) is a software architectural design pattern that separates an application into three interconnected components, promoting organized code, separation of concerns, and easier maintainability. --- - Represents the data and business logic of the application - Responsible fo...

Open this answer on its own page →

Controllers and action methods

2081 · 10 marks

How do you create Controllers, Actions and Action results? Explain.[10]

Show solved answer

Controllers, Actions, and Action Results in ASP.NET MVC

Note: The reference notes did not contain specific content on this topic. The following answer is based on standard ASP.NET MVC curriculum as taught in TU BSc CSIT, using correct and widely accepted terminology.


1. Controllers in ASP.NET MVC

A Controller is a class that handles incoming HTTP requests, processes user input, interacts with the model, and returns an appropriate response (view or data).

Rules for Creating a Controller:

  • The class name must end with "Controller" (e.g., HomeController)
  • It must inherit from the Controller base class
  • It is placed inside the Controllers folder of the MVC project
  • It must be a public class

Syntax to Create a Controller:

using System.Web.Mvc;

namespace MyApp.Controllers
{
    public class HomeController : Controller
    {
        // Actions go here
    }
}

Ways to Create a Controller:

  1. Manually - Create a class file in the Controllers folder following the naming convention.
  2. Using Scaffolding - Right-click on Controllers folder > Add > Controller > Select template (Empty, with Read/Write actions, etc.)

2. Actions in ASP.NET MVC

An Action is a public method inside a controller that responds to a specific HTTP request (GET, POST, etc.).

Rules for Action Methods:

  • Must be a public method
  • Must not be static
  • Must not have [NonAction] attribute (unless intentionally excluded)
  • Returns an ActionResult or its derived types

Example of Action Methods:

public class StudentController : Controller
{
    // Action for GET request
    public ActionResult Index()
    {
        return View();
    }

    // Action for displaying details
    public ActionResult Details(int id)
    {
        // fetch student by id
        return View();
    }

    // Action for GET - show form
    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    // Action for POST - submit form
    [HttpPost]
    public ActionResult Create(Student student)
    {
        if (ModelState.IsValid)
        {
            // save to database
            return RedirectToAction("Index");
        }
        return View(student);
    }
}

Action Selectors (Attributes):

AttributeDescription
[HttpGet]Handles GET requests
[HttpPost]Handles POST requests
[HttpPut]Handles PUT requests
[HttpDelete]Handles DELETE requests
[ActionName("name")]Assigns a different name to the action
[NonAction]Excludes a public method from being an action

3. Action Results in ASP.NET MVC

An ActionResult is the return type of an action method. It is an abstract base class from which all specific result types are derived. It represents the result of executing an action method.

Common ActionResult Types:

ActionResult TypeHelper MethodDescription
ViewResultView()Renders a view (HTML page)
PartialViewResultPartialView()Renders a partial view
RedirectResultRedirect()Redirects to a URL
RedirectToRouteResultRedirectToAction()Redirects to another action
ContentResultContent()Returns plain text/string content
JsonResultJson()Returns JSON formatted data
FileResultFile()Returns a file to download
EmptyResult(none)Returns nothing (void equivalent)
HttpNotFoundResultHttpNotFound()Returns 404 error

Examples of Different Action Results:

public class DemoController : Controller
{
    // Returns a View
    public ActionResult Index()
    {
        return View();
    }

    // Returns JSON data
    public JsonResult GetData()
    {
        var data = new { Name = "Ram", Age = 20 };
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    // Returns plain content
    public ContentResult ShowMessage()
    {
        return Content("Hello from ASP.NET MVC!");
    }

    // Redirects to another action
    public ActionResult GoHome()
    {
        return RedirectToAction("Index", "Home");
    }

    // Returns a file
    public FileResult DownloadFile()
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(
            Server.MapPath("~/Files/sample.pdf"));
        return File(fileBytes, "application/pdf", "sample.pdf");
    }

    // Returns 404
    public ActionResult FindStudent(int id)
    {
        if (id <= 0)
            return HttpNotFound();
        return View();
    }
}

4. Summary Diagram

HTTP Request
     |
     v
  Controller  (inherits Controller class)
     |
     v
  Action Method  (public method, returns ActionResult)
     |
     v
  ActionResult  (ViewResult / JsonResult / RedirectResult ...)
     |
     v
  HTTP Response (HTML / JSON / File / Redirect ...)

5. Key Points to Remember

  • A Controller handles requests and inherits from Controller.
  • An Action is a public method inside a controller that processes a request.
  • An ActionResult is the return type that determines what response is sent back to the client.
  • The View() method returns a ViewResult which renders an HTML page.
  • RedirectToAction() is used to redirect from one action to another.
  • Json() is used in AJAX-based applications to return JSON data.
Open this answer on its own page →

View rendering with HTML

2081 · 5 marks

How rendering HTML with views is done? Explain. [5]

In Express.js (Node.js framework), rendering HTML with views means generating and sending dynamic HTML pages to the client using a template engine. Instead of writing static HTML, views allow embedding dynamic data into HTML templates. --- The most commonly used template engine with Express is EJ...

Open this answer on its own page →

URL routing and features

2080 · 10 marks

Define URL routing with its features. Discuss about ASP.Net core architecture.[10]

--- URL Routing is a mechanism in ASP.NET Core that maps incoming HTTP request URLs to specific controller actions or middleware handlers. Instead of mapping URLs directly to physical files on the server, routing interprets the URL pattern and dispatches the request to the appropriate handler (co...

Open this answer on its own page →

Razor templating engine

0 · 5 marks

Explain about Razor. [5]

Razor is a markup syntax (view engine) used in ASP.NET MVC and ASP.NET Core for creating dynamic web pages by embedding server-side code (C or VB.NET) directly into HTML markup. Note: Reference notes were not available for this topic; the following is based on standard ASP.NET curriculum content ...

Open this answer on its own page →