0% found this document useful (0 votes)
3 views148 pages

Unit-3 Net Core Framework

The document outlines the structure and functionality of Views in ASP.NET Core MVC, detailing types such as Razor Views, Partial Views, and Layout Views, along with their storage locations and creation methods. It explains the View Discovery process and the use of the View() method for returning views from controller actions. Additionally, it introduces Dependency Injection in ASP.NET Core, emphasizing its importance for managing object dependencies and achieving loose coupling in software development.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views148 pages

Unit-3 Net Core Framework

The document outlines the structure and functionality of Views in ASP.NET Core MVC, detailing types such as Razor Views, Partial Views, and Layout Views, along with their storage locations and creation methods. It explains the View Discovery process and the use of the View() method for returning views from controller actions. Additionally, it introduces Dependency Injection in ASP.NET Core, emphasizing its importance for managing object dependencies and achieving loose coupling in software development.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 148

CVM UNIVERSITY

INSTITUTE OF SCIENCE & TECHNOLOGY FOR ADVANCED STUDIES & RESEARCH


(ISTAR)
M.Sc. (Information Technology)
Semester – II

Paper Code: 101410212


Paper Title: .NET CORE FRAMEWORK

Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR

Unit 3: Views & Helpers: Introducing Razor View; Advantages of Razor


View; Razor Syntax; Types of Views; Partial Views; Layout Pages; Special
Views; View Categorization based on Model ; Html Helpers; Built-In Html
Helpers; URL helpers; Tag Helpers; Custom Tag Helpers

ASP.NET Core MVC – Views


ASP.NET Core MVC – HTML Helpers
ASP.NET Core MVC – Tag Helpers
Views in ASP.NET Core MVC
1. What are Views in ASP.NET Core MVC Application?
2. Where are View Files Stored in ASP.NET Core MVC Application?
3. How to create View in ASP.NET Core?
4. How do we return views from action methods?
5. What is the difference between View() and View(object model) Extension
Methods?
6. How do you specify the Absolute view file path?
7. How Does the Controller Action Method Identify the View in ASP.NET Core
MVC?

What is a View in ASP.NET Core MVC Application?


In Model-View-Controller (MVC) Design Pattern, the View is the component
that contains logic to represent the model data (the model data provided to
it by a controller) as a user interface with which the end-user can interact.
That means View is used to render the user interface. Views are the
components in ASP.NET Core MVC that handle the application’s
presentation logic. They are responsible for rendering HTML markup sent
to the client’s browser, typically written using the Razor syntax.
A view in ASP.NET Core MVC Application is a file with “.cshtml” (for C#
language) extension. The meaning of cshtml = CS (C Sharp) + HTML. The
View combines programming language (C#) and HTML (Hypertext Mark-
up Language). The Views in the ASP.NET Core MVC Application are
generally returned to the client from the Controller Action Method.

Types of Views in ASP.NET Core MVC:


In ASP.NET Core MVC, there are four Types of Views. They are as follows:
 Razor Views: These are the most common views in ASP.NET Core
MVC. They use the Razor syntax (.cshtml files), which is a
combination of HTML and C#.
 Partial Views: These are reusable view components that can be
embedded within other views. They are useful for rendering common
elements like headers, footers, or navigation menus.
 View Components: These are similar to partial views but more
powerful. They can encapsulate both the view and the logic needed to
generate it.
 Layout Views: These provide a consistent look and feel across
multiple views in your application. They define a common template
for your pages, including headers, footers, and navigation bars. They
define a common structure (like master pages in ASP.NET Web
Forms).
Where are Views Placed in ASP.NET Core MVC Application?
By default, Views are available inside the Views folder, created in the
project root directory. Usually, views are grouped into folder names with
the controller names. Each controller will have its own folder in which the
controller-specific view files will be stored. The controller-specific folders
will be created only within the Views folder.

Let’s say we have an ASP.NET Core MVC application with two controllers,
i.e., HomeController and StudentController. The HomeController is created
with the following three action methods.
1. AboutUs()
2. ContactUs()
3. Index()

On the other hand, StudentController is created with the following four


action methods.
1. Index()
2. Details()
3. Edit()
4. Delete()
Then, the following is the folder and file structure of the Views.

As you can see in the above image, a separate folder is created for each
controller within the Views Folder.

The Home folder represents the HomeController, and the Student folder
represents the Student Controller.
 The Home folder contains the views for the Index, AboutUs, and
ContactUs webpages. Whenever a user requests one of these web
pages, the Home Controller action method determines which of the
above three views to use to build the webpage and return it to the
user.
 Similarly, the Student folder contains the Index, Details, Edit, and
Delete web page views. So, whenever a user requests any of these
web pages, the Student Controller action method determines which
of the above views to use to build the webpage and return to the user.

Note: Besides action-specific views, we have also provided partial views,


layouts, and view components. We will discuss each of these in our
upcoming articles.

Example to Understand Views in ASP.NET Core MVC Application:


Adding Home Controller
We have already created a Controller called Student Controller in the
Controllers folder. Let us add a new Controller
named HomeController within the Controllers folder. At this time, your
project folder structure should look like the one below.

Open HomeController and then copy and paste the following code into it.

As you can see in the above HomeController class, we have only one action
method, Index. The return type of the Index() action method is ViewResult,
which means it will return a view. To return a view, we use
the View() extension method, which belongs to the Controller Base Class.

Note: Views are typically returned from the Action method as


a ViewResult, which is a type of ActionResult. Your action method can
create and return a ViewResult directly, but that isn’t commonly done.
Since most ASP.NET Core MVC Controllers are inherited from the
Controller base class, we can use the View helper method to return the
ViewResult.

Now run the application and navigate to the “/Home/Index” URL or the
default URL, and you will see the following error.
Why Did We Get the Above Invalid Operation Exception?
Let us understand why we got the above exception. As we return a view
from the Index action method of Home Controller, by default, the ASP.NET
Core MVC Framework will look for a file with the name Index.cshtml in the
following three locations.
1. First, it will look for the “Index.cshtml” file within the
“/Views/Home” folder, as the action method belongs to the Home
Controller.
2. Then it will look for the “Index.cshtml” file in the “/Views/Shared/”
folder.
3. Then it will look for the “Index.cshtml” file in the “/Pages/Shared/”
folder.

If the requested “.cshtml” file is found in any of the above folders, the View
generates the HTML and sends it back to the client who initially made the
request. On the other hand, if the requested file is not found in any of the
above locations, we will get the above error.

Creating Index View


As we already discussed, views will be created in a special folder
called Views. So, let us first add a folder to the project root level with the
name Views. To do so, right-click on the Project and select Add => New
Folder from the context menu. This will add a new folder, which we will
then rename Views.

As we already discussed, the Action Views will be created inside the folder
whose name is the same as the Controller’s name. We want to create a view
for the Index action method of the Home Controller. So, let us first add
the Home folder inside the View folder. To do so, right-click on
the Views folder and then select the Add => New Folder option to add a
new folder. Then, rename the folder Home.

Once you have created the Home folder, then we need to create a view
within this Home folder. In ASP.NET Core MVC, we can add views in many
different ways, and we will discuss them one by one.
So, right-click on the Home folder and then select the Add => View option,
which will open the Add View window, as shown in the image below. You
need to select the Razor View and click the Add button, as shown in the
image below.
Once you click the Add button, it will open the Add Razor View window.
Here, you need to give the View name as Index, select the Empty (without
model) template, uncheck the creation of a partial view, use a layout page
checkbox, and then click on the Add button as shown below.

Once you click the Add button, the Index.cshtml view should be created
within the Home folder, as shown in the image below.
Now open Index.cshtml file and then copy and paste the following code
into it.

With the above changes in place, run the application, and you should get
the expected output, as shown in the image below.

What is View Discovery in ASP.NET Core MVC?


View Discovery in ASP.NET Core MVC is the process by which the
framework determines which view file to use when rendering a response
to an HTTP request. This involves locating the appropriate view file based
on the action method and controller that handles the request.

Understanding View() Method in ASP.NET Core MVC Application:


If you go to the definition of the Controller base class, you will find four
overload versions of the View() method available, as shown in the image
below.

Let us understand the use and significance of each of the above-overloaded


versions of the View Extension method.
View() vs View(object model) Extension Methods:
If you use the View() or View(object model) extension method to return a
view, it will look for the view file with the same name as the action method
name. If you want to pass model data, you need to use the overloaded
version of the View method, which takes the object model as an input
parameter; otherwise, you can use the View() extension method, which
does not take any parameter.

For example, in the code below, we are using the View() extension method,
which does not take any parameter to return a view from the Index action
method of the Home Controller. So, by default, the ASP.NET Core MVC
framework will look for a view with the name Index.cshtml within the
“Views/Home” folder.

View(string viewName) vs View(string viewName, object model)


Extension Methods:
If you want to return a view from an action method whose name is
different than the action method name, then you need to use either
View(string viewName) or View(string viewName, object model) Methods.
If you want to pass model data to the view, you need to use the View(string
viewName, object model) method; otherwise, you can use the View(string
viewName) method, which takes the view name as a parameter.

To understand this concept, let’s create a view with the


name Test.cshtml within the Home folder. Please follow the same steps
we follow to create the index.cshtml view. Once you created the Test.cshtml
view, then open the Test.cshtml file and copy-paste the below code in it.
Now, modify the Index action method of the HomeController class as
shown below to use the View extension method, which takes the view
name as a parameter.

Run the application and navigate to the “/Home/Index” URL. As shown in


the image below, the response comes from the test view.
How do you specify the Absolute View File Path?
Let us modify the Index action method of the Home controller, as shown
below, to specify the Absolute path of the view file. So here, the ASP.NET
Core MVC framework will look for a view file with the name
“Test.cshtml” within the “Views/Home” folder.

Note: When using the absolute path, the .cshtml extension is mandatory.
When using an absolute path to reach the project’s root directory, you can
use / or ~/. You can also use any of the following, which will do the same
thing.

Absolute Path vs Relative Path in ASP.NET Core While Specifying the


View Name
In ASP.NET Core, when specifying the view name in a controller, you can
use either an absolute or relative path. Understanding the difference
between these two types of paths and when to use each is important for
efficient and error-free coding.
Absolute Path:
 An absolute path is a complete path from the application’s root to the
view file. It usually starts with a forward slash (/) or a tilde and
forward slash (~/), which represents the web application’s root.
 Example: return View(“~/Views/Home/Index.cshtml”);
Relative Path
 A relative path is relative to the location of the calling controller. In
ASP.NET Core, the default convention is to look for views in a folder
that matches the controller name within the Views folder.
 Example: If you have a HomeController, calling return
View(“Index”) will, by default, look for the view
in Views/Home/Index.cshtml.
When to Use:
 Use relative paths when the views are located in the conventional
locations (e.g., Views/[ControllerName]/[ViewName].cshtml).
 Use absolute paths when referencing a view outside the conventional
locations or to ensure the path remains valid regardless of controller
location.
Another way of Creating Views:
Let us add a new action to the HomeController with the name About. So,
please modify the HomeController as shown below.

Now, right-click anywhere within the About action method and click on the
Add View from the context menu, as shown in the image below.

Once you click on the Add View, it will open the Add New Scaffolded Item
window, as shown below. In this window, you need to select the Razor
View and click the Add button, as shown in the image below.
Once you click on the Add button, the Add Razor View window will open.
By default, the View will be named About (action method name). Finally,
click the Add button, as shown in the image below.

Once you click the Add button, it will add the About.cshtml file within the
View/Home folder, as shown in the below image.

ASP.NET Core Dependency Injection

1. Understanding the Need for ASP.NET Core Dependency Injection


2. What is the Dependency Injection Design Pattern?
3. How do you Register a Service with ASP.NET Core Dependency
Injection Container?
4. What are the different Methods ASP.NET Core Provides to
Register a Service?
5. Understanding the Singleton, Scoped, and Transient Methods
6. What are the Advantages of using Dependency Injection?

Understanding the Need for ASP.NET Core Dependency Injection


ASP.NET Core Dependency Injection (DI) is a powerful feature that helps
manage object dependencies within our application. DI is a design pattern
used to achieve loose coupling in software development. Instead of creating
dependencies (objects or services) directly within a class, dependencies are
injected into the class from outside, typically through constructor
parameters.

Let us understand the need for Dependency Injection Design Patterns in


ASP.NET Core Applications with an example. First, create a new ASP.NET
Core Application named FirstCoreMVCWebApplication with an Empty
Project Template. Once you create the ASP.NET Core Empty Project, let us
add our models. To do so, first, create a folder with the name Models.
Within the Models folder, let us add a class file with the
name Student.cs, and this Student class will be our model for this
application. Then open the Student.cs class file and copy and paste the
following code into it.

Creating Service Interface:


Next, create an interface named IStudentRepository.cs within the Models
folder. This interface will declare the methods or operations we can
perform on the student data. So, open IStudentRepository.cs and copy
and paste the following code. Here, you can see we have created the
interface with two methods.
Creating Service Implementation:
Next, create a class file named StudentRepository.cs within the
same Models folder. Then open the StudentRepository.cs class file and
copy-paste the following code. This class implements
the IStudentRepository interface by implementing the two methods
declared in the IStudentRepository interface. Here, we have hard-coded the
student data, but you will get the student data from a database in real-time
applications.

Program.cs:
In the Program class, we need to do two things. First, we need to configure
the required MVC service to the IoC Container, and then we need to add the
MVC Middleware to the request processing pipeline. So, modify the
Program class as shown below.
Without Dependency Injection:
Create a folder named Controllers in your project. Then, add a class file
named HomeController.cs within the Controllers folder and copy-paste
the following code. Here, you can see that within the Index and
GetStudentDetails action methods, we are creating an instance of the
StudentRepository class and calling the respective methods.

With the above changes in place, now run the application and check the
above two methods. it should work as expected, as shown in the image
below.
Let’s first understand the problem in the above implementation. Then, we
will discuss how to overcome it by using the Dependency Injection Design
Pattern in the ASP.NET Core application.

What is the Problem with the above implementation?


As you can see in the above HomeController class, it depends on an
instance of the StudentRepository class to get student data. Here, within
the HomeController class, we create an instance of
the StudentRepository class and invoke
the GetStudentById() and GetAllStudent methods. This is tight coupling
because the HomeController class is now tightly coupled with the
StudentRepository concrete class.

Tomorrow, if the implementation class of the IStudentRepository is


changed from StudentRepository to TestStudentRepository, then we
also need to make the changes to the code in the HomeController class, as
they are both tightly coupled. We can overcome this problem by
implementing the Dependency Injection Design Pattern.

What is the Dependency Injection (DI) Design Pattern?


