0% found this document useful (0 votes)
2 views

CoreMVC1

The document introduces the Model-View-Controller (MVC) design pattern and the ASP.NET Core MVC framework, explaining their components and functionalities. It outlines the roles of Model, View, and Controller in managing application data, user interface, and request handling, respectively. Additionally, it discusses the features of ASP.NET Core MVC, guidelines for choosing between ASP.NET MVC and ASP.NET Core MVC, and provides instructions for setting up MVC in an ASP.NET Core application.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CoreMVC1

The document introduces the Model-View-Controller (MVC) design pattern and the ASP.NET Core MVC framework, explaining their components and functionalities. It outlines the roles of Model, View, and Controller in managing application data, user interface, and request handling, respectively. Additionally, it discusses the features of ASP.NET Core MVC, guidelines for choosing between ASP.NET MVC and ASP.NET Core MVC, and provides instructions for setting up MVC in an ASP.NET Core application.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Introduction to ASP.

NET Core MVC Framework

I will briefly introduce the Model View Controller Pattern and ASP.NET Core
MVC Framework. MVC is a Design Pattern, and ASP.NET Core MVC is a framework
based on the MVC Design Pattern. As part of this article, we will discuss the
following pointers.

1. What is MVC?
2. How Does MVC Design Pattern Work in ASP.NET Core?
3. What is ASP.NET Core MVC?
4. Features of ASP.NET Core MVC
5. When to Choose ASP.NET MVC and When to Choose ASP.NET Core
MVC?

What is MVC?

MVC stands for Model View and Controller. It is an Architectural Design Pattern,
which means it is used at the application’s architecture level. So, MVC is not a
programming language, not a Framework. It is a Design Pattern. When we design
an application, we first create its architecture, and MVC plays an important role in
designing that architecture.

The MVC Design Pattern is used to develop interactive applications. An interactive


application involves user interaction, and based on the user interaction, some
event handling occurs. The most important point you need to remember is that it
is not only used for developing Web-Based Applications; we can also use this MVC
Design Pattern to develop Desktop or Mobile-Based applications.

The MVC (Model-View-Controller) Design Pattern was introduced in the 1970s. It


divides an application into three major components: Model, View, and Controller.
The main objective of the MVC Design Pattern is the separation of concerns. This
means the Domain Model and Business Logic are separated from the User
Interface (i.e., View). As a result, maintaining and testing the application become
simpler and easier.

How Does MVC Design Pattern Work in ASP.NET Core?

Let’s look at an example to understand how the MVC Design Pattern works in an
ASP.NET Core MVC application. We want to design an application that displays the
student details on a web page, as shown below.

So, when we request something like https://localhost:7132/Student/Details/2


from a web browser, the following things happen to handle the request.

1
The Controller is the Component in the MVC design pattern that handles the
incoming request. The controller components do several things to handle the
request. The controller component creates the model that is required by a view.
The model is the component in the MVC design pattern, which basically contains
classes that are used to store the domain data or, you can say, business data. In
the MVC design pattern, the Model component also contains the required logic to
retrieve data from a database.

Once the controller creates the model, it selects a view to render the domain or
model data. While selecting a view, it is also the controller’s responsibility to pass
the model data. In the MVC design pattern, the view’s only responsibility is
rendering the model data. So, in MVC, the view is the component responsible for
generating the necessary HTML to render the model data. Once the view
generates the HTML, that HTML is sent to the client over the network who initially
made the request.

The three major components of an ASP.NET Core MVC Application are the Model,
View, and Controller. Let’s discuss each component of the MVC design pattern in
detail.

Role of Model in MVC Design Pattern:

The Model in an MVC application represents the application’s state and business
logic. That means the Model is the component in the MVC Design pattern used to
manage the data, i.e., the application’s state in memory. The Model represents a
set of classes used to describe the application’s validation, business, and data
access logic. So, in our example, the model consists of Student and
StudentBusinessLayer classes.

Student.cs

namespace ASPNETCoreMVCApplication.Models

public class Student

public int StudentID { get; set; }

