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.
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 answerHide 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
.aspxfile 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, andDropDownListcan 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:
RequiredFieldValidatorRangeValidatorRegularExpressionValidatorCompareValidatorCustomValidator
- 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,CreateUserWizardsimplify authentication tasks. - Forms-based authentication is commonly used.
7. Session and Application Management
- Web Forms manage user sessions and application-level data.
Sessionobject stores user-specific data across multiple requests.Applicationobject 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
IsPostBackproperty 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 (
.cshtmlfiles). - 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
| Advantage | Reason |
|---|---|
| Separation of concerns | Data, presentation and request handling live in three different places |
| Testability | Controllers and models are plain classes, so they can be unit tested without a browser |
| Full control of the markup | There is no view state and no server control identifiers, so the HTML is exactly what the developer wrote |
| Clean URLs | Routing maps readable URLs onto controllers and actions |
| Parallel development | One 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.
Controllers and action methods
2081 · 10 marks
How do you create Controllers, Actions and Action results? Explain.[10]
Show solved answerHide 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
Controllerbase class - It is placed inside the
Controllersfolder 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:
- Manually - Create a class file in the Controllers folder following the naming convention.
- 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):
| Attribute | Description |
|---|---|
[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 Type | Helper Method | Description |
|---|---|---|
ViewResult | View() | Renders a view (HTML page) |
PartialViewResult | PartialView() | Renders a partial view |
RedirectResult | Redirect() | Redirects to a URL |
RedirectToRouteResult | RedirectToAction() | Redirects to another action |
ContentResult | Content() | Returns plain text/string content |
JsonResult | Json() | Returns JSON formatted data |
FileResult | File() | Returns a file to download |
EmptyResult | (none) | Returns nothing (void equivalent) |
HttpNotFoundResult | HttpNotFound() | 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 aViewResultwhich 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.
View rendering with HTML
URL routing and features
2080 · 10 marks
Define URL routing with its features. Discuss about ASP.Net core architecture.[10]
Razor templating engine
Make Unit 4 stick
Practice BIT351 with flashcards & quizzes