Dependency Injection is the process of injecting the dependency object into
a class that depends on it. It is the most commonly used design pattern
nowadays to remove the dependencies between objects, allowing us to
develop loosely coupled software components. Let us discuss the step-by-
step procedure for implementing dependency injection in the ASP.NET
Core MVC application.
The ASP.NET Core Framework is designed from scratch to provide built-in
support for dependency injection design patterns. It injects dependency
objects into a class through a constructor or method using the built-in IoC
(Inversion of Control) container. The built-in IoC (Inversion of Control)
container is represented by IServiceProvider implementation, which
supports default constructor injection. The types (i.e., classes) managed by
built-in IoC containers are called services.

Types of Services in ASP.NET Core:


There are two types of services in ASP.NET Core. They are as follows:
1. Framework Services: Services that are a part of the ASP.NET Core
Framework, such as IApplicationBuilder, IHostingEnvironment,
ILoggerFactory, etc.
2. Application Services: The services (custom types or classes) you
create as a programmer for your application.

To let the IoC container automatically inject our application services, we


must first register them with the IoC container.

How do you Register a Service with ASP.NET Core Dependency


Injection Container?
We need to register a service with the ASP.NET Core Dependency Injection
Container within the Main method of the Program class. Before we discuss
how to Register a service with the Dependency Injection Container, it is
important to understand the service’s lifetime. Setting the lifetime of the
dependency object determines how many times it needs to be created.
What are the Different Methods ASP.NET Core Provides to Register a
Service with the Dependency Injection Container?
ASP.NET Core provides 3 methods for registering a service with the
ASP.NET Core Dependency Injection container. The method we use to
register a service will determine its lifetime.

Singleton:
Services registered as Singleton are instantiated once per application and
shared throughout its lifetime. It is Ideal for configuration services, logging,
or other services where a single instance is sufficient and expensive to
create. All requests for the service within the application receive the same
instance. The container ensures thread safety when accessing the singleton
instance. Exists for the entire duration of the application. This can be
achieved by adding the service as a singleton through the AddSingleton
method of the IServiceCollection.

Transient:
Services registered as Transient are created each time they are requested.
This method is suitable for lightweight, stateless services with short-lived
and transient behavior. A new instance is created every time the service is
requested, and instances are not shared among different consumers. This
can be achieved by adding the service through the AddTransient method of
the IServiceCollection.

Scoped:
Services registered as Scoped are created once per request (in a web
application, this typically means per HTTP request). It is used for services
that should be reused within a single request, maintaining state across
different components of the request, but should not be shared across
different requests. Instances are disposed of at the end of the request.
Common examples include data access operations within a single
transaction. This can be achieved by adding the service through the
AddScoped method of the IServiceCollection.
Registering the StudentRepository with ASP.NET Core Dependency
Injection
We need to register the service to the built-in dependency injection
container with the program class. The following code shows how to
register a service with different lifetimes:

What is the ServiceDescriptor Class in .NET Core?


The ServiceDescriptor Class is part of the Dependency Injection (DI)
framework provided by Microsoft in the ASP.NET Core framework. It
describes how a service (an interface or a concrete type) should be
registered with the DI container. It encapsulates information about the
service’s type, implementation, and lifetime (singleton, transient, scoped).
Essentially, it defines the configuration that the DI container uses to resolve
dependencies.

Extension Methods for Registration


ASP.NET Core framework includes extension methods for each type of
lifetime: AddSingleton(), AddTransient(), and AddScoped() methods for
singleton, transient, and scoped lifetime, respectively. The following
example shows how to register types (services) using extension methods.
Let us use the service’s Singleton Instance in this example. Modify the Main
method of the Program class as shown below. Which approach do you want
to use to register the service? It is your preference.

Constructor Injection in ASP.NET Core MVC Application


Once we register the service, the IoC container automatically performs
constructor injection if a service type is included as a parameter in a
constructor.
Let us modify the HomeController, as shown below, to use Constructor
Dependency Injection in the ASP.NET Core MVC Application.

Code Explanation:
In the above example, the IoC container will automatically inject an
instance of the StudentRepository into the constructor of HomeController.
We don’t need to do anything else. The IoC container will create and
dispose of an instance of the IStudentRepository based on the registered
lifetime. Injecting the dependency object through a constructor is called a
constructor dependency injection.

We created the _ repository variable as read-only, ensuring that once we


inject the dependency object, that value can never be changed. At this point,
run the application, and you should get the output as expected, as shown in
the below image.
Action Method Injection in ASP.NET Core Application
Sometimes, we only need a dependency object in a single action method. In
that case, we need to use the [FromServices] attribute. For a better
understanding, please modify the HomeController class as follows. We are
using the [FromServices] attribute within the Index action method. So, at
runtime, the IoC Container will inject the dependency object into the
IStudentRepository repository reference variable. Injecting the dependency
object through a method is called method dependency injection.

Run the application, and you will get the expected output, as shown below.
What is the FromServices in ASP.NET Core Dependency Injection?
The [FromServices] attribute in ASP.NET Core explicitly indicates that a
parameter of an action method should be resolved from the Dependency
Injection (DI) container. This attribute is useful when we need to inject
services directly into action methods instead of through the constructor.
When you decorate a parameter in an action method with the
[FromServices] attribute, ASP.NET Core’s dependency injection system will
resolve and inject the specified service directly into the action method.

Property Dependency Injection in ASP.NET Core


The Built-in IoC container does not support property injection. You will
have to use a third-party IoC container.

Get Services Manually in ASP.NET Core


We can also manually access the services configured with built-in IoC
containers using the RequestServices property of HttpContext. The
GetService method in ASP.NET Core Dependency Injection (DI) is used to
retrieve a service from the DI container. It is provided by the
IServiceProvider interface and allows for dynamic service resolution at
runtime. So, modify the HomeController class as shown below to access the
dependent service manually.
With the above changes in place, run the application, and you should get
the output as expected as in the previous examples. It is recommended to
use constructor injection instead of getting it using RequestServices.
What are the Advantages of using ASP.NET Core Dependency Injection?

The ASP.NET Core Dependency Injection allows us to develop loosely


coupled software components. Here are some of the advantages of using
dependency injection in ASP.NET Core:
1. Loose Coupling: Using dependency injection, we can separate our
classes from their dependencies, resulting in simpler code to
maintain and test.
2. Testability: By using dependency injection, we can increase the
testability of our code by easily replacing dependencies with mock
objects during unit testing.
3. Extensibility: Using Dependency injection enhances the extensibility
of our code by offering the flexibility to switch out dependencies
conveniently.
4. Reusability: Using dependency injection makes our code more
reusable since we can conveniently share dependencies among
various classes.
Layout View in ASP.NET Core MVC
1. What is Layout View in ASP.NET Core MVC?
2. Why Do We Need Layout View in ASP.NET Core MVC?
3. How Do We Create a Layout View in ASP.NET Core MVC?
4. Understanding the _Layout.cshtml file.
5. How to Use Layout View in ASP.NET Core MVC Application?

What is Layout View in ASP.NET Core MVC?


In ASP.NET Core MVC, the Layout View is a shared template or master page
that can be used across different views within your application to maintain
consistent looks and feels. It is useful for defining elements that are
common across multiple pages, such as headers, footers, navigation bars,
and sidebars. This helps maintain a consistent look and feel across your
web application and also minimizes code duplication.

Rendering is the process of displaying content on a webpage by combining


data and templates. When you visit a website, your browser “renders” the
page, meaning it fetches data and transforms it into a visible format. From a
web developer’s perspective, rendering refers to how content is generated
and delivered to users.

So, a Layout View in ASP.NET Core MVC contains HTML markup and Razor
code that will be rendered in other views that use this layout. For example,
you can define a layout with a common header, footer, and navigation
menu and then specify this layout in your individual views. The Layout
Views include the following sections:

 @RenderBody(): This is a placeholder where the content of the


views that use this layout will be rendered.

 @RenderSection(“SectionName”, required: false): This method is


used to render optional sections that views might provide. If required
is set to true, the section must be defined in the views.

Why Do We Need Layout View in ASP.NET Core MVC?


The layouts in ASP.NET Core MVC Applications help us maintain a
consistent look across all the pages of our application. Nowadays, most web
applications have a common layout that provides a consistent user
experience when the user navigates from one page to another. The layout
typically includes common user interface elements such as:
1. Website Header
2. Website Footer
3. Navigation Menus
4. Main Content Area
Please look at the following diagram, which shows the above-mentioned
four areas on a website.

If you don’t have a layout view for your website, then you need to repeat
the required HTML for the above-mentioned sections in each and every
view of your application. This violates the DRY (Don’t Repeat
Yourself) principle as we are repeating the same code in multiple views.
As a result, it isn’t easy to maintain the application code. For example,
suppose we have to remove or add a menu item from the list of navigation
menus or even if we want to change the header or footer of our website. In
that case, we need to do this in every view, which is tedious, time-
consuming, and error-prone.

Instead of putting all the sections (i.e., the HTML) in every view page, it is
always better and advisable to put them in a layout view and then inherit
that layout view in every view where we want that look and feel. With the
help of layout views, it is now easier to maintain our application’s
consistent look and feel. This is because if we need to make any changes,
we need to do it only in one place, i.e., in the layout view, and the changes
will be reflected immediately across all the views inherited from the layout
view.
How Do We Create a Layout View in ASP.NET Core MVC Application?
First, create a new ASP.NET Core Application
named FirstCoreMVCApplication using the Model-View-Controller
Template. Next, follow the steps below to create a layout view in ASP.NET
Core MVC.
1. The layout view is usually placed in the Views/Shared folder and
named _Layout.cshtml by convention. Right-click on the “Views”
folder and then add a new folder named “Shared” if not already
added. If you are creating the ASP.NET Core Web Application using
Model-View-Controller, the Shared folder will be there with
the _Layout.cshtml file by default.
2. Next, Right-click on the “Shared” folder and select the “Add” – “New
Item” option from the context menu. This will open the Add New
Item window.
3. From the “Add New Item” window, search for Layout and then
select “Razor Layout“, give your layout view a meaningful name
(_Layout.cshtml), and finally, click on the “Add” button, as shown
below. This should add the _Layout.cshtml file to the Shared folder.
So, once you add the _Layout.cshtml file, your Views folder should look as
shown below.

Understanding the _Layout.cshtml file:


Let us first modify the _Layout.cshtml file as follows.

The above layout file contains the standard HTML, head, title, and body
elements. Since these elements are present in the layout file, we don’t have
to repeat them in every view of our application that uses this layout.
The View or Page-Specific title is retrieved by using
the @ViewBag.Title expression. For example, when the “index.cshtml”
view is rendered using this layout view, then the index.cshtml view will
set the ViewBag.Title property. This is then retrieved by the Layout view
using the expression @ViewBag.Title and set as the value for the <title>
tag.

The @RenderBody() method specifies the location where the View or


Page-Specific content will be injected. For example, if the “index.cshtml”
view is rendered using this layout view, then the index.cshtml view
content will be injected at the @RenderBody() location.
Structure of Layout View in ASP.NET Core MVC:

Now, let us modify the _Layout.cshtml page again, as shown below, to


include the header, footer, left navigation menus, and main content area
section.
Modifying the Home Controller:
The Home Controller class is created by default. Please modify it as shown
below. We have created the Home Controller class with two action
methods: Index and Details. Both action methods return a view.

How to Use Layout View in ASP.NET Core MVC Application?


Now, we will create the Index and Details views using the Layout view. We
need to set the Layout property to render a view using the layout view
(_Layout.cshtml).

Index.cshtml:
Please modify the Index.cshtml view as shown below to use the layout
view. Here, we are setting the Page Title using the ViewBag.Title property,
i.e., ViewBag.Title = “Home Page”; and we are also setting the Layout for
our view as Layout = “~/Views/Shared/_Layout.cshtml”;

Details.cshtml:
Please create the Details.cshtml view within the Views/Home folder and
then copy and paste the following code to use the layout view. Here, we are
setting the Page Title using the ViewBag.Title property, i.e., ViewBag.Title
= “Details Page”; and we are also setting the Layout for our view
as Layout = “~/Views/Shared/_Layout.cshtml”;
Now run the application and navigate to the Home/Index URL, which
should display the page below.

Next, navigate to the Home/Details URL, which should display the page
below.

If you compare both pages, you will see that only the Page Title and Main
Content area are changed; the rest, like the Footer, Menus, and Header, will
be the same. Here, we are not repeating the HTML code in both the Index
and Details View; rather, we are using the Layout view, which contains the
common HTML Elements.

Key Points to Remember:


 Like the regular view in ASP.NET Core MVC, the layout view is also a
file with a .cshtmlextension
 If you are coming from an ASP.NET Web Forms background, you can
think of the layout view as the master page of the ASP.NET Web
Forms application. If you are coming from ASP.NET MVC Background,
it is similar to the layout view that we use in ASP.NET MVC Web
Applications.
 The layout views are not specific to any controller and will be used
across multiple views of our application. Therefore, they are usually
placed in the Shared subfolder within the Views folder.
 By default, in the ASP.NET Core MVC Application, the layout view file
is named _Layout.cshtml. But you can change the name if you wish.
 The leading underscore in the file name indicates that these files are
not intended to be served directly by the browser.
 In ASP.NET Core MVC, creating multiple layout files for a single
application is possible. For example, you may have one layout file for
admin users and another for non-admin users.
Sections in Layout View in ASP.NET Core MVC

1. What are Sections in Layout View?


2. Why Do We Need Sections in a Layout View?
3. Understanding RenderSection and RenderSectionAsync
Methods.
4. How Do We Use the RenderSection Method in ASP.NET Core
MVC?
5. How Do We Provide Section Content in a Child View?
6. Optional and Required Sections in ASP.NET Core MVC.
7. How Do We Make the Layout Section Optional in ASP.NET Core
MVC?
8. RenderSectionAsync Method Real-Time Example in ASP.NET
Core MVC.

What are Sections in Layout View?


The layout view is a shared template used to maintain a consistent look and
feel across all the views in our application. In ASP.NET Core MVC, sections
within a Layout View provide a way to inject content from a child view into
specific places in the layout. This feature is useful when we want to include
page-specific scripts, styles, or other elements in the layout without
affecting our main content area.

Sections are defined in the Layout View using


the RenderSection or RenderSectionAsync method and can be marked as
optional or required. In the child views, we need to specify the content for
these sections using the @section directive.

Why Do We Need Sections in a Layout View?


To understand the Need for Sections in a Layout View, let us first create a
custom JavaScript file. If it isn’t already there, create a folder at the root
level of the application with the name wwwroot. As we create the project
using Model-View-Controller, the wwwroot folder should be there.