2
public string? Name { get; set; }

public string? Gender { get; set; }

public string? Branch { get; set; }

public string? Section { get; set; }

StudentBusinessLayer.cs

namespace ASPNETCoreMVCApplication.Models

public class StudentBusinessLayer

public IEnumerable<Student> GetAll()

//logic to return all employees

return new List<Student>();

public Student GetById(int StudentID)

//logic to return an employee by employeeId

Student student = new Student()

StudentID = StudentID,

Name = "James",

Gender = "Male",

3
Branch = "CSE",

Section = "A2",

};

return student;

public void Insert(Student student)

//logic to insert a student

public void Update(Student student)

//logic to Update a student

public void Delete(int StudentID)

//logic to Delete a student

In our example, we use the Student class to hold the student data in memory. The
StudentBusinessLayer class manages the student data, performs the CRUD
operation, Validates the Student data, etc.

So, in short, we can say that a Model in the MVC Design Pattern contains a set of
classes used to represent the data and the logic to manage those data. In our
example, the Student class represents the data. The StudentBusinessLayer class
manages the student data, validates it, and stores it in the database.

Key Responsibilities of Models:

4
 Retrieve and store data in the database or other storage mechanisms.
 Provide data to the controller as needed.
 Respond to instructions from the controller to update itself (e.g., updating
data points).
Role of View in MVC Design Pattern:

The View is the Component in the MVC Design pattern that contains the logic to
represent the model data as a user interface with which the end-user can interact.
Basically, the view renders the domain data (i.e., business data) provided by the
controller. There should be minimal logic (you should not write any business logic,
calculation logic, validation logic, etc.) within views, and any logic in them should
only be related to presenting the content.

For example, we want to display Student data on a web page. The student model
carried the student data to the view. As already discussed, the view’s one and
only responsibility is to render the model data, in this case, student model data.
The following code does the same thing.

@model ASPNETCoreMVCApplication.Models.Student

<html>

<head>

<title>Student Details</title>

</head>

<body>

<br />

<br />

<table>

<tr>

<td>Student ID: </td>

<td>@Model.StudentID</td>

</tr>

<tr>

<td>Name: </td>

<td>@Model.Name</td>

5
</tr>

<tr>

<td>Gender: </td>

<td>@Model.Gender </td>

</tr>

<tr>

<td>Branch: </td>

<td>@Model.Branch</td>

</tr>

<tr>

<td>Section: </td>

<td>@Model.Section </td>

</tr>

</table>

</body>

</html>

Key Responsibilities of Views:

 Display the data provided by the controller in a format suitable for


interaction.
 Send user inputs (like button clicks or data entries) to the controller.
 Update the visual presentation when the data in the model changes.
Role of Controller in MVC Design Pattern:

The Controller is the component in an MVC application that handles the incoming
HTTP Request. Based on the user action, the respective controller might work with
the model, select a view to render the information, and then send the response
back to the user who initially made the request. So, the Controller is the
component that will interact with both the models and views to control the
application execution flow.

