CoreMVC1
CoreMVC1
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.
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.
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.
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
2
public string? Name { get; set; }
StudentBusinessLayer.cs
namespace ASPNETCoreMVCApplication.Models
StudentID = StudentID,
Name = "James",
Gender = "Male",
3
Branch = "CSE",
Section = "A2",
};
return 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.
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>@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>
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
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.
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.
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:
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:
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.
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.
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.
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.
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.
13
It should be placed before middleware, which depends on route matching,
such as MapDefaultControllerRoute.
Syntax: app.UseRouting();
MapDefaultControllerRoute Middleware in ASP.NET Core:
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.
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.
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.
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.
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.
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.
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