In general, all the static files of our ASP.NET Core MVC Application need to
be placed within this wwwroot folder. Once you have created the
“wwwroot” folder, create a subfolder within it with the name “js” if it is not
already there, and then add a Javascript file with the
name “CustomJavascript.js” within the js folder.
To do so, right-click on the js folder and select Add => New Item from the
context menu, which will open the Add New Item window. Here, search
javascript, select Javascript File, give the file name CustomJavascript.js,
and finally click the Add button, as shown in the image below.
Once you add the CustomJavascript.js file, your wwwroot folder should
look as shown in the image below.

Situation 1:
If we have a custom Javascript file (e.g., CustomJavascript.js) and all the
views of our application require that file, we need to place that file in the
Layout View of our application. Let us add that CustomJavascript.js file
within our _Layout.cshtml file. So, modify the _Layout.cshtml file as
follows.
Note: Putting all the script files before the closing body tag is always a good
programming practice.

Situation 2:
Suppose we have a custom Javascript file (e.g., CustomJavascript.js), and we
want this file to be used in some specific views. Let’s assume we want this
file in the Index view but not in the Details view of the Home Controller. In
such scenarios, we can use the Layout Section in ASP.NET Core MVC
Applications.
To use Section in ASP.NET Core MVC Layout Views, we are provided with
the RenderSection and RenderSectionAsync methods. Let us look at the
signatures of the RenderSection and RenderSectionAsync methods, shown
below.

As you can see, two overloaded versions of the RenderSection Method


exist. The same is the case for the RenderSectionAsync method. The first
version of the RenderSection method takes a single parameter (i.e.,
name) that specifies the section’s name. The second overloaded version
takes two parameters. The first parameter (name) specifies the section’s
name, while the second parameter (required) specifies whether the
section is required or optional.

 name: The name of the section.


 required: A boolean value indicating whether the section is
mandatory. If set to true, an exception is thrown if the section is not
defined on the content page. If set to false, the layout will render
without the section if it’s not present on the content page.

Note: The first overloaded version takes only the name parameter; in that
case, by default, it sets the required parameter value to true. So, if you use
the first overloaded version, then it will be a required section.

Differences Between RenderSection and RenderSectionAsync:


In ASP.NET Core MVC, both RenderSection and RenderSectionAsync
methods are used to include sections of content in a layout view. However,
there are some differences between them related to how they handle
asynchronous operations. RenderSection is a synchronous method.
RenderSectionAsync is an asynchronous method. RenderSectionAsync is
useful when the section’s content involves asynchronous operations, such
as fetching data or performing I/O-bound tasks.

Synchronous vs. Asynchronous:


 RenderSection is synchronous and blocks the execution until the
section content is rendered.
 RenderSectionAsync is asynchronous and does not block the
execution, allowing other asynchronous operations to run
concurrently.
Use Case:
 Use RenderSection when the content for the section does not involve
any asynchronous operations.
 Use RenderSectionAsync when the section content involves
asynchronous operations, such as network calls, database queries, or
any other asynchronous tasks.

How Do We Use the RenderSection Method in ASP.NET Core MVC?


From your layout view, we need to call the RenderSection() method at the
location where we want the section content to be rendered. For example,
we want the script file to be included before the closing </body> tag. So,
here, we are calling the @RenderSection() method just before the
closing </body> tag, as shown below.
In the above code, we use the first overloaded version of the RenderSection
method, which only takes the name parameter. In this case, the second
parameter value will be true by default. That means it is a mandatory
section. Also, remember that we have provided the section name as Scripts.

How Do We Provide Section Content in a Child View?


We have created a section in our layout view. Now, let us understand how
to provide section content from the Child Views. Each view that wants to
provide section content must include a section within the view. We need to
use the @section directive to include the section and provide the content.
In our example, we want to provide the section content from the Index
view. So, modify the Index view as shown below. Here, you can see we are
using @section Scripts {<script
src=”~/js/CustomJavascript.js”></script>} as we are trying to include a
javascript file. Here, we need to provide the section name as Scripts, and
this is because, in the _Layout view, we have specified the section name
as Scripts, i.e., @RenderSection(“Scripts”)
Now run the application and navigate to the Home/Index URL, and you
will see the out as expected, as shown in the below image.

But, when you navigate the Home/Details URL, you will get the following
error page.

The reason for getting the above exception is the section is mandatory, and
we have not specified the section content in the Details view. To verify this,
go to the definition of the RenderSection(“Scripts”) method, which takes
the string file name as a parameter, and you will see the following.

As you can see, this method takes only the name parameter, and internally,
it sets the required parameter value to true, making it mandatory to
include the section in the child view. And in the Details view, we have not
included any section.

Optional and Required Sections in ASP.NET Core MVC


As mentioned, sections can be marked as required or optional in the layout:
 Required Sections: If a section is marked as required in the layout
and if the child view does not include that section, an exception will
be thrown.
 Optional Sections: If a section is marked as optional (required:
false), the layout will render without the section content if the child
view does not define it.

How Do We Make the Layout Section Optional in ASP.NET Core MVC?


We can make the layout section optional in ASP.NET Core MVC in two ways.
They are as follows:

Option 1: Use the RenderSection method, which takes two parameters.


Set the second parameter (i.e., the required) to false.
@RenderSection(“Scripts”, required: false)
So, modify the _Layout.cshtml file as shown below to make the section
optional.

With the above changes in place, run the application and navigate to both
URLs. You should get the expected output.

Option 2: Using the IsSectionDefined() method.


This method returns a value indicating whether the specified section is
defined on the child view. If the section is defined in the child view, then
the IsSectionDefined() method returns true, and in that case,
the RenderSection method loads the content from the child view. If the
method returns false, then the RenderSection method is not going to be
executed and be ignored. So, modify the _Layout.cshtml file as shown
below.

With the above changes in place, run the application and navigate to both
URLs. You should get the expected output.
ViewStart in ASP.NET Core MVC Application

1. Why Do We Need _ViewStart.cshtml File in ASP.NET Core MVC Application?


2. How to Create _ViewStart.cshtml file in ASP.NET Core MVC Application?
3. How to Set the Layout Property in ViewStart.cshtml file?
4. Understanding the Hierarchy of _ViewStart.cshtml File in ASP.NET Core
MVC.
5. How to Use a Different Layout Other the Layout Specified in the
_ViewStart.cshtml File?
6. How Do We Select a Layout Conditionally in the ViewStart file?
7. Real-time Example of ViewStart file in ASP.NET Core MVC Application.

What is _ViewStart.cshtml File in ASP.NET Core MVC Application?


In ASP.NET Core MVC, the _ViewStart.cshtml file is a special view that
allows us to set common configuration settings for views in our application.
This file is typically used to define settings that should apply to all views,
such as specifying a layout, setting view-specific data, or configuring view
behavior.

The primary purpose of _ViewStart.cshtml is to contain code that we want


to execute before rendering each view in the directory where the
_ViewStart.cshtml file exists and its subdirectories. The _ViewStart.cshtml
is executed before each view is rendered.

Why Do We Need _ViewStart.cshtml File?


The primary use of _ViewStart.cshtml is to specify a default layout for all
views, so we don’t need to set it individually in every view. For example, we
have used the Layout Property to associate a view with a layout view, as
shown below. So, basically, within the Child view, we have added the
following statement to use the layout view.
Layout = “~/Views/Shared/_Layout.cshtml”;

Suppose we have 100 views in our application, and all the views want to
use the same layout file. Then, we need to set the Layout Property,
i.e., Layout = “~/Views/Shared/_Layout.cshtml”; in all 100 views. This
violates the DRY (Don’t Repeat Yourself) Principle.

Suppose, later, you want to use a different Layout for all 100 views
tomorrow. Then, you need to update the Layout Property in each individual
view of your application. This process is tedious, time-consuming, and
error-prone because you may miss updating the Layout Property in some
views. To solve the above problems, we need to use
the _ViewStart.cshtml file.

How to Create _ViewStart.cshtml file in ASP.NET Core MVC


Application?
The _ViewStart.cshtml files are created within the Views or the Views
folder’s subfolder. To create the _ViewStart.cshtml file, right-click on the
Views folder and then select the Add – New Item option from the context
menu; this will open the New Item window.

From the New Item window, search for Razor and then select the Razor
View Start template, provide the name as _ViewStart.cshtml, and click on
the Add button as shown in the below image, which should create
the _ViewStart.cshtml file within the Views folder of your project.

If you are creating the ASP.NET Core Application using the Model-View-
Controller Project template, then by default, the _ViewStart.cshtml file is
added within the Views folder, as shown in the image below.
How to Set the Layout Property in _ViewStart.cshtml file in ASP.NET
Core MVC Application?
Once the _ViewStart.cshtml file is created, modify it as shown below to set
the Layout property. Here, you can see that we are specifying the layout
file path using the Layout property. Layout files are typically in
the Views/Shared folder and have the .cshtml file extension.

Then, we need to remove the Layout property on individual views. So,


modify the Index view of the Home Controller, i.e., the Index.cshtml View
is inside the Views=>Home Folder, as shown below.

Next, modify the Details.cshtml view of Home Controller as follows.

With the above changes in place, run the application and navigate
to Home/Index and Home/Details. It should display the output as
expected.

Understanding the Hierarchy of _ViewStart.cshtml File in ASP.NET


Core MVC:
As we already discussed, we can place the _ViewStart.cshtml file within
the Views folder as well as its subfolder. So, we need to understand the
hierarchical order of the ViewStart file.

The _ViewStart.cshtml file can be placed in the Views root directory or any
subdirectory under Views. ASP.NET Core MVC applications search for the
_ViewStart.cshtml file using a top-down approach, starting from the
specific view’s directory to the root of the Views directory.

Let us understand this with an example. First, create another layout file
named _MyLayout.cshtml within the Shared folder. To do so, right-click on
the Shared folder and then select Add => New Item from the context menu,
which will open the following Add New Item window. Here, search
for Layout and then select Razor Layout template, give the view name
as _MyLayout.cshtml, and finally click on the Add button as shown below
image, which should add _MyLayout.cshtml file within the Shared folder.

Once you create the _MyLayout.cshtml file, copy and paste the following
code.

With this Layout, we now have two layouts


(_Layout.cshtml and _MyLayout.cshtml) for our application.

Creating Another ViewStart File within the Home Folder:


Let’s add another ViewStart file within the Home Folder, which is present
within the Views folder. Once you create the _ViewStart.cshtml file,
modify it as shown below. Here, we are setting the newly
created _MyLayout.cshtml layout using the Layout property.
With the above changes in place, our application’s Views folder should look
like the image below.

As you can see in the above image, we have placed one ViewStart file
inside the Views folder and another inside the Home sub-folder. Now run
the application and navigate to the Home/Index URL, as shown in the
image below.

The above Index view of the Home Controller uses MyLayout.cshtml view,
which we specified within the _ViewStart.cshtml File, which is present
inside the Home Folder. So, here, the Layout Page, specified in the
_ViewStart.cshtml file in the Home sub-folder, overwrites the Layout Page,
which is specified in the _ViewStart.cshtml File in the Views folder.

This means all the views in the Views folder will use the layout
page specified in the _ViewStart.cshtml file in the Views folder, but the
views in the Home folder will use the layout page specified in
the _ViewStart.cshtml File in the Home folder.

How to Use a Different Layout Other the Layout Specified in the


_ViewStart.cshtml File?
To use a different layout than the one specified in
the _ViewStart.cshtml file, we need to set the layout explicitly in individual
view files. If you don’t want to use the layout file specified in the _ViewStart
file either from the Home folder or the Views folder, rather you want to use
a different layout file, then you need to use the Layout property in the
individual view to set the layout.

Let us understand this with an example. Create another Layout with the
name _NewLayout.cshtml within the Shared Folder. Once you create
the _NewLayout.cshtml file, copy and paste the following code.

I want to use the above _NewLayout.cshtml in the Details View of our


Home Controller. To do so explicitly, we need to use the Layout property
and provide the path of the _NewLayout.cshtml file. So, modify the
Details.cshtml file as follows.

Now, run the application and navigate to Home/Details. You should get
the following output, which means the Details view now uses the Layout,
which is specified in the Details view only.

Now, if you don’t want to use any layout or want to render a view without a
layout, then you need to set the Layout property to null. For example, if you
don’t want to use a Layout in Details View, you need to modify
the Details.cshtml view as follows.

Now, run the application and navigate to the Home/Details URL. You
should see the output without using any layout page.

How Do We Select a Layout Conditionally in the ViewStart file?


To conditionally select a layout in the _ViewStart.cshtml file in an ASP.NET
Core MVC application, you can use C# code to set the layout based on
certain conditions. Here is a step-by-step guide on how to do this:

 Identify the Condition: First, you need to determine the condition


for changing the layout. This could be based on the current
controller, action, user roles, or any custom logic.
 Implement the Conditional Logic: Inside the _ViewStart.cshtml file,
you can write C# code within @{ … } blocks. Using this C# code block,
you can write your conditional logic to select the layout.

When you work with a Real-Time ASP.NET Core MVC application, you may
have multiple layout views. Let’s say we have two Layouts, such
as _NonAdminLayout and _AdminLayout. If you want to select the layout
based on the user role, i.e., if the user role is Admin, then
use _AdminLayout; otherwise, use the _NonAdminLayout. Then, you need
to write the following conditional logic within the _ViewStart.cshtml file,
which will select the layout based on the logged-in user’s role.
Real-Time Example: Setting Up a Default Layout and Initializing ViewData
Let’s assume we are developing a content management system (CMS) for a
small news website. We want to ensure that all views use a consistent
layout called _Layout.cshtml. Additionally, we want to initialize some
ViewData properties that should be available across all views, such as the
title suffix and a generic message.

Create the Default Layout


First, let’s define our default layout, _Layout.cshtml, which should be
located in the Views/Shared folder. This layout includes placeholders for
the title, application name, header, and content. We already have this
layout in our application. So, please modify the _Layout.cshtml file as
follows:

Configure _ViewStart.cshtml
Now, we need to set up the _ViewStart.cshtml file to specify that
_Layout.cshtml should be the default layout for all views. We also initialize
ViewData with a default title, header, and application name that will be
consistent across the website. We have already created
the _ViewStart.cshtml file within the Views folder, so modify the file as
follows:

Note: Please remove the _ViewStart.cshtml file from the Views/Home


folder.
Create a View
Let’s create a view for a specific page, such as the homepage, which resides
under Views/Home/Index.cshtml. This view will use the layout and
ViewData, which are initialized in _ViewStart.cshtml. We already have this
view, so let us modify the Index.cshtml as follows:

Now, run the application and access the Index Page, and you should see the
following output:

How It Works
When a request is made to the Home controller’s Index action, the Razor
view engine starts processing Index.cshtml. Before rendering Index.cshtml,
it executes _ViewStart.cshtml, which sets the layout and initializes some
ViewData.

 The layout for the view is set to _Layout.cshtml.


 ViewData[“Title”] is initially set to “Welcome”, but it is overridden in
Index.cshtml to “Home”.
 ViewData[“ApplicationName”] is set to “My ASP.NET Core MVC App”;
and will also appear in the page title
 ViewData[“Header”] is set to “News Around Us” and will appear as
the header in all views unless specifically overridden.

The layout _Layout.cshtml uses the ViewData values to render the HTML
title and the header. This results in a consistent look and feel across the site
with minimal code duplication and centralized configuration for common
elements like the layout, title, and header.
ViewImports in ASP.NET Core MVC

What is _ViewImports.cshtml in ASP.NET Core MVC Application?


In ASP.NET Core MVC, the _ViewImports.cshtml file is a special view file
that provides a way to include common C# directives and namespaces used
across multiple views within an application. It helps to keep view files
cleaner and more maintainable by allowing to define common settings such
as namespaces, services, view components, and tag helpers in a single
location. These settings are then automatically applied to all Razor views in
the same directory or in any subdirectory.

Common Uses of _ViewImports.cshtml:


The following are the Common Uses of _ViewImports.cshtml file in ASP.NET
Core MVC Application.

Importing Namespaces:
We can use _ViewImports.cshtml to import namespaces that are used
across our Razor views. This can simplify our view code by allowing us to
use types from those namespaces without having to specify @using
directives in every view.
@using MyApp.Models
@using MyApp.ViewModels

Tag Helpers:
We can register tag helpers that we want to use in our Razor views. Tag
helpers enhance the HTML markup in our views with server-side
processing, eliminating the need to declare tag helpers in every view where
they are used.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View Components:
If we have custom view components that we want to use in your Razor
views, we can also include them here.
@using MyApp.ViewComponents

Injecting Services:
We can also use the @inject directive in the _ViewImports.cshtml file to set
up dependency injection for commonly used services across all Razor
views. This feature allows us to inject services directly into the view, which
can be very useful for accessing application data and functionality directly
from within your views.
@inject IHttpContextAccessor HttpContextAccessor
Note: In this article, I will show you how to use the @using directive in
the ViewImports.cshtml file. We will discuss the rest of the directives in
our upcoming articles.

Example to Understand ViewImports in ASP.NET Core MVC:


Create a class file named Student.cs within the Models folder and
then copy and paste the following code. As you can see, we have created the
Student model with five properties.

Modifying Home Controller:


Next, modify the Home Controller as shown below. As you can see, we
have created two action methods here. The Index Action Method displays
all the student data, while the Details Action Method takes the student ID as
a parameter and displays that student information.
Modifying the Index and Details view:
Index.cshtml:
Details.cshtml:

In the above Index and Details view, we are using the @model directive to
specify the model for the view. If you notice, you can see that in both views,
we have specified the fully qualified name for the model, such
as FirstCoreMVCApplication.Models.Student. Now, let us see how to
move the namespace to the ViewImports file so we can only specify the
model name.

Creating ViewImports.cshtml file in ASP.NET Core MVC Application:


In general, _ViewImports.cshtml files are created within the Views or
within the subfolder of the Views folder. To create the _ViewImports.cshtml
file, right-click on the Views folder and then select the Add – New
Item option from the context menu, which will open the “Add New Item”
window. From the New Item window, search for Razor, select the Razor
View Import, and click on the Add button as shown in the image below,
which should create the _ViewImport.cshtml within the Views folder.
Note: When creating the project using the ASP.NET Core Web Application
using the Model-View-Controller Project template, Visual Studio adds
the _ViewImports.cshtml file with the Views Folder by default. Once
the _ViewImports.cshtml file is created, copy and paste the following
code.

As we placed the above namespace in the ViewImports file, all the types
present in the above namespace are available to every view of our
application. So now we don’t need to type the Type’s fully qualified name.
So, modify the Index and Details view as shown below.

As you can see in the above image, we are removing the namespace and
only specifying the model name. Run the application, and it should work as
expected.
_ViewImports file Hierarchical Order in ASP.NET Core MVC:
Like the _ViewStart file, the _ViewImports file is hierarchical. It is also
possible to pace the _ViewImports in the subfolder of the Views folder. The
following are the places where you can place the _ViewImports file in

ASP.NET Core MVC:


 Application Level: The root level of the application is the most
general level where a _ViewImports.cshtml file can be placed.
Located in the Views folder, directives placed here are globally
available to all views throughout the application. This is the highest
level in the hierarchy.
 Controller Level: Within the Views directory, the controller-
specific _ViewImports.cshtml can be placed inside
the Views/[ControllerName] directory. This targets all views
associated with the specified controller, allowing for controller-
specific namespaces or tag helpers.
 View Level: The most specific level is directly within a specific view
file. This allows for more control over directives that apply only to a
particular view.

Please have a look at the image below to better understand. Here, we have
one ViewImports file in the Views folder and another within
the Home folder.

The settings specified in the _ViewImports file in the Home subfolder will
overwrite the settings specified in the _ViewImports file in the Views
folder.

How Does It Work?


When rendering a view, ASP.NET Core MVC
processes _ViewImports.cshtml files from the most general to the most
specific. This means that directives defined at the application level are
applied first, followed by the controller level, and finally at the view level. If
the same directive is defined at multiple levels, the most specific definition
takes precedence. This hierarchical processing ensures that common
settings can be defined globally while allowing for specific overrides where
needed.
Partial Views in ASP.NET Core MVC
What are Partial Views in ASP.NET Core MVC?
Partial Views are special views in the ASP.NET Core MVC Application that
render a portion of the view content. They are used to encapsulate and
reuse view logic and markup. They help break down large views into
smaller, more manageable pieces, promoting reusability and
maintainability by avoiding duplication of code. For example, you might
have a partial view for a login form, a navigation menu, or a product
summary that can be included in various views.

Partial Views are similar to regular views, but they do not run on their own;
they must be embedded within other views. This makes them ideal for
rendering portions of HTML that are reusable across different parts of an
application, such as headers, footers, or complex form elements. For
example, if you have a section that displays user information that is
required on multiple pages, you can create a Partial View for that section
and include it wherever needed.
Example to Understand Partial Views in ASP.NET MVC:
It is a common task in Web Applications to use the same code repeatedly to
display/render information. For example, an e-commerce web application
would probably render each product similarly on multiple web pages, like
the Product details page, cart page, and checkout page. Let’s understand
how we can implement this using Partial Views in an ASP.NET Core MVC
Application. First, let’s create a new ASP.NET Core MVC Web Application
named “PartialViewInMVC” using the Model View Controller Project
Template.

Creating Product Model:


Create a class file named Product.cs within the Models folder, then copy
and paste the following code. This simple class holds the product
information in a few properties.

The View for rendering Product Details in ASP.NET Core MVC View is like
the one below.
This is just a simple Product class for demonstration purposes. What if we
wanted to display objects with twenty or even more properties? And what
if we needed to display this information on multiple pages in our
application? Writing the same code repeatedly would be time-consuming
and error-prone, and maintenance becomes a headache. If we need to
modify anything, we need to do it in all places. This is where Partial Views
Come into the picture in the ASP.NET Core MVC Application.

Creating Product Controller:


Add a new Controller named ProductController within
the Controllers folder, and choose the “MVC Controller – Empty”
template. Once you create the ProductController, copy and paste the
following code into it. Here, you can see we have the Details action method,
which will take the Product ID as input and then return a view that will
render the Product information. Here, we are using an in-memory data
store to store all the product information. In real time, you will get this data
from a database.
Next, add the Details.cshtml view within the Views => Product folder.
Once you add the view, copy and paste the following code. The following is
a strongly typed view where the Model is a Product object. It then renders
the product details from the Model using both Razor Syntax and HTML
Markup.
Now, run the application and navigate to URL: Product/Details/1, and you
should get the following output.
When we need a section of a web page (both the Razor Syntax and HTML
Markup) on several different pages, we need to create and use them as
Partial Views in ASP.NET Core MVC Applications.

How Do We Create a Partial View in ASP.NET Core MVC Application?


Creating a partial view in an ASP.NET Core MVC application is a
straightforward process. Partial views are similar to regular views, but they
start with an underscore (_) in their file name to indicate that they are
meant to be partial. For example, _ProductDetails.cshtml. Here, the
underscore (_) prefix is a convention to denote partial views but is not
mandatory. They need to be created inside the Views/Shared directory of
our ASP.NET Core MVC project.

So, right-click on the /Views/Shared folder, then select the Add ->
View option from the context menu. It will open the following window.
Here, we need to select Razor View and click the Add button, as shown in
the image below.

Once you click on the Add button, it will open the following window: Here,
please provide the View name as _ProductDetails without .cshtml
extension, check the Create as a partial view check box, and then click on
the Add button as shown in the image below.
This will create a Partial view. Once you create
the _ProductDetails.cshtml Partial View, open the view file, and copy and
paste the following code. Here, you can see we are using Product as the
model and then displaying Product information. This is similar to our Main
views, which can have a Model, and they can have both Razor Syntax and
HTML Markup to generate dynamic views.

How to Use the Partial Views in ASP.NET Core MVC Application?


There are many methods available to render a partial view from the main
view in our ASP.NET Core MVC Application. They are as follows:

Method 1: Using Html.Partial


This is one of the simplest ways to render a partial view. It returns an
HTML-encoded string and can be included directly within a Razor view.
This method is executed synchronously. It is not recommended for use in
modern applications because it blocks the calling thread until the view is
rendered.
Syntax:

 @Html.Partial(“_PartialViewName”)
 @Html.Partial(“_PartialViewName”, model)

Arguments:
 The first argument is the name of the partial view.
 The second argument (optional) is the model passed to the partial
view.

Method 2: Using Html.RenderPartial


This method is similar to Html.Partial, but it renders the partial view
directly to the response stream. This can improve performance because it
doesn’t require converting the partial view to a string before rendering.

This method is also executed synchronously but does not return anything;
it writes output directly. This method is useful when the partial view is
large, and you want to avoid the overhead of string manipulation.

Syntax:
 @{ Html.RenderPartial(“_PartialViewName”); }
 @{ Html.RenderPartial(“_PartialViewName”, model); }

Method 3: Using Html.PartialAsync


This method is the asynchronous counterpart of Html.Partial. This method
is used to asynchronously render partial views. It is the recommended way
due to its non-blocking nature.
Syntax:
 @await Html.PartialAsync(“_PartialViewName”)
 @await Html.PartialAsync(“_PartialViewName”, model)
Method 4: Using Html.RenderPartialAsync
This method is the asynchronous counterpart of Html.RenderPartial. This
method is similar to Html.PartialAsync, but it directly writes the output to
the response stream and does not return a result that can be captured.

Syntax:

@{ await Html.RenderPartialAsync(“_PartialViewName”); }
 @{ await Html.RenderPartialAsync(“_PartialViewName”,
model); }
Method 5: Using Tag Helpers
ASP.NET Core MVC provides a Partial Tag Helper that can render partial
views. This is also executed synchronously.
Syntax: <partial name=”_MyPartialView” model=”Model.PartialData”
/>

Rendering the Partial View using the PartialAsync Helper Method

Let us render the partial view using the PartialAsync helper method. To
use this Partial HTML Helper method, we need to pass the name of the
partial view as a parameter. As our partial view, expecting the Product
model, we need to pass the Product object as the second parameter, such
as @await Html.PartialAsync(“_ProductDetails”, Model). As it is an
asynchronous method, we need to use the await keyword when calling the
method. So, modify the Details.cshtml View as follows.

Now, run your application and see that everything is working as expected.
But this time, you can re-use this partial view wherever you want, and
moreover, if you decide to change how product details should be rendered,
the only View you need to change is the _ProductDetails.cshtml Partial
View. The above @Html.PartialAsync helper method passed a Product
object to the “_ProductDetails” partial view. The partial view was
dynamically rendered.

Now, let us see how we can use the same Partial View from another View.
Let us first modify the Product Controller as follows. Here, you can see we
have added the Index action method, which is going to render all the
product details.
Next, add the Index.cshhtml view within the Views => Product folder.
Once you add the view, copy and paste the following code.
As you can see in the above code, each loop item calls the same partial view
by passing the product object, which will act as the model in the partial
view. With the above changes in place, run the application and navigate to
the Product/Index action method, and you will see the data as expected,
as shown in the image below.
Using Partial HTML Helper Method in ASP.NET Core MVC:
Now, let us use the Partial HTML Helper method to render the Partial View.
So, modify the Index.cshtml view of the Product Controller as follows. Here,
you can see, we are using the Html.Partial HTML Helper method.

With the above changes in place, run the application and access
the Product/Index URL, and you should get the output as
expected. However, Microsoft does not recommend the use
of HTML.Partial HTML helper method to render partial view. If you move
the mouse pointer over the Partial Method, you will see the following
warning. The first part of the warning message says that you may get
Application Deadlocks.
An application deadlock is a situation in computer programming where
two or more processes or threads become permanently blocked because
each process is waiting for resources or conditions that are being held by
the other processes.

The second part of the warning message says that instead of using the
Partial Method, please use the Partial Tag Helper or PartialAsync method.
We have already discussed rendering the Partial View using the
PartialAsync HTML helper method; now, let us proceed with how to use the

Partial Tag Helper.


Using Partial Tag helper to Render Partial View in ASP.NET Core MVC:
So, what is Tag Helper? We will discuss this in our upcoming article. Now,
let us use the Partial Tag helper to render the Partial View in ASP.NET Core
MVC Application.

The Partial Tag Helper renders partial views synchronously. So, modify the
Index View of the Product Controller as follows. The model attribute is
assigned a Product instance to be binding to the partial view.
With the above changes in place, run the application, and you should get
the output as expected.

Benefits of Using Partial Views in ASP.NET Core MVC


The following are some of the benefits of using Partial Views in ASP.NET
Core MVC:
 Modularity: Breaking down views into partial views makes our
application modular and easier to manage.
 DRY Principle: Partial views help adhere to the DRY (Don’t Repeat
Yourself) principle by reusing common view logic. When we have a
component (like a banner, a navigation menu, or a footer) reused
across multiple pages.
 Performance: Rendering only parts of a view can improve