In ASP.NET Core MVC Application, a Controller is a .cs (for C# language) file with
some methods called Action Methods. When a request comes on the controller,
the controller’s action method handles those requests. In our example, when the
user issued a request, the following URL

6
https://localhost:7132/Student/Details/2

Then, that request is mapped to the Details action method of the Student
Controller using the Routing defined for our application.

using ASPNETCoreMVCApplication.Models;

using Microsoft.AspNetCore.Mvc;

namespace ASPNETCoreMVCApplication.Controllers

public class StudentController : Controller

public ActionResult Details(int studentId)

StudentBusinessLayer studentBL = new StudentBusinessLayer();

Student studentDetail = studentBL.GetById(studentId);

return View(studentDetail);

As you can see in the example, the Student Controller creates the Student object
within the Details action method. So, here, the Student is the Model. The
controller uses the StudentBusinessLayer class to fetch the Student data from the
database.

Once the controller creates the Student model with the necessary student data, it
passes the Student model to the Details view. The Details view then generates
the necessary HTML to present the Student data. Once the HTML is generated, it
is sent to the client over the network who initially made the request.

Key Responsibilities of Controllers:

 Handle user input and convert it to commands for the Model or View.

7
 Decide what response to send back to a user when a user makes a browser
request.
 Update the Model when the user manipulates it through the View.
 Select the appropriate View to present the data from the Model.
Note: The Controller and View depend on the Model in the MVC Design Pattern,
but the Model never depends on either View or Controller. This is one of the main
reasons for the separation of concerns, which allows us to build and test the
model independently of the visual presentation.

What is ASP.NET Core MVC?

ASP.NET Core MVC is a web application development framework developed by


Microsoft. It is a modern implementation of the Model-View-Controller (MVC)
architectural pattern designed to build dynamic web applications and web APIs. It
is part of the ASP.NET Core platform, a cross-platform, high-performance
framework for building modern, cloud-based, and internet-connected applications.
So, the point that you need to remember is that MVC is a Design Pattern, and
ASP.NET Core MVC is a Framework based on the MVC Design Pattern.

Features of ASP.NET Core MVC:

The ASP.NET Core MVC Framework comes with some amazing features. They are
as follows:

 Open Source: The ASP.NET Core MVC Framework is open source, which is
the main reason for its popularity. The Entire Source Code of ASP.NET Core
MVC Framework is available at https://github.com/aspnet, and you are
free to download the source code; even if you want, you can also modify
and compile your own version.
 Built-In Dependency Injection: ASP.NET Core has built-in support for
dependency injection, which helps manage dependencies between objects,
making the system more modular, scalable, and testable.
 Rich Routing: ASP.NET Core MVC provides a robust routing mechanism
that allows developers to control web application URLs. It supports pattern-
based URL mapping, which helps define SEO-friendly URLs.
 Support for Web APIs: ASP.NET Core MVC can be used to develop
RESTful HTTP services. It fully supports formatting response data as JSON or
XML and can easily handle different content types with content negotiation.
 Extensive Built-In Middleware: The framework provides extensive built-
in middleware components that can handle requests for authentication,
routing, session state, and more. Developers can also create custom
middleware.
 Tag Helpers: Tag Helpers enable server-side code to participate in
creating and rendering HTML elements in Razor files.

When to Choose ASP.NET MVC and When to Choose ASP.NET Core MVC?

Choosing between ASP.NET MVC and ASP.NET Core MVC depends on various
factors, including project requirements, existing infrastructure, performance
needs, and future maintenance considerations. The following are some of the
guidelines to help you decide:

ASP.NET MVC:

1. If you are currently working on an existing application with ASP.NET MVC


and would like to expand the functionalities by adding new features.

8
2. If your team is familiar with ASP.NET MVC Framework but has yet to gain
experience with ASP.NET Core MVC.
3. If you want, your application will only be compatible with devices and
servers that run on the Windows operating system.
ASP.NET Core MVC:

1. If you have a preference for utilizing a framework that is completely open


source.
2. If you want your application to be able to be developed and hosted on any
operating system.
3. If your team members have knowledge of ASP.NET Core MVC.
4. If you are looking for an application development framework with a long
development roadmap ahead of it, look at .NET’s roadmap. Microsoft has
already provided it for the next five years.

How to Set up MVC in ASP.NET Core Application

In this article, I will discuss how to set up MVC in ASP.NET Core Web
Application step by step with Examples.

In ASP.NET Core (.NET), it is possible to build an entire application using only the
ASP.NET Core Middleware component. However, the ASP.NET Core MVC
framework provides the features we can use to create HTML Pages and HTTP-
based APIs easily. So, I will show you how to set up MVC in the ASP.NET Core
Application.

Creating a new ASP.NET Core Empty Application:

Let us first create an empty ASP.NET Core application. To create a new Empty
ASP.NET Core Web Application, open Visual Studio 2022 and click the Create a
new project tab, as shown in the image below.

A
Once you click on the Create a new project tab, the Create a new project window
will open. In this window, select the ASP.NET Core Empty project template and
click the Next button, as shown in the image below.

9
Once
you click on the Next button, it will open the Configure Your New Project window.
Here, provide the necessary information to create a new project. First, give an
appropriate name for your project (FirstCoreMVCWebApplication), set the
location where you want to create this project, and the solution name for the
ASP.NET Core Web application. And finally, click on the Create button, as shown in
the image below.

Once you click on the Next button, it will open the Additional Information window.
Here, you need to select .NET Framework. You also need to check the Configure
for HTTPS and do not use top-level statements check boxes. Finally, click the
Create button, as shown in the image below.

10
Once you click the Create button, a new ASP.NET Core Web Application will be
created in Visual Studio 2022 using .NET 8. The project will have the following file
and folder structure.

By default, the Empty template does not include the MVC setup. Let’s see how to
set up MVC in the ASP.NET Core application.

How to Setup MVC in ASP.NET Core Application:

Setting up the MVC (Model-View-Controller) in the ASP.NET Core Application


involves two steps: Configuring the Required MVC Services and Middleware
Components in the Request Processing Pipeline.

Adding MVC Service to the Request Processing Pipeline:

First, we need to add the required MVC services to the Application Request
Processing Pipeline. To do so, we need to modify the Main method of
the Program class as follows. The builder.Service.AddMVC() statement will
include all the services required to develop the ASP.NET Core MVC application.
Once you add this, you can use Models, Controllers, Views, TempData, ViewData,
ViewBag, and many other features in your ASP.NET Core MVC Application.

11
Note: In ASP.NET Core, along with the AddMVC() method, we also have the
AddControllersWithViews() method.

Adding Controller in ASP.NET Core MVC Application:

In the ASP.NET Core MVC application, all the Controllers should be in a specific
folder named Controllers. So first, create a folder named Controllers within the
project root directory. Once you add the Controllers folder, add a new class file
named HomeController.cs within the Controllers folder. Once you add the
HomeController class, your project folder structure should look as shown below.

Now open the HomeController.cs class file and copy and paste the following
code. To make a class as a controller in ASP.NET Core MVC, that class must be
inherited from the Controller base class. So, you can see in the below code that
our controller, i.e., HomeController, is inherited from the Controller base class.
This Controller base class belongs to Microsoft.AspNetCore.Mvc namespace.

using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
public class HomeController : Controller

12
{
public string Index()
{
return "This is Index action from MVC Controller";
}
}
}
With the above changes in place, now run the application, and you will get the
following output.