performance, especially when combined with AJAX requests to load
partial content dynamically. Partial views can be returned from
controller actions for AJAX calls to update a portion of a page without
reloading the entire page.
Different Ways to Render Partial View in ASP.NET Core MVC
In the ASP.NET Core MVC Application, we can render a partial view using
the following ways:
1. Html.Partial: The Html.Partial method is used to render a partial
view synchronously. It inserts the HTML output of the partial view
directly into the parent view. You can also store the return HTML in a
variable. This method is typically used when the data needed by the
partial view is already available in the parent view. Syntax:
@Html.Partial(“_PartialViewName”, model)
2. Html.RenderPartial: Similar to Html.Partial, the Html.RenderPartial
renders a partial view synchronously. The key difference is that
RenderPartial writes the output directly to the response stream. This
method does not return an HTML string but instead sends the output
directly to the HTTP response, which can improve performance in
certain scenarios. Syntax: @{
Html.RenderPartial(“_PartialViewName”, model); }
3. Html.PartialAsync: Html.PartialAsync is the asynchronous
counterpart of Html.Partial. It is used to render a partial view
asynchronously, which can be beneficial when the partial view needs
to perform asynchronous operations, such as database calls or file
I/O operations, before rendering. Syntax: @await
Html.PartialAsync(“_PartialViewName”, model)
4. Html.RenderPartialAsync: Html.RenderPartialAsync is the
asynchronous version of Html.RenderPartial. It renders the partial
view asynchronously and writes the output directly to the response
stream. This method is useful for improving the performance of
rendering partial views that perform asynchronous
operations. Syntax: @{ await
Html.RenderPartialAsync(“_PartialViewName”, model); }
5. Partial Tag Helper: ASP.NET Core introduced Tag Helpers to render
partial views in a more HTML-like syntax. The partial Tag Helper
allows you to include a partial view within another view. Syntax:
<partial name=”_PartialViewName” model=”Model” />

Example to Understand How to Render Partial View:


We will use the same example we created in our previous article. The
following is the Product Controller class.
Next, modify the _ProductDetails.cshtml Partial View file as follows:
Render a Partial view using @Html.Partial() Method in ASP.NET Core
MVC:
The Html.Partial() method synchronously returns an IHtmlContent that
represents the HTML content generated by the specified partial view. Since
it’s synchronous, it can potentially block the thread if the operation takes a
long time.

The Html.Partial() is an HTML helper method available in


the Microsoft.AspNetCore.Mvc.Rendering namespace. Four overloaded
versions of the Partial method are available, as shown in the image below.
Parameters:
 htmlHelper: The HTML helper instance that this method extends
 partialViewName: The name of the partial view to render
 viewData: The view data dictionary for the partial view.
 model: The model for the partial view.

Returns: The partial view that is rendered as an HTML-encoded string.


To render a partial view using @Html.Partial() html helper, please modify
the Details.cshtml view of the Product controller as shown below. Here,
_ProductDetails is the name of the partial view file, and Model is the
model object.

Render a Partial view using the @Html.PartialAsync() Method in


ASP.NET Core MVC:
The Html.PartialAsync() HTML Helper Method is the async version of
Html.Partial() Method. This method asynchronously returns an
IHtmlContent that represents the HTML content generated by the specified
partial view. This method is preferred over Html.Partial when the partial
view involves I/O operations, such as database calls or file reads, as it
doesn’t block the thread while these operations are complete.
The Html.PartialAsync is also an HTML helper available
in Microsoft.AspNetCore.Mvc.Rendering namespace. There are 3
overloaded versions of this HTML.PartialAsync method, which is available
as follows.
To render a partial view using @Html.PartialAsync() html helper, please
modify the Details.cshtml file of the Product controller as shown below.
Here, _ProductDetails is the name of the partial view file, and Model is the
model object. Here, we must use the await keyword as this method works
asynchronously.

Render a Partial view using @Html.RenderPartial() Method in


ASP.NET Core MVC:
The Html.RenderPartial synchronously renders the specified partial view
to the response stream. This method does not return a value; instead, it
writes the rendered HTML directly to the response’s output stream. This
can be more efficient than HTML.Partial in terms of memory usage since it
doesn’t need to store the rendered HTML in an intermediary IHtmlContent
object before it’s written to the response.

The @Html.RenderPartial is also an HTML helper method for rendering a


partial view. It is available in the Microsoft.AspNetCore.Mvc.Rendering
namespace. There are 4 overloaded versions of the RenderPartial method
available, as shown in the image below. You can use any one of them as per
your requirements.

Parameters:
 htmlHelper: The HTML helper instance that this method extends
 partialViewName: The name of the partial view.
 viewData: The view data for the partial view.
 model: The model for the partial view.

To render a partial view using @Html.RenderPartial() HTML helper,


please modify the Details.cshtml view of the Product controller as shown
below. Here, _ProductDetails is the name of the partial view file,
and Model is the model object. This method works synchronously.

Render a Partial view using @Html.RenderPartialAsync() Method in


ASP.NET Core MVC:
The Html.RenderPartialAsync asynchronously renders the specified partial
view to the response stream. It is similar to Html.RenderPartial, but it
performs the rendering operation asynchronously, making it suitable for
I/O-bound operations within the partial view.
The Html.RenderPartialAsync() Method is the async version of
@Html.RenderPartal(), which is also used to render a partial view. It is
available in the Microsoft.AspNetCore.Mvc.Rendering namespace.
Three overloaded versions of the RenderPartialAsync method are available,
as shown in the image below.

To render a partial view using @Html.RenderPartialAsync() HTML helper,


please modify the Details.cshtml file of the Product controller as shown
below. Here, _ProductDetails is the name of the partial view file,
and Model is the model object. Here, we must use the await keyword as
this method works asynchronously.
Rending Partial View using Partial Tag Helper in ASP.NET Core MVC
The Partial Tag Helper, introduced in ASP.NET Core, is used within a view
to render a partial view. It uses a more concise syntax compared to the
Html.* methods and supports asynchronous rendering by default. The
syntax looks like <partial name=”_PartialViewName” />, making it more
readable and consistent with other tag helpers in ASP.NET Core. This
approach is often recommended for its simplicity and modern syntax.
Important features of Partial tag helper –
 Easy to use
 HTML like syntax
 The partial tag works in async mode
 Newly introduced tag helper in ASP.NET Core
To render a partial view using the partial tag helper, please modify
the Details.cshtml file of the Product controller as shown below.

Let’s discuss the details of this partial tag helper –


 Tag name: The name of the tag is partial. <partial /> is a self-closing
tag helper.
 Partial view name: We can write the name of the partial view using
the name attribute of the partial tag.
 Pass data (Model) to the partial view: We can pass the model to
the partial view using the model attribute of the partial tag.

Partial View with ViewData in ASP.NET Core MVC:


Now, let us understand how to create a partial view that will accept a
model object as well as a ViewData. So, modify
the _ProductDetails.cshtml partial view as follows. As you can see, we are
using the Product model as well as a ViewData for displaying the header.

Next, modify the Details.cshtml view of the product controller is as


follows. Here, I show how to call the partial view using ViewData with all
five approaches.
Difference Between @Html.Partial and @Html.RenderPartial in
ASP.NET Core MVC:
In ASP.NET Core MVC, both @Html.Partial and @Html.RenderPartial are
used to render a partial view within a parent view. However, they differ in
the way they render the partial view and their return types, which
influences how they are used within your Razor views. Understanding the
difference between these two can help in deciding which one to use based
on your specific needs.

@Html.Partial
 Return Type: @Html.Partial returns an IHtmlString, which means it
returns the rendered HTML content of the partial view as an HTML-
encoded string. This allows the result to be stored in a variable or
returned directly in a Razor file.
 Usage: Because it returns an IHtmlString, you can use it like this in
your Razor view: @Html.Partial(“_PartialViewName”, model). The
rendered HTML from the partial view is inserted into the parent
view’s output.
 Performance: It might be slightly slower in scenarios where direct
writing to the output stream is more efficient because it involves
creating a string of the rendered HTML before it’s written to the
output stream.
@Html.RenderPartial
 Return Type: @Html.RenderPartial writes the rendered HTML
content of the partial view directly to the Response stream. It does
not return anything (void return type); instead, it outputs the
rendered HTML directly to the page’s output.
 Usage: Since it does not return a value, you have to call it within a
code block in your Razor view like this: @{
Html.RenderPartial(“_PartialViewName”, model); }. This means the
HTML is directly streamed to the output, which can be more efficient
in terms of performance.
 Performance: Generally, @Html.RenderPartial is more efficient,
especially for larger partial views, because it avoids the overhead of
generating and then writing an IHtmlString to the output.

Note: The same differences are there between @Html.PartialAsync and


@Html.RenderPartialAsync. The only difference is that @Html.PartialAsync
and @Html.RenderPartialAsync work asynchronously, whereas
@Html.Partial and @Html.RenderPartial work synchronously.

Choosing the Right Method


 For Synchronous Operations: If the partial view rendering is CPU-
bound and expected to complete quickly, Html.Partial or
Html.RenderPartial might be suitable. However, in most cases, it’s
better to default to asynchronous methods to avoid blocking the
thread.
 For Asynchronous Operations: When the partial view involves I/O-
bound operations, prefer Html.PartialAsync,
Html.RenderPartialAsync, or the Partial Tag Helper. These methods
allow the thread to be released back to the thread pool to handle
other requests while waiting for the I/O operations to complete.
 For Cleaner Syntax and Consistency: The Partial Tag Helper is
often preferred for its cleaner syntax and consistency with other tag
helpers in ASP.NET Core, making your views more readable and
maintainable.
HTML Helpers in ASP.NET Core MVC What are HTML Helpers in
ASP.NET Core MVC?
HTML Helpers in ASP.NET Core MVC are methods used in Razor views to
generate HTML elements dynamically. They provide a way to render
standard HTML elements programmatically, which helps reduce the
amount of manual HTML code we have to write in our views. HTML
Helpers simplify the process of creating form controls such as textboxes,
dropdown lists, checkboxes, radio buttons, and other HTML elements,
especially when bound to model data. They help keep the Razor views
cleaner by encapsulating HTML markup. By using HTML Helpers,
developers can render HTML in a strongly typed, C# centric way. This
allows for better reuse and more readable code.

Why HTML Helpers in ASP.NET Core MVC?

HTML Helpers in ASP.NET Core MVC simplify the process of creating HTML
elements on a web page and binding data to them. Using HTML Helpers
reduces the chances of introducing typos or errors when manually writing
HTML code. Additionally, HTML Helpers facilitate model binding,
validation, and integration with ASP.NET Core features such as tag helpers,
form validation, and data annotations. They also promote code reusability
and maintainability, making views cleaner and easier to manage.

For example, if you want to generate a textbox with id=”firstname” and


name=”firstname,” you can type all the required HTML in a view, as shown
below.

<input type=”text” name=”firtsname” id=”firstname” />

However, in ASP.NET Core MVC, you can use the TextBox HTML helper
method to generate a text box as follows.

@Html.TextBox(“firtsname”)

Several overloaded versions of the above TextBox HTML helper method are
available, which you can use according to your requirements. For example,
you can use the following overloaded version of the TextBox helper method
to set the value and name.

@Html.TextBox(“firtsname”, “Pranaya”)
At runtime, the above TextBox HTML helper method generates the
following HTML

<input id=”firtsname” name=”firtsname” type=”text” value=”Pranaya” />

It is also possible to set the HTML attributes of a text box. If you want to do
so, you need to use the following overloaded version of the TextBox HTML
helper method.

@Html.TextBox(“firtsname”, “Pranaya”, new { style = “background-


color:Red; color:White; font-weight:bold”, title=”Please enter your first
name” })