We are not getting the output from the HomeController’s Index action method.
The above output comes from the MapGet method, which you can find within the
Program class’s Main method.

How Do We Configure our Index Action Method of HomeController as the


Default Route?

We need to tell the ASP.NET Core MVC Framework to use the Index action method
of our Home Controller as the default route. To do so, we must add the Required
MVC Middleware Component (UseRouting and MapDefaultControllerRoute) to
the application request processing pipeline.

UseRouting Middleware in ASP.NET Core:

The UseRouting middleware adds the routing capabilities to the request


processing pipeline. Its primary objective is to match incoming HTTP requests to
the corresponding route endpoint definitions.

 By adding UseRouting, we enable the application to use route matching.


 It matches the incoming request URL to the routes that are defined in the
application. This is essential for directing requests to the appropriate
controllers and actions.

13
It should be placed before middleware, which depends on route matching,

such as MapDefaultControllerRoute.
 Syntax: app.UseRouting();
MapDefaultControllerRoute Middleware in ASP.NET Core:

The MapDefaultControllerRoute method is a shorthand method to configure the


default route for MVC controllers. Its primary objective is to set up a conventional
routing pattern that maps URLs to controllers and actions using a predefined
template.

It uses the default routing


template {controller=Home}/{action=Index}/{id?}. This means that if
no specific route is provided, the request will be directed to the
HomeController and its Index action.
 This method ensures that requests are routed to the appropriate controller
and action method based on the URL.
 Syntax: app.MapDefaultControllerRoute();
So, modify the Main Method of the Program class as shown below.
The UseRouting() and MapDefaultControllerRoute() Middleware
Components add the MVC Middleware to the Request Processing Pipeline.

namespace FirstCoreMVCWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Create a WebApplication builder, which provides various configuration settings
// and services for the web application
var builder = WebApplication.CreateBuilder(args);
// Add MVC services to the service container.
// This includes support for controllers and views.
builder.Services.AddMvc();
// Build the application using the configured builder
var app = builder.Build();
// Enable routing middleware, which matches incoming HTTP requests to
endpoints defined in the application
app.UseRouting();
// Map the default controller route (convention:
{controller=Home}/{action=Index}/{id?})
// This means if no specific route is provided, it will default to HomeController and
Index action
app.MapDefaultControllerRoute();
// Run the application, which blocks the calling thread and starts listening for
incoming HTTP requests
app.Run();
}

14
}
}
Run the application, and you should get the expected output, as shown in the
image below.

How do we specify a custom controller and action method?

The MapDefaultControllerRoute() middleware uses Home as the default Controller


and Index as the default action method for our application. This is why when we
run the application, the Index action method of the Home Controller handles the
request. But you can also change this default behavior. To do so, we need to use
the MapControllerRoute Middleware component instead of the
MapDefaultControllerRoute() middleware and specify the default controller and
action.

MapControllerRoute Middleware Component:

The MapControllerRoute method is used to define a custom route for MVC


controllers in an ASP.NET Core application. Its primary objective is to map
incoming HTTP requests to specific controllers and actions based on a defined URL
pattern.

 It allows us to specify custom URL patterns that map to controllers and


actions, providing flexibility in how URLs are structured.
 It also defines a custom URL pattern that specifies how URLs should be
parsed and matched to controller actions.
 We can also define multiple routes using MapControllerRoute to handle
different URL patterns and route them to different controllers and actions.
So, modify the Main method of the Program class to use the MapControllerRoute
Middleware component instead of the MapDefaultControllerRoute() middleware as
follows.

namespace FirstCoreMVCWebApplication
{
public class Program
{
public static void Main(string[] args)
{
// Create a WebApplication builder, which provides various configuration settings
// and services for the web application
var builder = WebApplication.CreateBuilder(args);

15
// Add MVC services to the service container.
// This includes support for controllers and views.
builder.Services.AddMvc();
// Build the application using the configured builder
var app = builder.Build();
// Enable routing middleware, which matches incoming HTTP requests to
endpoints defined in the application
app.UseRouting();
// Map the default controller route (convention:
{controller=Home}/{action=Index}/{id?})
// This means if no specific route is provided, it will default to HomeController and
Index action
app.MapControllerRoute(
name: "default", // Name of the route
pattern: "{controller=Home}/{action=Index}/{id?}" // URL pattern for the route
);
// Run the application, which blocks the calling thread and starts listening for
incoming HTTP requests
app.Run();
}
}
}
Now, run the application, and you should get the output as expected.

So, in short, to set up MVC in the ASP.NET Core Web Application, we first need to
add the required MVC Services to the dependency injection container and then
configure the required MVC Middleware Components to the Request Processing
Pipeline.

AddController vs AddMvc vs AddControllersWithViews vs AddRazorPages

I will discuss the differences between AddController() vs AddMvc() vs


AddControllersWithViews() vs AddRazorPages() Methods in ASP.NET Core
Web Application. We will also discuss when to use what methods in ASP.NET Core.

Different MVC Services Methods Available in ASP.NET Core:

Let us understand the differences between AddController, AddMvc,


AddControllersWithViews, and AddRazorPages in ASP.NET Core
Application. Understanding the differences between AddController, AddMvc,
AddControllersWithViews, and AddRazorPages can help you choose the right
approach for your needs.

Go to the definition of the AddMvc() Extension Method. You will see that along
with the AddMvc() method, AddController(), AddControllersWithViews(),
and AddRazorPages() methods are also available, as shown in the below image.
All these methods are implemented as an extension method on

16
the IServiceCollection interface. And further, each method has two overloaded
versions available. One overloaded version does not take any parameter, while
the other overloaded version takes the Options object as the parameter using
which you can customize the service.