Notice that we are passing the HTML attributes title and style to the
TextBox helper method as an anonymous type. Some HTML attributes are
reserved keywords, such as readonly, class, etc. If you want to use these
attributes within a Helper method (which is a C# method), you must prefix
them with the @ symbol, as shown in the example below.

@Html.TextBox(“firtsname”, “Pranaya”, new { @class = “redtextbox”,


@readonly=”true” })

Types of HTML Helpers in ASP.NET Core MVC

HTML Helpers can be categorized into three types:

Standard HTML Helpers:

These helpers generate basic HTML elements such as text boxes,


checkboxes, radio buttons, etc. Examples include

Html.TextBox()

Html.TextArea()

Html.DropDownList()

Strongly Typed HTML Helpers:

These helpers are associated with a specific data model and allow for
compile-time checking of model properties. They use lambda expressions
to refer to model properties directly. Examples include:

Html.TextBoxFor(model => model.PropertyName)

Html.EditorFor(model => model.PropertyName)

Html.DropDownListFor(model => model.PropertyName)


Categories of HTML Helpers Methods in ASP.NET Core MVC
Application

The HTML Helper methods in ASP.NET Core MVC can be categorized based
on the types of HTML they generate. They are as follows:

Input Control Helpers:

Generate HTML input elements such as text boxes, checkboxes, radio


buttons, etc. Examples include:

Html.TextBox()

Html.CheckBox()

Html.RadioButton()

Display Control Helpers:

Render read-only representations of model properties. Examples include:

Html.Label()

Html.DisplayFor()

Html.DisplayTextFor()

Form Helpers:

Help generate form elements and manage form submissions. Examples


include:

Html.BeginForm()

Html.EndForm()

Validation Helpers:

Display validation messages related to model validation. Examples include:

Html.ValidationMessageFor()

Html.ValidationSummary()
Link HTML Helpers:

The Link HTML Helpers generate anchor (<a>) tags that create hyperlinks
to different pages within your application. The following are the examples:

Html.ActionLink

Html.RouteLink

TextBox HTML Helper in ASP.NET Core MVC


A TextBox in web applications is a form element that allows users to input
text data. It’s a basic yet essential component in creating web forms,
enabling the collection of information from users. TextBoxes can be used
for various purposes, such as entering names, email addresses, passwords,
search queries, and other data. Here are some key points about TextBoxes
in web applications:

Single-line TextBox: The most common type of TextBox allows users to


input a single line of text. It’s used for short text inputs like names, email
addresses, or search terms.

Multiline TextBox: A multiline TextBox or textarea can be used for longer


inputs, such as comments or messages. This type of TextBox allows for the
input of text across multiple lines.

Example to Understand TextBox HTML Helper in ASP.NET Core MVC:

Let us understand how to create a text box using the TextBox Helper
method with an example. First, create a new ASP.NET Core Web
Application using the Model-View-Controller Project template named
HTML_HELPER.

Creating Employee Model:

Once you create the project, create a class file with the name Employee.cs
within the Models folder and then copy and paste the following code into it.

We will use the above Employee model with TextBox() and TextBoxFor() HTML Helper
methods.

Modifying Home Controller:

Modify the Home Controller as follows. The HomeController is created with


one action method, i.e., the Index action method.
TextBox() HTML Helper Method in ASP.NET Core MVC:

The Html.TextBox() Helper method creates an element of <input


type=”text”> with specified name, value, and HTML attributes. There are
four overloaded versions of this Html.TextBox() Helper method is available,
as shown in the image below. The following methods are loosely typed
methods.

Parameters:

htmlHelper: This is the instance of IHtmlHelper that provides access to the


TextBox method and other HTML helpers in Razor views. It is implicitly
available in Razor views (e.g., as @Html) and is used to generate HTML
elements dynamically. You do not pass this manually; it’s always available
as the helper context.

expression: In the TextBox helper method, the expression refers to the


input field’s name. This string represents the name and id attributes of the
<input> element. It tells the helper the input element’s name, which is
essential for model binding when posting data back to the controller.

value: This parameter is the initial value the input field will display when
rendered. It populates the <input> element with a value. It provides a way
to pre-fill the input field, such as when editing a form with existing data.

format: This optional parameter specifies how the value should be


formatted when rendered in the input field. It is typically used to format
dates, numbers, or other values requiring a specific display format. It
ensures that the value is displayed in a specific format (e.g., date or
currency formatting) that might differ from how it is stored in the model.
htmlAttributes: This parameter allows you to specify additional HTML
attributes for the <input> element, such as CSS classes, IDs, placeholders,
etc. It is passed as an anonymous object. It customizes the appearance and
behavior of the input field by adding attributes like class, id, maxlength, etc.

Modifying the Index View:

Please modify the Index View of the Home Controller as shown below to
use the TextBox Helper method.

Here in @Html.TextBox(“EmployeeName”, null, new { @class = “form-control”


})

EmployeeName: The name of the input element. If you are binding to a model,
this should match the property’s name in your model.

null: This is where you can specify the value of the TextBox. Passing null means,
it will be empty by default or filled with data from the model if the name
matches.

new { @class = “form-control”}: This anonymous object contains HTML


attributes for the TextBox. In this example, it sets the CSS class.

Run the application and view the page source. The textbox will be produced
using the following HTML.

<input class=”form-control” id=”EmployeeName” name=”EmployeeName”


type=”text” value=”” />

In the above example, the first parameter is EmployeeName, a property of the


Employee model that will be set as the name and id of the textbox. The second
parameter is the value that we need to display in the textbox, which is null in
the above example because the TextBox() method will automatically display
the value of the EmployeeName property of the Employee model. The third
parameter will be set as the class attribute. The HTML attributes parameter is
an object type so that it can be an anonymous object, and the attributes name
will be its properties starting with @ symbol.
You can also specify any name for the textbox. However, it will not be bound to
a model.

It will produce the following HTML

<input class=”form-control” id=”myTextBox” name=”myTextBox”


type=”text” value=”This is value” />

You can also apply the format parameter to specify how to display the data.
For example, modify the Index.cshtml view as follows. Here, we display the
date time values in yyyy-MM-dd format.

TextBoxFor() HTML Helper Method in ASP.NET Core MVC Application:

The TextBoxFor() HTML helper is a strongly typed HTML helper method in


ASP.NET Core MVC that generates a text input element for a form. This
helper method binds a model property to a text box, automatically enabling
the framework to handle data display, posting, and validation feedback for
the associated property. The TextBoxFor() HTML Helper Method has three
overloaded versions available in ASP.NET Core MVC, as shown in the image
below.

Parameters:

htmlHelper: This refers to the instance of IHtmlHelper, which is used to


call the TextBoxFor method. It is implicitly available in Razor views as
@Html. It provides access to helper methods, such as TextBoxFor, that
generate HTML based on the model’s properties and enable interaction
between the model and view.

expression: This is a lambda expression that identifies the model property


the TextBoxFor helper will bind to. It defines which model property will
generate the <input> element. The expression allows automatic data
binding between the form’s input field and the model’s property, ensuring
that data from the form is correctly bound back to the model when
submitted.

format: This optional parameter specifies the format in which the value of
the bound model property should be displayed in the input field. It is
commonly used for formatting dates, numbers, or other data types. The
format ensures that the value of the bound property is displayed in a user-
friendly or standardized way, such as formatting a date to MM/dd/yyyy or
a number to a currency format.

htmlAttributes: This parameter allows you to pass additional HTML


attributes to the generated <input> element, such as class, id, placeholder,
etc. It is passed as an anonymous object. The htmlAttributes parameter
customizes the appearance and behavior of the input field by allowing you
to set CSS classes, add a placeholder, specify the field’s maximum length,
etc.

Example to understand the TextBoxFor() HTML Helper Method:

Please modify the Index View of the Home Controller as shown below to
use the TextBoxFor Helper method. Here, we are creating
HTML_HELPER.Models.Employee model.

Here,

model => model.EmployeeName: A lambda expression that specifies the


property of the model to which this TextBox is bound.

new { @class = “form-control” }: Similar to the Html.TextBox example sets


the HTML attributes for the TextBox.

Run the application and inspect the element, and you will see that it will
produce the following HTML
<input class=”form-control” id=”EmployeeName” name=”EmployeeName”
type=”text” value=”” />
In the above example, the first parameter in TextBoxFor() HTML Helper
Method is a lambda expression that specifies the EmployeeName property
of the Model object to bind with the textbox. It generates an input-type text
element with id and name property, and the property’s value is set to
EmployeeName. The value attribute will be set to the value of the
EmployeeName property of the Model Object.

You can also apply the optional format parameter to specify how to display
the data. For example, modify the Index.cshtml view as follows. Here, we
display the date-time values in yyyy-MM-dd format.
TextArea HTML Helper in ASP.NET Core MVC

The TextArea in Web Applications refers to an element that allows users to


input multiple lines of text. It is a form control that can capture user input,
such as comments, descriptions, or any other information that requires
more than a single line of text. Unlike a single-line text input field (often
created using an <input type=”text”> tag in HTML), a TextArea provides a
larger, flexible area for text entry, making it suitable for inputs that require
more extensive content.

The TextArea element is defined in HTML using the <textarea> tag. This tag
can include attributes to control its appearance and functionality, such as
rows and cols to specify its size, placeholder for placeholder text,
maxlength to limit the number of characters a user can enter, and readonly
or disabled to control user interaction.

How Do We Create TexArea using HTML Helper in ASP.NET Core MVC


Application?

In ASP.NET Core MVC, the TextArea HTML helper is used to generate a


multiline text input element (i.e., a <textarea> tag) in Razor views. It allows
users to input multiple lines of text. This is particularly useful when dealing
with form fields that require larger amounts of text input, such as
comments or descriptions. The IHtmlHelper class provides two extension
methods to generate the textarea: They are TextArea() and TextAreaFor().

The Html.TextArea method is used when you want to specify the name of
the form field manually, while Html.TextAreaFor is used with model
properties, providing a strongly typed approach. That means the
TextArea() HTML Helper method is loosely typed, whereas the
TextAreaFor() HTML Helper method is strongly typed.

TextArea() HTML Helper Method in ASP.NET Core MVC:

The TextArea() HTML Helper method is a loosely typed helper method


because the name parameter is a string. As shown in the image below,
there are four overloaded versions available for the TextArea() HTML
Helper Method in ASP.NET Core MVC.
Parameters:

htmlHelper:

The htmlHelper property refers to the instance of the HtmlHelper class,


which provides methods for rendering HTML controls in Razor views, such
as input fields, buttons, dropdowns, etc. The htmlHelper is implicitly
available in Razor views as @Html and is used to invoke HTML helper
methods, like TextArea, to generate HTML elements.

For example: @Html.TextArea(“Description”)

Here, Html is an instance of the htmlHelper, and you are calling the
TextArea method on it to generate a <textarea> element.

expression:

In the context of the TextArea helper method, the expression refers to the
name of the form field or model property to which the generated
<textarea> will be bound. It is a string that specifies the name or the
“expression” that will map to a key in the form’s posted data.

For example: @Html.TextArea(“Description”)

Here, “Description” is the expression that specifies the name attribute of


the generated <textarea> element. It does not have to be bound to a model
but can simply represent the name used to access the value when the form
is submitted.

value:

The value parameter in the TextArea method refers to the initial content or
value to be displayed inside the <textarea> element. This could be a
predefined string or some dynamic data you want to show to the user when
the form is rendered.

For example: @Html.TextArea(“Description”, “Default text”)


Here, “Default text” is the value that will be pre-populated in the
<textarea>. When the page is rendered, this text will appear inside the
textarea box, and the user can modify it as needed.

htmlAttributes:

The htmlAttributes parameter allows you to specify additional HTML


attributes that will be applied to the generated <textarea> element. This
can include attributes like CSS classes, inline styles, placeholder, id, and
more. It is passed as an anonymous object, where each property
corresponds to an HTML attribute.

For example: @Html.TextArea(“Description”, “Default text”, new { @class =


“form-control”, @placeholder = “Enter your description here”, @id =
“descriptionTextArea” })

In this case:

@class = “form-control”: Adds a CSS class form-control to the textarea


for styling.

@placeholder = “Enter your description here”: Adds placeholder text.

@id = “descriptionTextArea”: Sets the id attribute of the textarea.

Example to Understand TextArea HTML Helper Method in ASP.NET


Core MVC

Let’s see an example of the TextArea HTML Helper Method in the ASP.NET
Core MVC Application. First, modify the Employee Model, as shown below.

Next, modify the Home Controller as shown below:


Modify the Index View:
Copy and paste the following code into the Index view

If you inspect the text area, then you will see that it will produce the
following HTML

<textarea class=”form-control” id=”Address” name=”Address”>Andheri,


Sakinaka, Mumbai, 400097, Maharashtra, India</textarea>

In the above example, the first parameter is the “Address” property of the
Employee model class, which will be set as the name and id of the textarea.
The second parameter is the value to display in the textarea, which is null
in the above example because the TextArea() method will automatically
display a value of the Address property in the textarea. The third
parameter will be set as a class attribute. The HtmlAttributes parameter is
an object type so it will be an anonymous object, and the attribute name
will be its properties starting with @ symbol.

We can also specify any name for the textarea. However, it will not be
bound to a model.
It will produce the HTML: <textarea class=”form-control”
id=”MyTextArea” name=”MyTextArea”>This is value</textarea>

If you want, then you can also specify the rows and cols size of the text area
as follows:

@Html.TextArea(“MyTextArea”, “This is value”, new { @class = “form-


control”, @rows = “4”, @cols = “20”})

In this example:

 “MyTextArea“ is the name of the text area which will be used in the
form submission.
 new { @class = “form-control”, @rows = “4”, @cols = “20” } is an
object initializer that sets HTML attributes like class, rows, and
columns for the TextArea.

Example to Understand TextAreaFor HTML Helper Method in ASP.NET


Core MVC:
The TextAreaFor helper is specifically designed to work with the model
properties efficiently. Let us see an example of the TextAreaFor HTML
Helper Method in the ASP.NET Core MVC Application. Copy and paste the
following code into the index view.

It will produce the following HTML

<textarea class=”form-control” id=”Address” name=”Address”>Andheri,


Sakinaka, Mumbai, 400097, Maharashtra, India</textarea>

In the above example, the first parameter in the TextAreaFor() method is a


lambda expression that specifies the model property to be bound with the
textarea element. In our example, we specified the Address property. So, it
generates the input type <textarea> element with id and name property set to
the property name Address. The value of the Text Area will be set to the value
of the Address property. If you want, then you can also specify the rows and
cols size of the text area as follows:
@Html.TextAreaFor(m => m.Address, new { @class = “form-control”, @rows =
“4”, @cols = “20”})

In this example:

 model => model.Address is a lambda expression indicating the model


property that the text area is bound to.
 new { @class = “form-control”, @rows = “4”, @cols = “20”} is an
anonymous object that specifies HTML attributes for the <textarea>
element. In this case, it assigns a CSS class for styling and sets the
number of rows to 5 and the number of cols to 20, determining the text
area’s height and width.

DropDownList HTML Helper in ASP.NET Core MVC


A DropDownList in a web application is a user interface control allowing users
to select a single item from a list of items presented in a dropdown menu.
When it is not activated, it shows the currently selected item. When clicked or
tapped, it displays a list of options from which the user can select one. The
DropDownList is particularly useful for fields that have a fixed set of options,
such as:

 Countries
 States or regions within a country
 Categories or types of items
 Settings options that have predefined choices

In HTML, a DropDownList can be created using the <select> element, where


each option within the dropdown is defined using an <option> tag. Here’s a
basic example:

In this example, the DropDownList allows users to select a country from


the list. When a user selects an option, the value of the <select> element
(accessible through JavaScript or on the server side after form submission)
becomes the value of the selected <option>.
How Do We Create DropDownList using HTML Helper in ASP.NET Core
MVC?

To create a DropDownList using the HTML Helper Method in the ASP.NET


Core MVC Application, we need to use the DropDownList Helper method. In
ASP.NET Core MVC, the DropDownList HTML Helper generates an <select>
element representing a dropdown list in an HTML form. We can use two
different types of DropDownList Helper methods to generate a textbox in a
Razor view. These two extension methods are DropDownList() and
DropDownListFor().

The Html.DropDownList method is used when you want to specify the


name of the form field manually, while Html.DropDownListFor is used with
model properties, providing a strongly typed approach. That means the
DropDownList() HTML Helper method is loosely typed, whereas the
DropDownList() HTML Helper method is strongly typed.

Example to Understand DropDownList HTML Helper Method in


ASP.NET Core

A Drop-down List in an ASP.NET Core MVC application is a collection of


SelectListItem objects. Depending on the business requirement, we may
either hard code the values or retrieve them from a database table. In this
article, I will discuss both approaches. First, we will discuss creating the
Drop-down List using the hard-coded values and then see how to create it
with the values from a database.

Modifying the Home Controller:

First, modify the Home Controller as follows:

Modifying the Index.cshtml View:

Modify the Index.cshtml view as follows. The following code will generate a
department dropdown list. The first item in the drop-down list will be
Select Department. Here, we have used the Selected property to true for the
IT element, so the “IT” element will be selected by default when the page
loads.

Understanding the DropDownList Help Method:

The @Html.DropDownList helper method in ASP.NET Core MVC generates


a dropdown list in an HTML form. In our example, we used the following
DropDownList Help Method.

Explanation of Parameters

Departments (name Parameter):

This is the name of the form element that will be generated. The name
attribute in HTML is used to identify form elements when submitting data.
In this case, the form will send the selected department’s value (e.g., “1” for
IT, “2” for HR, etc) as the Departments field when submitted.

new List<SelectListItem> {…} (items parameter):

This is the list of options for the dropdown. Each SelectListItem object
represents an item in the dropdown with the following properties:

 Text: The text that will be displayed to the user in the dropdown
(e.g., “IT”, “HR”, “Payroll”).
 Value: The actual value that will be submitted when the user selects
this option (e.g., “1” for IT, “2” for HR, “3” for Payroll).
 Selected: A Boolean value indicates whether this option is selected
by default. In our case, “IT” is selected by default because
Selected=true is set for the first item.

“Select Department” (optionLabel parameter):

This default text will be shown when no option is selected. This acts as a
placeholder for the dropdown and is displayed as an option that cannot be
selected. It encourages the user to select an actual department. If the user
selects no value, this option will be shown in the dropdown.

new { @class = “form-control” } (htmlAttributes parameter):

This is an anonymous object used to specify HTML attributes for the


rendered <select> element. In this case, the form-control class is added to
the dropdown to apply Bootstrap styling. You can add other HTML
attributes as needed, such as id, data-* attributes, style, etc., by specifying
them inside this object.

HTML Output

Now, run the application and access the Index Page. The helper method
should generate an HTML <select> element with options corresponding to
the list’s items as follows. To see this, please view the page source code in
the browser:

Here,

 The id and name attributes are “Departments”.


 The class=”form-control” applies Bootstrap styling.
 The first <option> is the default placeholder text, “Select
Department”.
 Each subsequent <option> is generated from the list of items with the
appropriate value and text.
 “IT” is selected by default because of Selected=true.
Tag Helpers in ASP.NET Core MVC
Tag Helpers in ASP.NET Core MVC allow server-side code to participate in
creating and rendering HTML elements in Razor views. They provide a way
to add server-side functionality to HTML elements in a more readable way
than traditional HTML helpers. Tag Helpers enhance HTML elements with
attributes that generate dynamic HTML and allow developers to create
cleaner and more maintainable markup.

The following are some of the Key Characteristics of Tag Helpers in


ASP.NET Core MVC:
 HTML-Like Syntax: Tag Helpers use HTML-like syntax, which allows

HTML developers to create and edit Razor views easily.


 Model Binding: Tag Helpers supports model binding.
 Reusable: They encapsulate the rendering logic and can be reused
across different views, reducing code duplication.
 Extensible: Developers can create custom Tag Helpers to meet
specific needs beyond what’s provided by built-in Tag Helpers.
 Easy to Understand: Tag Helpers use HTML-like syntax, making it
easier for developers to understand and work with than HTML
helpers, which rely on method calls.
 IntelliSense Support: Provides strong IntelliSense support within
Visual Studio, making development faster and reducing errors.

Types of Tag Helpers in ASP.NET Core MVC:


Tag Helpers in ASP.NET Core MVC are classified into two Types. They are
as follows:
 Built-In Tag Helpers: The ASP.NET Core framework provides these.
They include functionality for common tasks such as form handling,
link generation, and showing validation messages.
 Custom Tag Helpers: Developers can create their own Tag Helpers
to encapsulate specific functionality or rendering logic required by
their application.

Built-in Tag Helpers Type in ASP.NET Core MVC:


The ASP.NET Core MVC Framework provides several built-in HTML Tag
Helpers that generate the most common HTML elements and scenarios.
The following are some of the built-in HTML Tag Helpers available in
ASP.NET Core MVC:
 Form Tag Helpers: <form> Tag Helper generates HTML forms. They
help create forms that post data to actions in your controllers. For
example: <form asp-controller=”Account” asp-action=”Login”
method=”post”> <!– form fields –> </form>
 Input Tag Helpers: <input>, <label>, <textarea>, <select>, etc, to
facilitate form data management and validation. For example, <input
asp-for=”Name” /> and <input asp-for=”IsAdmin” type=”checkbox”
/>.
 Anchor Tag Helper: <a> Tag Helper for generating links using
routing information. For example, <a asp-controller=”Home” asp-
action=”Details” asp-route-id=”1″>Details</a>
 Image Tag Helper: <img> Tag Helper for rendering images with
dynamic sources. For example, <img src=”~/images/pic.jpg”
alt=”Picture”>
 Environment Tag Helper: <environment> Tag Helper for rendering
content conditionally based on the current environment, such as
Development, Staging, or Production.
 Cache Tag Helper: <cache> Tag Helper for output caching. This can
help cache portions of your views to improve performance by
reducing the need to recompute content on every request. For
example, <cache> <!– Content to be cached –> </cache>
 Partial Tag Helper: <partial> Tag Helper for rendering partial
views. This tag helper renders a partial view within another view.
 View Component Tag Helper: <view-component> tag helper
renders a view component within a view. View components are
similar to partial views but offer more encapsulation and flexibility.

How to Use Tag Helpers in ASP.NET Core MVC?


We need to follow the below two Steps to Use Tag Helpers in ASP.NET Core
MVC:
Enable Tag Helpers: To enable tag helpers, we first need to add the
@addTagHelper directive to our Razor view or layout file. You can also add
the @addTagHelper directive in the _ViewImports.cshtml file.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Use Tag Helpers: Use Tag Helpers directly (HTML-like syntax) in the
Razor views by adding them as HTML attributes. They will be processed on
the server side and rendered as HTML. For example, use asp-action, asp-
controller, or asp-for attributes to generate links or bind data to input
fields.
Example to Understand Built-in Tag Helpers in ASP.NET Core MVC:
create a new ASP.NET Core Application named TagHelpersDemo using the
Model-View-Controller Project template. To make the Built-in Tag Helpers
available for all views of our application, we need to import
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
directive inside the _ViewImports.cshtml file.

If you are creating the ASP.NET Core project using Model-View-Controller,


then by default, this directive is included inside the _ViewImports.cshtml.

If you open the _ViewImports.cshtml file, you will see the following code:

@using TagHelpersDemo
@using TagHelpersDemo.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

What is @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers


Directive in ASP.NET Core MVC?
The @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers directive
in an ASP.NET Core MVC application enables the built-in Tag Helpers
provided by the ASP.NET Core MVC framework to be used across all the
Razor views within the application.

This directive is typically added to the _ViewImports.cshtml file, a


common place for importing directives that should be shared across
multiple views.

Here,
@addTagHelper: This directive includes specific Tag Helpers in the Razor
view.

* (wildcard): The * symbol acts as a wildcard, loading all available Tag


Helpers from the specified assembly or namespace. In this case, it loads all
Tag Helpers from Microsoft.AspNetCore.Mvc.TagHelpers namespace.
Microsoft.AspNetCore.Mvc.TagHelpers: This is the namespace where the
built-in ASP.NET Core MVC Tag Helpers are defined. It includes Tag Helpers
such as:
 AnchorTagHelper for generating HTML links
 FormTagHelper for form management
 InputTagHelper for binding inputs to model properties
 LabelTagHelper for generating labels
 And many more…
Generating Links using Tag Helpers in ASP.NET Core MVC
Application:
First, create a class file named Student.cs within the Models folder, and
then please copy and paste the following code. This Student Model has only
five properties: ID, Name, Branch, Section, and Gender.

Modifying Home Controller:


Next, modify the HomeController as shown below. Here, we have created
two action methods. To simplify things and keep the focus on Tag helpers,
we have hard-coded the required student data within the action method.
The Index action method returns a list of students to the view, whereas the
Details action method takes the Student ID as a parameter and returns that
student information to the view.
Creating Details View:
Create a view named Details.cshtml within the Views=>Home folder,
then copy and paste the following code. The model for this view is Student,
and this view renders the Student information.
Modifying Index View:
Next, we need to display all the limited Student information within the
Index View and a link to the Details view. When we click the link, we need
to display the Student Details. For example, we need to generate the
following hyperlink. The number 101 is the ID of the student whose details
we want to view.
/home/details/101

Many different methods are available for generating a link in the ASP.NET
Core MVC Application.

Let’s discuss all the possible options and why we should use Tag Helper
over others.
Method 1: Using HTML Element:
In this case, we need to use the anchor tag, and in the href attribute, we
need to specify the path of the details action method (i.e., the Controller
Name and Action Name) along with the student id like <a
href=”/home/details/@student.StudentId”>View</a>. So, modify the
Index action method of the Home Controller as follows.
With the above changes, run the application and navigate to the Root
or Home/Index URL. You should see the following page on the web
browser.

Once you click the View button, the Home Controller’s Details action
method will execute by passing the corresponding Student ID value. If you
click the View button of Student ID 1, you will see the following Details
view of the Home Controller showing the Student details.
Method 2: Using HTML Helpers
Using HTML Helper methods, we can also generate the link. In this case, we
need to use the ActionLink Helper method to generate the link
like @Html.ActionLink(“View”, “Details”, “Home”, new { id =
student.StudentId }, new { @class = “btn btn-primary” }).

Here, the parameter View is nothing but the link text; the second
parameter Details is the Action method name; the third
parameter Home is the controller’s name.

The fourth parameter is object routeValues, which specifies the id


parameter value.

The fifth parameter is the HTML attributes, and here, we are applying the
BootStarp class. So, modify the Index.cshtml View of the Home Controller
as follows to use the HTML Helper Method to generate the link.
With the above changes, run the application and see if everything works as
expected.

Method 3: Using Tag Helpers:


To use Tag Helpers, please modify the Index view of the Home Controller as
shown below.
Now, run the application, and it should work as expected.

Understanding Anchor Tag Helper in ASP.NET Core MVC:


The Anchor Tag Helper in ASP.NET Core creates the standard HTML anchor
(<a … ></a>) tag by adding attributes such as:
 asp-controller: It is used to specify the controller to target based on
the routing system. For example, asp-controller=”Home” Specifies
the controller name (“Home”). If you omitted this, then the controller
of the current view is used by default.

 asp-action: It is used to specify the Action method to target based on


the routing system. For example, asp-action=”Details” Specifies the
action method name (“Details”). If you omit this attribute, the action
rendering the current view is the default.

 asp-route-{value}: It specifies the value required by the action


method. For example, asp-route-id=”@student.StudentId” specifies
the route parameter (in this case, the id) dynamically from the model,
i.e., @student.StudentId.
The value of the rendered anchor element’s “href” attribute is determined
by the values of these “asp-” attributes. As the name says, asp-controller
specifies the controller’s name, whereas asp-action specifies the action
name.
Similarly, the asp-route-{value} attribute includes route data in the
generated href attribute value. {value} can be replaced with route
parameters such as id, name, etc. Let us have a look at the following image
for a better understanding.

As you can see in the above image, manually generating the links is much
easier than using HTML Helpers or Tag Helpers. So why should we use
HTML helpers or Tag Helpers instead of manually generating these links in
ASP.NET Core?

Why should we use Tag Helpers over manually generating these links
in ASP.NET Core?
In ASP.NET Core MVC, Tag Helpers generate links based on the application
routing configuration. That means if we change the routing configuration in
the future, the links generated by tag helpers will automatically reflect
those changes. So, the generated links work as expected without any
trouble.

On the other hand, if we manually hard-code the URL paths, we need to


change the code wherever we have hard-coded the path in our application
when the application routing configuration changes. Let’s understand this
with an example.

The following is the program class code.


As you can see in the above code, currently, we have the route template
pattern as {controller=Home}/{action=Index}/{id?}.

Generating Link Manually:


We can generate the link manually using the following code by hard-coding
the URL paths as /Home/Details.

<a href=”/Home/Details/@student.StudentId”>View</a>

Generating Link using Tag Helper:


In the following code, we generate the link using anchor tag helper.
<a asp-controller=”Home” asp-action=”Details”
asp-route-id=”@student.StudentId”>View</a>

As you can see with Tag Helper, we have not hardcoded the URL paths.
Here, we only specify the controller and action name, route parameters,
and their values. When the tag helpers are executed on the server, they
automatically look at the route templates and generate the correct URLs.
So, to better understand, modify the Index View as follows:

Here, both the techniques generate the same URL path, i.e.
(/Home/Details/101), and it also works with the current route template,
i.e. ({controller=Home}/{action=Index}/{id?})

Modifying the Routing Configuration:


Now, let us change the routing template as shown below. Here, we have
added the string literal “dotnet” with the Route Template Pattern, i.e., the
Pattern is: dotnet/{controller=Home}/{action=Index}/{id?}

Run the application and navigate to the URL dotnet/Home/Index. Click on


the View buttons. You will observe that manually generating the link will
not work with the above changes in place, whereas the link generating with
Tag Helpers will work as expected.
Why Tag Helpers over HTML Helpers in ASP.NET Core MVC?
Tag Helpers are often preferred over HTML Helpers in ASP.NET Core MVC
for several reasons:

Readable and HTML-Like Syntax


Tag Helpers use HTML-like syntax, which makes them easier to read and
work with, especially for front-end developers familiar with HTML.

Example Using Tag Helper: <a asp-action=”Details” asp-controller=”Home”


asp-route-id=”@student.StudentId” class=”btn btn-primary”>View</a>

Example Using HTML Helper: @Html.ActionLink(“View”, “Details”, “Home”,


new { id = student.StudentId }, new { @class = “btn btn-primary” })

In the Tag Helper example, the code looks like standard HTML and the
attributes are more self-explanatory (asp-action, asp-controller, asp-route-
id). In contrast, the HTML Helper syntax is more complex and harder to
read, especially for designers or developers coming from an HTML
background.

Better IntelliSense Support


Tag Helpers are fully integrated with IntelliSense in Visual Studio, offering
auto-completion, tooltips, and error checking directly in the Razor view.
This improves productivity and reduces the chance of mistakes.

Tag Helper Example: <input asp-for=”UserName” class=”form-control” />


As you type asp-for=”UserName”, IntelliSense will suggest model
properties and provide contextual information.

HTML Helper Example: @Html.TextBoxFor(m => m.UserName, new {


@class = “form-control” })
IntelliSense is less effective in the HTML Helper example, making it harder
to remember correct method signatures and syntax.

Cleaner and More Maintainable Code


Tag Helpers follow the natural HTML flow, resulting in cleaner and more
maintainable Razor views, especially when working with complex forms or
UI components.
Tag Helper Example:

HTML Helper Example:

The code in the Tag Helper version is cleaner and follows an HTML-first
approach. In contrast, the HTML Helper version embeds C# logic in the
markup, which can make the view more difficult to maintain, especially as
the form’s complexity grows.
Navigation-Menus in ASP.NET Core MVC Application
How to Create Responsive Navigation-Menus in ASP.NET Core MVC
Applications using Bootstrap and jQuery.

What is Responsive Navigation Menus in ASP.NET Core MVC?


Responsive Navigation Menus are dynamic navigation menus that adapt and respond to
different screen sizes and devices used to view the website. They adjust their layout,
font sizes, and positioning to provide a consistent user experience across desktops,
tablets, and mobile devices. In ASP.NET Core MVC, this can be achieved using front-
end frameworks like Bootstrap, which provides built-in support for responsive design,
including navigation menus that collapse or adjust based on the screen size.

Example to Understand Navigation Menus in ASP.NET Core MVC:


Let us understand this with an example. We want to develop one application, and when
we open our web application on large-screen devices like desktops and tablets, we want
the navigation menus to look like the image below. Here, the menus List, Create, About,
and Contact are visible in a horizontal bar.

But when we open our website on a small screen device like a mobile, we want to show
the navigation menus like the one below. Here, you can see the menus List, Create,
About, and Contact are not visible; instead, the hamburger menu (three horizontal lines)
is visible, and once we click on the three horizontal lines, it will display all the menus.

Creating a New ASP.NET Core MVC Application:


First, create a new ASP.NET Core Application using the Model-View-
Controller Project Template named FirstCoreMVCApplication. Once you
have created the project, please ensure Bootstrap and jQuery files are
added. By default, these files are automatically added when you create the
project using the Model-View-Controller template.

Adding images Folder inside the wwwroot folder:


Add a folder called images with the wwwroot folder and then paste two
different images with the names Logo.png and Student.png, as shown in
the image below.

Modifying _Layout.cshtml file:


Create your navigation menu using the Bootstrap Navbar component.
Bootstrap’s Navbar automatically becomes responsive and toggles between
a horizontal menu and a hamburger menu on smaller screens.

Please modify the _Layout.cshtml file, which is present inside the Views
=> Shared folder, as shown below.

In the head section, we refer to the files MyCustomStyleSheet.css,


bootstrap.css, query.js, and bootstrap.js. The navbar-toggler button is a
responsive component that will appear on smaller screen sizes.

When clicked, it toggles the visibility of the navigation menu items.


Creating Models:
Next, we need to create two enums to store a student’s Gender and Branch.
So, create two classes within the Models folder named Gender.cs and
Branch.cs. Open the Branch.cs class file and copy and paste the following
code. As you can see, we have created the Branch enum with four named
constants, i.e., None, CSE, ETC, and Mech.

Next, open the Gender.cs class file and copy and paste the following code.
As you can see, we have created the Gender enum with two named
constants, i.e., Male and Female.

Student Model:
We want to display the student information on the web page. So, create a
class file named Student.cs within the Models folder and copy and paste the
following code.

Modifying Home Controller:


Next, modify the Home Controller as shown below. As you can see in the
code below, we have added two action methods. The Index action method
will return all the students, while the Details action takes the student ID
and returns that student’s information.

Modifying Index.cshtml file:


Please modify the Index view, which is present inside the Home folder, as
shown below. Notice how the buttons (View, Edit, and Delete) are attached
to each other. Use the Bootstrap margin classes (m-1, m-2, etc.) to include
the margin between these buttons. In the class name, “m” stands for
margin, and the numbers 1, 2, 3, etc., are the size of the space you want
between the buttons. In this view, List<Student> is the model, and using a
for each loop, we are accessing all the students. Further, if you notice, we
have used Tag Helper to generate the link for the View button.
Creating Detail.cshtml file:
Please create a view named Details.cshtml within the Views/Home folder
and copy and paste the following code into it. In this view, the Student will
be the model, and we can access the student model properties using the
@Model object.
Now, run your application and resize the browser window, or use a mobile
device to see the responsive navigation menu in action. On smaller screens,
the menu items should collapse into a hamburger menu (three horizontal
lines). When you click the hamburger menu, the menu items will appear in
a dropdown.
Form Tag Helpers in ASP.NET Core MVC
Tag Helpers in ASP.NET Core MVC make binding and generating HTML
elements in Razor views easier. ASP.NET Core MVC Framework provides
several Tag Helpers to simplify form generation, binding, and validation
when creating forms. Let us understand this with an example. We will
create a form using Tag Helpers, as shown below. The following form is
used to create a student.

Let us proceed and implement this step by step. First, create a new
ASP.NET Core MVC Application using the Model View Controller Project
template and give the project name FormTagHelperDemo.

Creating Models:
First, we need to create two Enums to hold the Gender and Branch-named
constants and the Student model, which will hold the student data.

Creating Gender Enum:


The Gender enum is a strongly typed list of constants representing the
gender options available in the student registration form. It helps avoid
hard-coding gender strings and ensures that only predefined values (Male,
Female, or Other) can be selected. So, create a class file named Gender.cs
within the Models folder and copy and paste the following code.
Creating Branch Enum
Like the Gender enum, the Branch enum provides a list of fixed values
representing different branches of study, such as CSE (Computer Science),
ETC (Electronics & Telecommunications), Mechanical, and Electrical. This
ensures that users select only valid branch options when filling out the
form. So, create a class file named Branch.cs within the Models folder and
copy and paste the following code.

Creating Student Model


The Student class represents the model for student registration in our
application. It defines the data structure and validation rules for the
student entity. This class will be used in views and controllers to handle the
data inputted by users.

It includes properties for storing student information, such as FullName,


Password, DateOfBirth, Gender, Address, Branch, etc. The class also uses
data annotations to specify validation rules, like requiring certain fields and
limiting the length of strings. So, create a class file named Student.cs within
the Models folder and then copy and paste the following code.
Creating the Student Controller:
Next, create an Empty MVC controller named StudentController within the
Controllers folder and copy and paste the following code. The following
StudentController manages operations related to student registration,
viewing student lists, and displaying student details. The controller
interacts with the Student model and handles incoming HTTP requests for
student-related actions.
Creating Student List View:
Next, create a view named List.cshtml within the Views/Student folder and
then copy and paste the following code. The following view is to display a
list of students in a tabular format and provide actions (such as viewing
details) for each student. This view is typically rendered by the
StudentController’s List action, which passes a collection of Student objects
to the view as the model.
Creating Student Details View:
Next, create a view named Details.cshtml within the Views/Student folder
and then copy and paste the following code. The following view is to
display detailed information about a specific student. It provides a clear
and organized presentation of the student’s data using a card layout with
Bootstrap styling. This view is typically rendered by the Details action of
the StudentController, where a specific student is passed as the model. The
“Back to List” button allows for easy navigation to the List View Page.
Creating Student Register View:
Next, create a view named Register.cshtml within the Views/Student folder
and copy and paste the following code. The following view is to provide a
registration form for students, allowing users to input various details about
a student and submit the form. This view is designed to interact with the
Register action of the StudentController, which handles both displaying the
form (GET request) and processing the submitted data (POST request).
Understanding the Tag Helper used in the above Code:
We have used the following built-in Tag helpers to generate the Form in
ASP.NET Core MVC Application:
asp-action (Used in the <form> Tag):
Example: <form asp-action=”Register” asp-controller=”Student”
method=”post” class=”form-horizontal”>

The asp-action Tag Helper specifies the name of the action method to which
the form will submit its data. When this form is submitted, the data will be
sent to the Register action method of the specified controller (in this case,
the StudentController).

asp-controller (Used in the <form> Tag):


Example: <form asp-action=”Register” asp-controller=”Student”
method=”post” class=”form-horizontal”>

The asp-controller Tag Helper specifies the controller’s name, which


contains the action method to which the form will submit data. This tells
the form that the Register action method resides in the StudentController.

asp-for (Used in <label>, <input>, <textarea>, and <select> Tags)


Example: <label asp-for=”FullName”>, <input asp-for=”FullName”>,
<textarea asp-for=”Address”>, <select asp-for=”Branch”>

The asp-for Tag Helper automatically binds the form element to a model
property. It generates the appropriate id, name, and value attributes for the
HTML element based on the bound property in the Student model. For
example, asp-for=”FullName” binds the <input> element to the FullName
property of the Student model. It also generates the correct label text and
sets for attributes in <label> elements.

asp-validation-for (Used in <span> Tags)


Example: <span asp-validation-for=”FullName” class=”text-
danger”></span>.

The asp-validation-for Tag Helper displays validation error messages


associated with the specified model property. If validation errors exist for
the FullName property, the error messages will be displayed inside the
<span> element. It also allows for custom styling (e.g., text-danger for red
text in Bootstrap).

asp-for with <input type=”radio”> (Used in Radio Buttons)


Example: <input type=”radio” asp-for=”Gender” value=”@gender”
class=”form-check-input”>.

The asp-for Tag Helper, in this case, binds the radio buttons to the Gender
property in the model. Each radio button is created dynamically for each
enum value (Male, Female, etc.). The value=”@gender” sets the value of
each radio button to the corresponding gender enum value.

asp-for with <select> (Used in Dropdowns)


Example: <select asp-for=”Branch” class=”form-control”>.

The asp-for Tag Helper binds the <select> dropdown to the Branch
property in the Student model. The Tag Helper generates the necessary
name, id, and value attributes, and the dropdown options are dynamically
populated using a foreach loop that iterates over the Branch enum values.

asp-for with <input type=”checkbox”> (Used in Single Checkboxes)


Example: <input asp-for=”TermsAndConditions” type=”checkbox”
class=”form-check-input”>.

This binds the checkbox to the TermsAndConditions boolean property in


the Student model. If the model property is true, the checkbox will be
checked when the form is loaded. The Tag Helper ensures the correct
binding and naming of the checkbox input element.
asp-for with <select multiple> (Used in ListBox for Multi-Select)
Example: <select asp-for=”Skills” class=”form-control” multiple>.

The asp-for Tag Helper binds the multi-select dropdown to the Skills list in
the Student model. When the form is submitted, the selected values from
the multi-select dropdown are bound to the Skills list in the model. The
multiple attribute allows multiple options to be selected.

asp-for with <textarea> (Used for Multi-line Input)


Example: <textarea asp-for=”Address” class=”form-
control”></textarea>

This Tag Helper binds the <textarea> element to the Address property of
the Student model. It handles multi-line input and ensures the correct ID,
name, and initial value are set from the model data.

asp-for with <input type=”password”> (Used for Password Fields)


Example: <input asp-for=”Password” type=”password” class=”form-
control” />.

The asp-for Tag Helper binds the <input> element to the Password
property of the model, ensuring that the name and id attributes are set
correctly. The type=”password” attribute ensures that the input will be
treated as a password field, hiding the user’s input.

Modifying the Layout View:


Next, please modify the Layout view as follows. Here, we are adding a few
menus that link to the Student List and Register Student Pages.
Testing the Application:
We are done with our application implementation. Now, run the
application and click on the Student List menu, which should display the
following page:
Next, click on the Details button in the List Page, and you should see the
Student Details information as shown in the below image:

Now, click the Add New Student menu to open the Student Registration
page. Please fill out the form and click on the Register button as shown in
the image below:

Once you click on the Register button, it should Register the new Student
and navigate to the Student list Page, where you should see the newly
created student as shown in the image below:
Partial Tag Helper in ASP.NET Core MVC
What is a Partial View in ASP.NET Core MVC?
A Partial View in ASP.NET Core MVC is a reusable View Component that can
be embedded within other views. It is essentially a smaller view or part of a
view rendered inside a parent view. Partial Views are useful when we want
to break down large views into smaller, manageable components that can
be reused across different views in our application.

Partial Views are similar to regular views but do not have a layout by
default.
They typically render a portion of the view or page, like headers, footers,
forms, or other sections.
You can pass data to Partial Views using the parent model or passing a
separate one.

What is Partial Tag Helper in ASP.NET Core MVC


The Partial Tag Helper in ASP.NET Core MVC is a built-in Tag Helper that
simplifies rendering partial views directly within Razor views. Instead of
using the HTML Helper Methods (such as Html.Partial, Html.RenderPartial,
Html.PartialAsync, and Html.RenderPartialAsync) in Razor views, the
Partial Tag Helper provides a cleaner and more expressive HTML-like
syntax to render the Partial Views.

How Do We Use Partial Tag Helper in ASP.NET Core MVC?


To use the Partial Tag Helper, we need to follow the following steps:

Create the Partial View:


Define the partial view in the Views/Shared folder or any other folder
under Views. Ensure the partial view has a name starting with an
underscore (e.g., _UserProfilePartial.cshtml, _FooterPartial.cshtml).

Use the Partial Tag Helper in Your Main View:


In the main view where you want to include the partial view, use the
<partial> tag helper. If you need to pass a model to the Partial View, use the
model attribute within the Partial Tag Helper, as shown in the below
example:
<partial name=”_UserProfilePartial” model=”@Model.UserProfile” />

Rendering Without a Model: If the partial view does not require any
specific model, you can render it like the below example:
<partial name=”_FooterPartial” />

Note: The name attribute specifies the name of the partial view, and the
model attribute provides the model data to be used within it.

Partial Tag Helper Real-Time Example in ASP.NET Core MVC:


Let us understand Partial Tag Helper with one Real-Time Example in an
ASP.NET Core MVC Application. In this application, we will implement
three partial views using the Partial Tag Helper. One partial view will use
model data, and the other two partial views will be static without any
model data.

We have an application that displays a list of products on a page. We will


include a footer and a header that is consistent across all pages. The
product list will be rendered via a partial view that receives model data,
while the footer and header will be rendered via partial views that do not
need any model data.

First, create a new ASP.NET Core Project using the Model View Controller
Template and name it PartialTagHelperDemo.

Create the Model:


First, create a class file named Product.cs within the Models folder and then
copy and paste the following code. This model will be used to pass data to
the partial view that displays the product list.

Modify the Home Controller


Now, modify the HomeController as follows: We will generate some
dummy product data and render the views.
Create the Partial Views
Next, we need to create three Partial Views inside the Views/Shared folder.

_ProductListPartial.cshtml (With Model Data)


This partial view will display the product list passed from the controller. It
will display the product details, including the image, name, description, and
price. We will also indicate whether the product is in stock. So, create the
Partial view named _ProductListPartial.cshtml within the Views/Shared
folder and then copy and paste the following code.
_HeaderPartial.cshtml (Without Model Data)
This partial view will contain the static header section, which will be
consistent across all pages. We will create a header partial view that
includes a simple navigation bar with Bootstrap styling. So, create the
Partial view named _HeaderPartial.cshtml within the Views/Shared folder
and then copy and paste the following code.

_FooterPartial.cshtml (Without Model Data)


This partial view will contain the static footer section, which will be
consistent across all pages. This partial view will contain a Bootstrap-styled
footer with contact information and social media links. So, create the
Partial view named _FooterPartial.cshtml within the Views/Shared folder
and then copy and paste the following code.

Update the _Layout.cshtml View


The layout view will contain the header and footer, which will be shared
across all views in the application. So, modify the _Layout.cshtml View as
follows:
Index.cshtml (Parent View with Partial Tag Helpers)
Finally, the Index view will include Product List partial views. So, modify
the Index.cshtml View as follows:

Run the Application


Once you have set up the views, controller, and model, run the application.
You should see a beautifully designed product page, as shown in the image
below.

Here, you can see

A Header that includes navigation links.


A Product List that displays detailed information about each product,
including name, description, price, stock status, and an image.
A Footer with company information and links.

You might also like