Let us discuss each of these methods and the features they provide in detail. For
a better understanding, please have a look at the following image.

Features of All the Above Methods:

Controller: Support for the Controller is available for all the Methods. So, you can
use any of the four methods if you need only a controller. Controllers are
responsible for controlling the flow of the application execution. When you make a
request to an MVC or Web API application, the controller action method will
handle the request and return the response.

Model Binding: The Model Binding feature is available for all four methods.
Model binding maps the incoming HTTP Request data (Route Data, Query String
Data, Request Body Data, Posted form Data, etc.) to the controller action method
parameters. The model binder is a middleman that maps the incoming HTTP
request data with the Controller action method parameter.

API Explorer: Except for the AddRazorPages method, all other methods support
the API Explorer feature. API Explorer contains functionality for exposing metadata
about your applications. We can use it to provide details such as a list of
controllers and actions, their URLs, allowed HTTP methods, parameters, response
types, etc.

Authorization: Authorization is available for all four methods. Authorization is


used to provide security features. Authorization is a process used to determine
whether the user has access to a particular resource. In ASP.NET Core MVC and
Web API Applications, we can use Authorize Attribute to implement Authorization.

CORS: Again, except for the AddRazorPages method, all other methods support
CORS. CORS stands for Cross-Origin Resource Sharing. CORS is a feature that

17
allows CROS domain calls. That means they can access your method from other
domains using jQuery AJAX. In simple words, we can say that it is a mechanism to
bypass the Same-Origin Policy of a Web browser.

Validation: All four methods support the validation feature used to validate the
HTTP Request Data. We can implement validation using DataAnnotations
attributes and Fluent API. DataAnnotations includes built-in validation attributes
for different validation rules, which can be applied to the properties of the model
class. Simultaneously, we need to use Fluent AP for condition-based validation.

Formatter Mapping: Except for the AddRazorPages method, all other methods
support the Formatter Mapping feature. This feature formats the output of your
action method, such as JSON or XML.

Antiforgery: This feature is unavailable in the AddControllers method and is


available for the other three methods. To prevent CSRF (Cross-Site Request
Forgery) attacks, ASP.NET Core MVC uses anti-forgery tokens, also called request
verification tokens.

TempData: This feature is unavailable in the AddControllers method but


available for the other three methods. TempData in ASP.NET Core MVC can store
temporary data that can be used in subsequent requests.

Views: This feature is not available in the AddControllers method but is available
for the other three methods. A view is a user interface that displays data from the
model to the user, enabling the user to modify the data.

Pages: The Pages are available only with AddMVC and AddRazorPages methods.
Razor Pages are designed for page-focused scenarios; each page can handle its
own model and actions.

Tag Helpers: Tag Helpers are not available in the AddControllers method and are
available for the other three methods. Tag Helper is a new feature in ASP.NET
Core MVC that enables the server-side code to create and render HTML elements.

Memory Cache: The Memory Cache feature is not available in the AddControllers
method but is available with the other three methods. It caches data within the
web server’s memory where your application is running. This in-memory cache
can significantly improve your application’s performance and scalability by
temporarily storing frequently accessed data, such as data from a database or
web service.

Which Method to Use in Our Application?

This depends on which type of application you want to create.

1. If you want to create a Web API Application, i.e., Restful Services, without
views, you must use the AddControllers() extension method.
2. If you want to work with the Razor Pages Application, you need to use
the AddRazorPages() extension method in your Main method of the
Program class.
3. If you want to develop a Web Application using the Model View Controller
Design Pattern, you need to use
the AddControllersWithViews() extension method. Further, if you want

18
Razor Pages features in your MVC application, you must use
the AddMVC method.
Note: The AddMvc method has all the features. You can use this AddMVC method
with any application (Web API, MVC, and Razor Pages). Adding the AddMvc()
method will add extra features even though they are not required for your
application, which might impact the performance of your application. So,
depending on the requirement, you must choose the appropriate method.

19

You might also like