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

Layout View in ASPCore

The document discusses the Layout View in ASP.NET Core MVC, which serves as a shared template for maintaining a consistent look across different views in an application. It explains the importance of using Layout Views to reduce code duplication and facilitate easier maintenance by defining common elements like headers, footers, and navigation menus in one place. Additionally, it covers how to create and implement Layout Views, including the use of sections for injecting page-specific content into the layout.

Uploaded by

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

Layout View in ASPCore

The document discusses the Layout View in ASP.NET Core MVC, which serves as a shared template for maintaining a consistent look across different views in an application. It explains the importance of using Layout Views to reduce code duplication and facilitate easier maintenance by defining common elements like headers, footers, and navigation menus in one place. Additionally, it covers how to create and implement Layout Views, including the use of sections for injecting page-specific content into the layout.

Uploaded by

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

Layout View in ASP.

NET Core MVC

Here I am going to discuss the Layout View in ASP.NET Core MVC Web Application with Examples.

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
our 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.

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

1
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.

<!DOCTYPE html>

<html>

<head>

2
<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<div>

@RenderBody()

</div>

</body>

</html>
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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

3
</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

</td>

<td style="width:600px">

@RenderBody()

</td>

</tr>

<tr>

<td colspan="2" style="text-align:center; font-size:x-small">

<h3>Website Footer</h3>

</td>

</tr>

</table>

</body>

</html>
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.

using Microsoft.AspNetCore.Mvc;

namespace FirstCoreMVCApplication.Controllers

public class HomeController : Controller

public ViewResult Index()

return View();

public ViewResult Details()

return View();

4
}

}
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”;

@{

ViewBag.Title = "Home Page";

Layout = "~/Views/Shared/_Layout.cshtml";

<h1>Home Page</h1>
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”;

@{

ViewBag.Title = "Details Page";

Layout = "~/Views/Shared/_Layout.cshtml";

<h1>Details Page</h1>
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.

5
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.
That’s it for today. In the next article, I am going to discuss Layout Page Sections in ASP.NET Core
MVC Applications. This article explains How to Create and Use Layout View Files in ASP.NET Core MVC
Applications with Examples.

Sections in Layout View in ASP.NET Core MVC

In this article, I will discuss the Sections in Layout View in ASP.NET Core MVC Application. Please
read our previous article discussing the Layout View in ASP.NET Core MVC Application. We will also
work with the example we created in our previous article. As part of this article, we will discuss the
following pointers.

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.

6
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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

7
</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

</td>

<td style="width:600px">

@RenderBody()

</td>

</tr>

<tr>

<td colspan="2" style="text-align:center; font-size:x-small">

<h3>Website Footer</h3>

</td>

</tr>

</table>

<script src="~/js/CustomJavascript.js"></script>

</body>

</html>
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.

Understanding the RenderSection and RenderSectionAsync Method:

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.

8
 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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

</td>

<td style="width:600px">

@RenderBody()

9
</td>

</tr>

<tr>

<td colspan="2" style="text-align:center; font-size:x-small">

<h3>Website Footer</h3>

</td>

</tr>

</table>

@RenderSection("Scripts")

</body>

</html>
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”)

@{

ViewBag.Title = "Home Page";

Layout = "~/Views/Shared/_Layout.cshtml";

<h1>Home Page</h1>

@section Scripts {

<script src="~/js/CustomJavascript.js"></script>

}
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.

10
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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

11
</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

</td>

<td style="width:600px">

@RenderBody()

</td>

</tr>

<tr>

<td colspan="2" style="text-align:center; font-size:x-small">

<h3>Website Footer</h3>

</td>

</tr>

</table>

@RenderSection("Scripts", false)

</body>

</html>
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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

12
</td>

<td style="width:600px">

@RenderBody()

</td>

</tr>

<tr>

<td colspan="2" style="text-align:center; font-size:x-small">

<h3>Website Footer</h3>

</td>

</tr>

</table>

@if (IsSectionDefined("Scripts"))

@RenderSection("Scripts")

</body>

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

RenderSectionAsync method in ASP.NET Core MVC Layout View:

Let’s understand the RenderSectionAsync method in ASP.NET Core MVC Layout View with one real-
time example: a blogging platform. In this example, we will use the RenderSectionAsync method in the
layout view to handle a section where we load some user-specific data asynchronously, such as recent
comments, which could take time due to database querying or processing.

Blogging Platform Layout with Asynchronous Sections

In the blogging platform, each page has a section that displays the recent comments or all comments.
The comments are fetched from the database and can vary in loading time depending on the number
of comments and server load. We want this section to load independently without blocking the
rendering of the rest of the page.

Define the Comment Model

First, let’s define a Comment model class that will represent a comment. Create a class file
named Comment.cs within the Models folder and then copy and paste the following code. This is a
simple model with two properties: Text and User.

namespace FirstCoreMVCApplication.Models

public class Comment

public string Text { get; set; }

public string User { get; set; }

}
Create the CommentService Class

13
Next, we will create a CommentService class that includes the GetRecentCommentsAsync() method.
This method will asynchronously return a list of Comment objects. So, create a class file
named CommentService.cs within the Models folder and then copy and paste the following code.

namespace FirstCoreMVCApplication.Models

public class CommentService

public static async Task<List<Comment>> GetRecentCommentsAsync()

// Simulate asynchronous data fetching by waiting for a short time

await Task.Delay(500); // Wait for half a second

// Return some hardcoded comments

return new List<Comment>

new Comment(){Text = "This is a great post!", User= "Alice"},

new Comment(){Text = "Very informative, thanks for sharing.", User= "Bob"},

new Comment(){Text = "I had a similar experience.", User= "Charlie"}

};

}
Modifying the _Layout.cshhtml

First, define the @RenderSectionAsync in your Layout view. This section will be used to render
notifications. So, modify the _Layout.cshhtml view as follows:

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<table border="1" style="width:800px; font-family:Arial">

<tr>

<td colspan="2" style="text-align:center">

<h3>Website Header</h3>

</td>

</tr>

<tr>

<td style="width:200px">

<h3>Left Navigation Menus</h3>

</td>

14
<td style="width:600px">

@RenderBody()

</td>

</tr>

<tr>

<td colspan="2" style="text-align:left;">

@await RenderSectionAsync("RecentComments", required: false)

</td>

</tr>

</table>

</body>

</html>
The layout view defines a section @await RenderSectionAsync(“RecentComments”, required:
false). This means it will render the “RecentComments” section if it is defined in the child view, but it
is not mandatory for every page.

Modifying the Index.cshhtml

In one of the views, let’s define the “RecentComments” section that we referenced in the layout. We
will make a call to a service that fetches recent comments and renders them. So, modify the
Index.cshhtml view as follows:

@{

ViewBag.Title = "Home Page";

Layout = "~/Views/Shared/_Layout.cshtml";

<h1>What is Section in Layout View</h1>

<p>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.

</p>

@section RecentComments {

<h3>Recent Comments</h3>

@{

var comments = await CommentService.GetRecentCommentsAsync();

if (comments.Any())

<ul>

@foreach (var comment in comments)

<li>@comment.Text - <strong>@comment.User</strong></li>

15
}

</ul>

else

<p>No recent comments.</p>

}
This view defines the content for the “RecentComments” section. It uses asynchronous
operations (await CommentService.GetRecentCommentsAsync()) to fetch recent comments. By
using RenderSectionAsync, the rest of the layout (main content, header, footer) can be rendered
independently and won’t have to wait for this potentially slow operation.

With the above changes in place, run the application and access the Index view. You should see the
output as expected, as shown in the image below.

By rendering the comments section asynchronously, the main content of the page can load without
having to wait for the comments to be fetched and processed. Users see the main parts of the page
(like the header and main content) quickly, which can be crucial for user retention and satisfaction,
especially during peak server load times.

ViewStart in ASP.NET Core MVC Application

In this article, I will discuss the ViewStart in ASP.NET Core MVC Web Application with Examples.
Please read our previous article before proceeding to this article, as it is a continuation part of our
previous article. Please read our previous article discussing the Sections in Layout View in
ASP.NET Core MVC Application. As part of this article, we will discuss the following pointers.

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.

16
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.

17
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.

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}
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.

@{

ViewBag.Title = "Home Page";

<h1>Home Page</h1>

@section Scripts {

<script src="~/js/CustomJavascript.js"></script>

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

@{

ViewBag.Title = "Details Page";

<h1>Details Page</h1>
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

18
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.

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<div>

@RenderBody()

</div>

@if (IsSectionDefined("Scripts"))

@RenderSection("Scripts")

</body>

</html>
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.

@{

Layout = "~/Views/Shared/_MyLayout.cshtml";

}
With the above changes in place, our application’s Views folder should look like the image below.

19
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.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

</head>

<body>

<div>

20
<h4>This View Using _NewLayout.cshtml</h4>

@RenderBody()

</div>

</body>

</html>
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.

@{

ViewBag.Title = "Details Page";

Layout = "~/Views/Shared/_NewLayout.cshtml";

<h1>Details Page</h1>
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.

@{

ViewBag.Title = "Details Page";

Layout = null;

<h1>Details Page</h1>
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.

21
@{

if (User.IsInRole("Admin"))

Layout = "_AdminLayout";

else

Layout = "_NonAdminLayout";

}
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:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>@ViewData["Title"] - @ViewData["ApplicationName"]</title>

</head>

<body>

<header>

<h1>@ViewData["Header"]</h1>

</header>

<main>

@RenderBody()

</main>

<footer>

<p>@DateTime.Now.Year © My News Site. All rights reserved.</p>

</footer>

</body>

</html>
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

22
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:

@{

Layout = "~/Views/Shared/_Layout.cshtml";

ViewData["Title"] = "Welcome";

ViewData["ApplicationName"] = "My ASP.NET Core MVC App";

ViewData["Header"] = "News Around Us";

}
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:

@{

// This will override the default title set in _ViewStart

ViewData["Title"] = "Home";

<p>Welcome to our news site @ViewData["ApplicationName"]. Check out the latest articles!</p>
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

23
In this article, I will discuss ViewImports in an ASP.NET Core MVC Application. Please read our
previous article before proceeding to this one, as it is a continuation of our previous article, where we
discussed the ViewStart in Layout Page in ASP.NET Core MVC Application.

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.

namespace FirstCoreMVCApplication.Models

public class Student

public int StudentId { get; set; }

24
public string? Name { get; set; }

public string? Branch { get; set; }

public string? Section { get; set; }

public string? Gender { get; set; }

}
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.

using FirstCoreMVCApplication.Models;

using Microsoft.AspNetCore.Mvc;

using System.Collections.Generic;

namespace FirstCoreMVCApplication.Controllers

public class HomeController : Controller

public ViewResult Index()

List<Student> listStudents = new List<Student>()

new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male"

},

new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male"

},

new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male"

},

new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female"

},

new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female"

};

return View(listStudents);

public ViewResult Details(int Id)

var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A",

Gender = "Male" };

return View(studentDetails);

25
}
Modifying the Index and Details view:

Index.cshtml:

@model List<FirstCoreMVCApplication.Models.Student>

@{

Layout = null;

<html>

<head>

<title>Index</title>

</head>

<body>

<table>

<thead>

<tr>

<th>ID</th>

<th>Name</th>

<th>Branch</th>

<th>Section</th>

<th>Gender</th>

</tr>

</thead>

<tbody>

@foreach (var student in Model)

<tr>

<td>

@student.StudentId

</td>

<td>

@student.Name

</td>

<td>

@student.Branch

</td>

<td>

@student.Section

</td>

<td>

@student.Gender

26
</td>

</tr>

</tbody>

</table>

</body>

</html>
Details.cshtml:

@model FirstCoreMVCApplication.Models.Student

@{

Layout = null;

<html>

<head>

<title>Student Detaills</title>

</head>

<body>

<div>

StudentId : @Model?.StudentId

</div>

<div>

Name : @Model?.Name

</div>

<div>

Branch : @Model?.Branch

</div>

<div>

Section : @Model?.Section

</div>

<div>

Gender : @Model?.Gender

</div>

</body>

</html>
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

27
the Add button as shown in the image below, which should create the _ViewImport.cshtml within
the Views folder.

Advertise
ments

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.

@using FirstCoreMVCApplication

@using FirstCoreMVCApplication.Models

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
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:

28
 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

In this article, I will discuss the Partial Views in ASP.NET Core MVC Applications with Examples.
Please read our previous article discussing ViewImports in ASP.NET Core MVC Application. At the
end of this article, you will understand What Partial Views in ASP.NET Core MVC are, Why We Need
Partial Views, and how to implement Partial Views in the ASP.NET Core MVC Application with Examples.

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.

Advertisements
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

29
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.

namespace PartialViewInMVC.Models

public class Product

public long ProductID { get; set; }

public string? Name { get; set; } = null!;

public string Category { get; set; } = null!;

public string Description { get; set; } = null!;

public decimal Price { get; set; }

}
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.

using Microsoft.AspNetCore.Mvc;

using PartialViewInMVC.Models;

30
namespace PartialViewInMVC.Controllers

public class ProductController : Controller

private List<Product> products = new List<Product>();

public ProductController()

products = new List<Product>()

new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description

1", Price = 10m},

new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description

2", Price = 20m},

new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description

3", Price = 30m},

new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description

4", Price = 40m},

new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description

5", Price = 50m},

new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description

6", Price = 50m}

};

//Product/Details/1

public ActionResult Details(int Id)

var ProductDetails = products.FirstOrDefault(prd => prd.ProductID == Id);

return View(ProductDetails);

}
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<table class="table">

31
<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

<tr>

<td>

@Model?.ProductID

</td>

<td>

@Model?.Name

</td>

<td>

@Model?.Category

</td>

<td>

@Model?.Description

</td>

<td>

@Model?.Price

</td>

</tr>

</table>

</div>
Now, run the application and navigate to URL: Product/Details/1, and you should get the following
output.

32
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.

33
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.

@model PartialViewInMVC.Models.Product

<tr>

<td>

@Model?.ProductID

</td>

<td>

@Model?.Name

</td>

<td>

@Model?.Category

</td>

<td>

@Model?.Description

</td>

<td>

@Model?.Price

</td>

</tr>
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

34
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

35
</th>

</tr>

@await Html.PartialAsync("_ProductDetails", Model)

</table>

</div>
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.

using Microsoft.AspNetCore.Mvc;

using PartialViewInMVC.Models;

namespace PartialViewInMVC.Controllers

public class ProductController : Controller

private List<Product> products = new List<Product>();

public ProductController()

products = new List<Product>()

new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description

1", Price = 10m},

new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description

2", Price = 20m},

new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description

3", Price = 30m},

new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description

4", Price = 40m},

new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description

5", Price = 50m},

36
new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description

6", Price = 50m}

};

//Product/Index

public ActionResult Index()

return View(products);

//Product/Details/1

public ActionResult Details(int Id)

var ProductDetails = products.FirstOrDefault(prd => prd.ProductID == Id);

return View(ProductDetails);

}
Next, add the Index.cshhtml view within the Views => Product folder. Once you add the view, copy
and paste the following code.

@model IEnumerable<PartialViewInMVC.Models.Product>

@{

ViewData["Title"] = "Index";

<h4>Product List</h4>

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

37
</tr>

@foreach (var item in Model)

@await Html.PartialAsync("_ProductDetails", item)

</table>
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.

@model IEnumerable<PartialViewInMVC.Models.Product>

@{

ViewData["Title"] = "Index";

<h4>Product List</h4>

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

38
</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

@foreach (var item in Model)

@Html.Partial("_ProductDetails", item)

</table>
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.

@model IEnumerable<PartialViewInMVC.Models.Product>

@{

ViewData["Title"] = "Index";

<h4>Product List</h4>

39
<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

@foreach (var product in Model)

<partial name="_ProductDetails" model="product" />

</table>
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 this article, I will discuss Different Ways to Render a Partial View in an ASP.NET Core MVC
Application with Examples. Please read our previous article on Partial Views in ASP.NET Core
MVC Applications. We will work with the same example we created in that article.

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

40
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.

using Microsoft.AspNetCore.Mvc;

using PartialViewInMVC.Models;

namespace PartialViewInMVC.Controllers

public class ProductController : Controller

private List<Product> products = new List<Product>();

public ProductController()

products = new List<Product>()

new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description

1", Price = 10m},

new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description

2", Price = 20m},

new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description

3", Price = 30m},

new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description

4", Price = 40m},

new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description

5", Price = 50m},

new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description

6", Price = 50m}

};

41
public ActionResult Index()

return View(products);

public ActionResult Details(int Id)

var ProductDetails = products.FirstOrDefault(prd => prd.ProductID == Id);

return View(ProductDetails);

}
Next, modify the _ProductDetails.cshtml Partial View file as follows:

@model PartialViewInMVC.Models.Product

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

<tr>

<td>

@Model?.ProductID

</td>

<td>

@Model?.Name

</td>

<td>

@Model?.Category

42
</td>

<td>

@Model?.Description

</td>

<td>

@Model?.Price

</td>

</tr>

</table>
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<p>Rendering the Result of Partial View</p>

@Html.Partial("_ProductDetails", Model)

<br/>

<p>Storing the Result of Partial View into a variable</p>

43
@{

var result = Html.Partial("_ProductDetails", Model);

<span>@result</span>

</div>
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<p>Rendering the Result of Partial View</p>

@await Html.PartialAsync("_ProductDetails", Model)

<br/>

<p>Storing the Result of Partial View into a variable</p>

@{

var result = await Html.PartialAsync("_ProductDetails", Model);

<span>@result</span>

</div>
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.

44
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<p>Rendering the Result of Partial View</p>

@{

Html.RenderPartial("_ProductDetails", Model);

</div>
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.

45
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<p>Rendering the Result of Partial View</p>

@{

await Html.RenderPartialAsync("_ProductDetails", Model);

</div>
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

<div>

<h4>Product Details</h4>

<p>Rendering the Result of Partial View</p>

<partial name="_ProductDetails" model="Model" />

</div>
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.

46
@model PartialViewInMVC.Models.Product

@{

var heading = ViewData["Header"];

<h2>@heading</h2>

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

<tr>

<td>

@Model?.ProductID

</td>

<td>

@Model?.Name

</td>

<td>

@Model?.Category

</td>

<td>

@Model?.Description

</td>

<td>

@Model?.Price

</td>

</tr>

</table>

47
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.

@model PartialViewInMVC.Models.Product

@{

ViewData["Title"] = "Details";

ViewData["Header"] = "Product Details";

<div>

<p>Using Tag Helper</p>

<partial name="_ProductDetails" model="Model" view-data="ViewData" />

<p>Using Html.Partial</p>

@Html.Partial("_ProductDetails", Model, ViewData)

<p>Using Html.PartialAsync</p>

@await Html.PartialAsync("_ProductDetails", Model, ViewData)

<p>Using Html.RenderPartial</p>

@{

Html.RenderPartial("_ProductDetails", Model, ViewData);

<p>Using Html.RenderPartialAsync</p>

@{

await Html.RenderPartialAsync("_ProductDetails", Model, ViewData);

</div>
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.

48
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.
View Components in ASP.NET Core MVC

In this article, I am going to discuss View Components in ASP.NET Core MVC Application with
Examples. Please read our previous article discussing Different Ways to Render Partial Views in
ASP.NET Core MVC Applications. At the end of this article, you will understand the following pointers.

1. What are the View Components in ASP.NET Core MVC?


2. What Are All Files Available in a View Component in ASP.NET Core MVC?
3. What Should be the Location for the Files of View Components in ASP.NET Core?
4. Example to Understand View Component in ASP.NET Core MVC.
5. How Do We Invoke a View Component from a View File in ASP.NET Core MVC?
6. View Component vs. Partial View in ASP.NET Core MVC
What are the View Components in ASP.NET Core MVC?

View Components in ASP.NET Core MVC are used to create reusable components that can encapsulate
rendering logic and data fetching logic independently from views, and they can be called from
different places like from Controller action methods, from views, and from Razor Pages. They are
similar to partial views, but they can have their own logic, making them suitable for creating dynamic
content that requires processing.

View Components consist of two main parts: the class that handles processing and logic and the result
it returns, which is typically a view (rendered HTML). They are ideal for scenarios where you need to
display information that requires some business logic to fetch or generate the displayed data, such as
dynamic navigation menus, a shopping cart, or user profile summaries.

What Are All Files Available in a View Component in ASP.NET Core MVC?

A View Component typically consists of 2 files in ASP.NET Core MVC. They are as follows:

 Server-Side File (.cs file): Contains the logic to retrieve or prepare data.
 Client Side File (.cshtml file): Renders the output, similar to how a partial view works.
What Should be the Location for the Files of View Components in ASP.NET Core?

Server-Side file (.cs):

This file can be created anywhere in the project. But we generally create a new folder (with the name
Components, ViewComponents, or any other name as per your choice) at the root level of the project
and put all the view components in this folder.

Client-Side File (.cshtml):

The client-side file of a view component must be placed at a specific location.

49
 Location 1: If you want to call the View Component from the controller’s action method, then
you need to add the view component client-side file at the location- /Views/{Controller
Name}/Components/{View Component Name}/{View Name}
 Location 2: If you want to call the view component from the other cshtml file, then you need
to add the view component client-side file at the
location- /Views/Shared/Components/{View Component Name}/{View Name}
 Location 3: If you are using a view component in Razor pages, then you need to add the view
component client-side file at the location- /Pages/Shared/Components/{View Component
Name}/{View Name}
Note: The name for each View Component file is Default.cshtml. But you can also have other names
for your vView Component client-side file. But the recommended one is Default.cshtml

Example to Understand View Component in ASP.NET Core MVC Web Application

We want to display the top-selling products on the web page using the View Component. Let us see
the step-by-step process to implement this using the View Component. First, create a new ASP.NET
Core Web Application using the Model-View-Controller Project template with the
name ViewComponentInMVC.

Product Model:

Create a class file named Product.cs within the Models folder, and then copy and paste the following
code. This is going to be our model, which will hold the product information.

namespace ViewComponentInMVC.Models

public class Product

public long ProductID { get; set; }

public string? Name { get; set; } = null!;

public string Category { get; set; } = null!;

public string Description { get; set; } = null!;

public decimal Price { get; set; }

}
ProductRepository File:

Create a Class file named ProductRepository.cs within the Models folder, and then copy and paste
the following code. The code for getting the top-selling products from the database is written in the
ProductRepository.cs file. You will get the data from the database in real time, but here, we have hard-
coded it.

namespace ViewComponentInMVC.Models

public class ProductRepository

public async Task<List<Product>> GetTopProductsAsync(int count)

IEnumerable<Product> products = new List<Product>()

new Product { ProductID =1, Name ="Product 1", Category = "Category 1", Description ="Description

1", Price = 10m},

50
new Product { ProductID =2, Name ="Product 2", Category = "Category 1", Description ="Description

2", Price = 20m},

new Product { ProductID =3, Name ="Product 3", Category = "Category 1", Description ="Description

3", Price = 30m},

new Product { ProductID =4, Name ="Product 4", Category = "Category 2", Description ="Description

4", Price = 40m},

new Product { ProductID =5, Name ="Product 5", Category = "Category 2", Description ="Description

5", Price = 50m},

new Product { ProductID =6, Name ="Product 6", Category = "Category 2", Description ="Description

6", Price = 50m}

};

//We are Delaying the Execution for 1 Seconds to get the Data from the database

await Task.Delay(TimeSpan.FromSeconds(1));

return products.Take(count).ToList();

}
View Component Server-Side File in ASP.NET Core MVC:

Now, we need to create the View Component server-side file. In the project, we can add the server-
side file at any location (let’s say within the ViewComponents folder). So, in the project root
directory, create a folder named ViewComponents. Suppose the name of the View Component
server-side file is TopProducts; then, we must add a suffix ViewComponent to its name. Hence, the
final name of the View Component server-side file will be TopProductsViewComponent.

Creating TopProductsViewComponent

A View Component is a class that derives from a ViewComponent class and implements the Invoke or
InvokeAsync method. The Invoke method is synchronous, while InvokeAsync is asynchronous. It
contains the logic to generate the content. The Invoke or InvokeAsync method can return a view
(HTML) using the View method, similar to how actions in controllers work. The Invoke or InvokeAsync
method is the entry point for the View Component. This method contains the logic to generate the
data and select a view to render it.

So, create a class file named TopProductsViewComponent.cs within the ViewComponents folder
and copy and paste the following code. The code is self-explained, so please read the comment line for
a better understanding. Here, we are using the InvokeAsync method for better performance and
scalability.

using Microsoft.AspNetCore.Mvc;

using ViewComponentInMVC.Models;

namespace ViewComponentInMVC.ViewComponents

//Create a Class, and it should inherit from ViewComponent class

public class TopProductsViewComponent : ViewComponent

//The Invoke method for the View component

public async Task<IViewComponentResult> InvokeAsync(int count)

51
// Your logic for preparing data

ProductRepository productRepository = new ProductRepository();

var products = await productRepository.GetTopProductsAsync(count);

return View(products);

//public IViewComponentResult Invoke(int count)

//{

// // Your logic for preparing data

// ProductRepository productRepository = new ProductRepository();

// var products = productRepository.GetTopProductsAsync(count).Result;

// return View(products);

//}

}
Here:


TopProductsViewComponent: The TopProductsViewComponent class inherits from the
ViewComponent class, making it a View Component. This inheritance enables the class to
execute logic and return a view for rendering.
 InvokeAsync Method: The InvokeAsync method is the entry point for the View Component.
It is called when the component is invoked from a Razor view. The method is asynchronous,
allowing for non-blocking I/O operations, such as database calls. It accepts an integer
parameter count, which specifies the number of top-selling products to retrieve.
 return View(products);: The InvokeAsync method returns a view for rendering by calling
the View method. The View method looks for a Razor view that matches the View Component’s
name in the Views/Shared/Components/TopProducts folder by default. The products
model, which is a collection of top-selling products, will be passed to the view. This model can
then be used within the view to render HTML content.
View Component Client-Side File in ASP.NET Core MVC:

We are using the ASP.NET Core MVC Application and want to invoke the View Component from a view
file. Hence, we need to place the client-side file at the
location /Views/Shared/Components/{ViewComponentName}/{ViewName}.cshtml. In our
example, the View Component Name is TopProducts, and the view name is going to
be Default.cshtml. So, we need to create the View in the
location: /Views/Shared/Components/TopProducts/Default.cshtml

Once you create the Default.cshtml view file, your Views folder should look as shown below.

Now, open Default.cshtml view file and then copy and paste the following code into it. Here, you can
see that IEnumerable<Product> is going to be the model, and using a loop, we are rendering the
top-selling products.

52
@model IEnumerable<Product>

<div class="row">

<div>

<h4>Product Details</h4>

<table class="table">

<tr>

<th>

ProductID

</th>

<th>

Name

</th>

<th>

Category

</th>

<th>

Description

</th>

<th>

Price

</th>

</tr>

@foreach (var product in Model)

<tr>

<td>

@product?.ProductID

</td>

<td>

@product?.Name

</td>

<td>

@product?.Category

</td>

<td>

@product?.Description

</td>

<td>

@product?.Price

</td>

</tr>

53
}

</table>

</div>

</div>
With this, our view component is completed and ready to use.

How Do We Invoke a View Component from a View File in ASP.NET Core MVC?

We can invoke a View Component from a view using the Component.InvokeAsync HTML Helper
method, passing the name of the component and any necessary parameters. View components do not
use model binding, so you need to pass any required data explicitly using an anonymous object. So,
we can invoke the View Component from a view file by using the following syntax:

@await Component.InvokeAsync(“Name of View Component”, {Anonymous Type


Containing Parameters});

How Do We Invoke a View Component from a View File Using Tag Helper ASP.NET Core
MVC?

View components can also be invoked using HTML Tag Helper on any view (cshtml) file using the
following syntax.

<vc:[view-component-name]
parameter1=”parameter1 value”
parameter2=”parameter2 value”>
</vc:[view-component-name]>

Invoking the TopProducts View Component in ASP.NET Core MVC View:

Now, we need to invoke the TopProducts View Component from another view file. So, modify
the Index.cshtml file of Home Controller as follows. Here, TopProducts is the name of the View
Component, and we are creating an anonymous object with a count property with a value of 3. You
can assign any value to the count parameter. If you check the View Component CS class file, you will
see the InvokeAsync or Invoke method taking one integer parameter named count, and here, we pass
a value 3 to that count parameter.

@{

ViewData["Title"] = "Home Page";

<div class="text-center">

@await Component.InvokeAsync("TopProducts", new { count = 3})

</div>
With the above changes in place, run the application, access the Home/Index URL and you should get
the following output.

54
Invoke a View Component From a View File Using HTML Tag Helper in ASP.NET Core MVC:

Please update the ViewImport file as follows to include the required tag helpers. Here,
ViewComponentInMVC is the project name.

@using ViewComponentInMVC

@using ViewComponentInMVC.Models

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@addTagHelper *, ViewComponentInMVC

@addTagHelper *, ViewComponentInMVC.TagHelpers
Now, if you want to invoke the View Component using Tag Helper, then modify the Index.cshtml file
of the Home controller as follows:

@{

ViewData["Title"] = "Home Page";

<div class="text-center">

<vc:top-products count="3"></vc:top-products>

</div>
View Components Real-Time Examples in ASP.NET Core MVC:

To avoid code duplication in ASP.NET Core MVC Web Applications, the View Components can be used
in various areas such as the Navigation Menus, Login Panel, Billing and Shipping Address, Shopping
Cart, etc. View components can be used to create the following features:

Login Panel.
Dynamic Navigation Menu (Based on role etc.).
Get some related data for a page. (Like Related posts, Related books).
Shopping Cart.
Shipping and Billing Address.
Any content visible on the side of the Web Page, etc.
View Component vs. Partial View in ASP.NET Core MVC

In ASP.NET Core MVC, View Components and Partial Views create reusable components, allowing
developers to avoid duplicating markup across different views. However, they serve different purposes
and come with their own features, making them suitable for different scenarios.

View Component in ASP.NET Core MVC

View Components are intended for more complex scenarios where you need to execute some logic
before rendering the HTML. They are a combination of a C# class that handles the logic and a Razor

55
view that generates the HTML markup. View Components are not part of the MVC request life cycle,
which means they cannot directly respond to HTTP requests. Instead, they are invoked from within a
view and can be used to render a portion of a page with its own logic. So, View Components are for
dynamic content such as dynamic navigation menus, a shopping cart, or user profile summaries.

Partial View in ASP.NET Core MVC

Partial Views, on the other hand, are more straightforward. Unlike View Components, Partial Views do
not have their own logic. They depend on the data provided to them by the view that renders them,
typically through model binding or ViewData/ViewBag. Partial views are best for HTML generation
without additional processing or data fetching. So, they are best for static content that is going to be
reused on multiple pages, such as headers, footers, or reusable forms.

Razor Syntax in ASP.NET Core

In this article, I will discuss Razor Syntax in ASP.NET Core MVC Web Application with Examples.
Please read our previous article discussing View Components in ASP.NET Core MVC.

What is Razor Markup?

Razor Markup refers to the syntax used in Razor view templates in ASP.NET web applications to
combine server-side code with HTML markup. Razor Markup allows developers to embed C# code
directly within HTML, making generating dynamic and data-driven content for web pages easier. The
Razor Markup syntax is designed to be concise, readable, and intuitive, enabling seamless integration
of code and markup.

The Controller in ASP.NET Core MVC invokes the View by passing the data to render. The Views must
be able to process the data and generate a response. This is done using the Razor markup, which
allows us to use C# code in an HTML file. The Razor View Engine processes these markups to generate
the HTML.

Example to Understand Razor Syntax in ASP.NET Core MVC:

First, create a new ASP.NET Core Web Application using the Model-View-Controller Project template
with the name RazorSyntaxDemo. Then, create a class file with the name Product.cs within the
Models folder and copy and paste the following code.

namespace RazorSyntaxDemo.Models

public class Product

public long ProductID { get; set; }

public string? Name { get; set; } = null!;

public string Category { get; set; } = null!;

public string Description { get; set; } = null!;

public decimal Price { get; set; }

}
Razor Syntax in ASP.NET Core MVC:

The Razor uses the @ symbol to switch from HTML markup to the C# code. The following are the two
ways by which you can achieve the transitions.

1. Using Razor code expressions


2. Using Razor code blocks.
These expressions are evaluated by the Razor View Engine and written to the response.

56
Razor Code Block Syntax in ASP.NET Core MVC:

The Razor code blocks start with the @ symbol, followed by curly braces. You can use code blocks
anywhere in the markup. A Razor code block can be used to manipulate a model, declare variables,
set local properties on a view, etc. However, it would be best if you did not use it for business
logic. Now, open the index.cshtml file of Home Controller and copy and paste the following code into
it.

<h3>Code Block</h3>

@{

var greeting = "Welcome to ASP.NET Core MVC!";

var weekDay = DateTime.Now.DayOfWeek;

ViewData["Title"] = "Home Page";

@{

var product = new RazorSyntaxDemo.Models.Product()

ProductID = 1000,

Name = "Laptop",

Description= "Its a Gaming Laptop",

Category = "Electronics",

Price = 10000

};

}
First, we have created a Razor code block beginning with a @ symbol and { } curly brackets. Inside
the Curly brackets, we have regular C# code, which declares greeting and weekDay Variables as well
as a ViewData to hold the Title property. The Second Razor Code block creates a product variable,
which is a new instance of the Product model class.

Razor Code Expression Syntax in ASP.NET Core MVC

The Razor Code expressions start with @ and are followed by C# code. The Code expression can be
either Implicit or Explicit.

Implicit Razor Expressions

Implicit Razor expressions start with @ followed by C# code. In the below example, the codes
@greeting, @DateTime.Now, and @WeekDay are treated as Implicit Razor expressions. Space is not
allowed in the Code expression, as it is used to identify the end of the expression. The Razor View
engine evaluates the expressions, and the result is inserted in their place.

<h3>Code Block</h3>

@{

var greeting = "Welcome to ASP.NET Core MVC!";

var weekDay = DateTime.Now.DayOfWeek;

ViewData["Title"] = "Home Page";

@{

var product = new RazorSyntaxDemo.Models.Product()

57
{

ProductID = 1000,

Name = "Laptop",

Description= "Its a Gaming Laptop",

Category = "Electronics",

Price = 10000

};

<h3>Code Expression</h3>

<p>@greeting</p>

<p>@DateTime.Now</p>

<p>Today is : @weekDay thank you </p>

<p>Name : @product.Name</p>

<p>Description : @product.Description</p>

<p>Price : @product.Price</p>
Now, run the application, and you should see the following output.

Explicit Razor Expressions

Explicit Razor expressions start with @ followed by (). Any content within the () parenthesis is
evaluated and rendered to the output.

<h3>Code Block</h3>

@{

var greeting = "Welcome to ASP.NET Core MVC!";

var weekDay = DateTime.Now.DayOfWeek;

ViewData["Title"] = "Home Page";

@{

var product = new RazorSyntaxDemo.Models.Product()

ProductID = 1000,

58
Name = "Laptop",

Description= "Its a Gaming Laptop",

Category = "Electronics",

Price = 10000

};

<h3>Code Expression</h3>

<p>@(greeting)</p>

<p>@(DateTime.Now)</p>

<p>Today is : @(weekDay) thank you </p>

<p>Name : @(product.Name)</p>

<p>Description : @(product.Description)</p>

<p>Price : @(product.Price)</p>
Now, run the application, and you should see the following output.

IntelliSense Support in Razor Syntax

The image below shows how the Razor markup is used inside an HTML page and the Intelligence
support from Visual Studio.

Using Directive

59
The @using directive works similarly to the C# using directive and allows you to import namespaces
and the RazorSyntaxDemo.Models can be imported as shown below. Here, you don’t need to need the
statement with a semicolon.

@using RazorSyntaxDemo.Models

And then, we can use var product = new Product() instead of var product = new
RazorSyntaxDemo.Models.Product() as follows:

@using RazorSyntaxDemo.Models

<h3>Code Block</h3>

@{

var greeting = "Welcome to ASP.NET Core MVC!";

var weekDay = DateTime.Now.DayOfWeek;

ViewData["Title"] = "Home Page";

@{

var product = new Product()

ProductID = 1000,

Name = "Laptop",

Description= "Its a Gaming Laptop",

Category = "Electronics",

Price = 10000

};

}
Variable Declaration using Razor Syntax in ASP.NET Core MVC

The Variables are declared using the var keyword or using the C# data type. The int, float, decimal,
bool, DateTime & string keywords can be used to store strings, numbers, dates, etc. The variables are
inserted directly into a page using @.

<h3>Variables </h3>

<!-- Storing a string -->

@{

string message = "Welcome to ASP.NET Core MVC";

<!—Storing date and integer-->

@{

DateTime date = DateTime.Now;

int Number = 100;

<p>@message</p>

<p> The current date is @date</p>

<p>Numbers : @Number</p>
Now, run the application, and you should see the following output.

60
Strings are enclosed in double quotation marks. To use a double quotation mark inside the string, use
a verbatim string literal. The verbatim string is prefixed with the @ symbol and repeats the quotation
mark.

@{

var helloWorld = @"Hello ""World""";

<p>@helloWorld</p>
Similarly, backslash characters can be printed using the same technique.

@{

var Path = @"C:\Windows\";

<p>The path is: @Path</p>


You can print @ in HTML by repeating (Escape) the @ symbol as shown below.

@{

var symbol = "You can print @ in html";

<p>The @@symbol is: @symbol</p>


So, modify the Index view as follows:

@{

var helloWorld = @"Hello ""World""";

<p>@helloWorld</p>

@{

var Path = @"C:\Windows\";

<p>The path is: @Path</p>

@{

var symbol = "You can print @ in html";

<p>The @@symbol is: @symbol</p>


Now, run the application, and you should see the following output.

61
Comments

Use @* *@ to place comments

@*This is comment*@

HTML Elements inside the code block

The Razor Engine Correctly Identifies any HTML Elements inside the Razor code block, as shown below.

@{

<p>Hello from the Code block</p>

}
Single line text

You can output the literal values without the HTML element by prefixing it with @: and @: used to
define the single line of literal values.

@{

@:Hello from the Code block

}
Multiline text

For the multiline text use the <text> </text> element

@{

<text>

Multiline text 1

Multiline text 2

Multiline text 3

</text>

}
Conditional Statements

The Razor engine is able to process conditional statements like if and Switch statements.

If and Else Conditions

If Condition is used to render a section based on a condition as shown below.

62
@{

int value = 200;

@if (value > 100)

<p>Value is greater than 100</p>

else

<p>Value is less than 100</p>

}
Or you can use the following code.

@{

var value = 200;

if (value > 100)

<p>The value is greater than 100</p>

else

<p>This value is less than 100</p>

}
Switch Statements in Razor View

A switch statement can insert a section into HTML based on a number of conditions.

@{

var value = 200;

@switch (value)

case 0:

@: value is Zero

break;

case 100:

<p>Value is 100 </p>

break;

case 200:

<p>Value is @value </p>

break;

63
case 300:

<text>Value is 300</text>

break;

default:

<p>Invalid Value </p>

break;

}
Loops

For loop

The loops are used to repeat a code block for,

@for (int i = 0; i < 5; i++)

<span> @i </span>

}
Foreach loop

The best use case of a for-each loop is to loop through a collection object and display the result inside
a table.

@using RazorSyntaxDemo.Models

@{

var productList = new List<Product>()

new Product() { ProductID = 1001, Name = "Laptop", Price = 1000 },

new Product() { ProductID = 1002, Name = "Desktop", Price = 2000 },

new Product() { ProductID = 1002, Name = "Mobile", Price = 3000 }

};

<table>

<thead>

<tr><td>ProductID</td><td>Name</td><td>Price</td></tr>

</thead>

@foreach (Product product in productList)

<tr>

<td>@product.ProductID</td>

<td>@product.Name</td>

<td>@product.Price</td>

</tr>

</table>

64
While loop:

<h3>While loop</h3>

@{

var r = 0;

while (r < 5)

r += 1;

<span> @r</span>

}
In the next article, I am going to discuss How to Install Bootstrap in ASP.NET Core
MVC Application. In this article, I explained Razor Syntax in the ASP.NET Core MVC Application. I hope
you enjoy this Razor Syntax in ASP.NET Core MVC article.

How to Install Bootstrap in ASP.NET Core MVC Application

In this article, I am going to discuss How to Install Bootstrap in ASP.NET Core MVC Web
Application. Our previous article discusses Razor View Engine and Razor Syntax in ASP.NET Core
MVC Web Applications. As part of this article, I am going to discuss the following pointers.

1. Different Tools to Install Client-Side Packages in ASP.NET Core.


2. What is Library Manager or Libman in ASP.NET Core?
3. How to Check and Upgrade the Version in Visual Studio?
4. How to Install Bootstrap in ASP.NET Core Using Library Manager?
5. What is the libman.json file in ASP.NET Core?
6. How to Clean and Restore Client-Side Libraries Using Libman in ASP.NET Core?
7.How to Uninstall or Update a Client-Side Library using the libman.json file?
Different Tools to Install Client-Side Packages in ASP.NET Core:

You can use many tools to install client-side packages, such as jQuery and Bootstrap, using Visual
Studio. Some of the popular tools are as follows:

1. Bower
2. NPM
3. WebPack, etc.
But, here in this article, I will not use any of the above tools; instead, we will use Library Manager,
known as LibMan, to install the client-side packages in ASP.NET Core MVC Application. In our upcoming
article, I will show you how to install the client-side packages using Bower, NPM, and WebPack.

What is Library Manager or Libman in ASP.NET Core?

The Library Manager or LibMan is one of the most popular lightweight, client-side library manager
tools. This tool is used to download client-side libraries and frameworks such as Bootstrap and jQuery
from a file system or a CDN (Content Delivery Network). In order to use Library Manager, you should
have Visual Studio 2017 version 15.8 or later.

How to Check and Upgrade the Version in Visual Studio?

In order to check the Visual Studio Version, you need to follow the below steps.

Click on the “Help” menu and then select the “About Microsoft Visual Studio” option from the
context menu. This will open the “About Microsoft Visual Studio” Window, which shows the version

65
number of Visual Studio in the image below. I have installed Visual Studio 2022 on my machine with
Version 17.6.4.

Advertisements

How to Install Bootstrap in ASP.NET Core Using Library Manager?

You must follow the steps below to install Bootstrap in ASP.NET Core MVC Application using the Library
Manager (Libman).

1. Right-click on the “Project Name” in the Solution Explorer and then select Add > Client-
Side Library, which will open the “Add Client-Side Library” Window.
2. Leave the default provider as it is, which “cdnjs” is in this case. The other providers
are filesystem, jsdelivr, and unpkg.
3. In the “Library” text box, type “twitter-bootstrap“. You can also get intelligence support
once you start typing. Once you select the matching entry, then it tries to install the latest
version of Bootstrap. However, if you want, you can manually type the version number. Here,
we are installing the latest version of Bootstrap, i.e. ([email protected]).
4. There are two radio buttons to select whether you to include “All library files” or “Choose
Specific files“. If you select the “All library files” radio button, all the files will be
downloaded. On the other hand, if you select the “Choose Specific files” radio button, then
you need to check the selected checkboxes as per your requirement. Here I am selecting the
“All library files” radio button.
5. In the “Target Location” text box, specify the folder location where you want the library files
to be installed. By default, the static files are only served from the wwwroot folder. I am going
with the default location, i.e., “wwwroot/lib/twitter-bootstrap/”.
6. Finally, click on the “Install” button, as shown in the image below.

Once it is successfully installed, then you will find two things. One is the libman.json file, and the
second one is the required bootstrap files. Please have a look at the following image.

66
What is the Libman.json file in ASP.NET Core MVC?

The libman.json file is the Library Manager manifest file. You will find the following code in the
libman.json file.

"version": "1.0",

"defaultProvider": "cdnjs",

"libraries": [

"library": "[email protected]",

"destination": "wwwroot/lib/twitter-bootstrap/"

}
As you can see in the above code, we have an entry for the Bootstrap library that we just installed
using Libman. It is also possible to install client-side libraries like Bootstrap and jQuery by editing the
above manifest file.

How to Clean Client-Side Libraries using LibMan in ASP.NET Core?

If you want to clean the library files created using the Library Manager, right-click on the libman.json
file and select the “Clean Client-Side Libraries” option from the context menu, as shown in the
below image.

67
Once you click on the “Clean Client-Side Libraries” option, then it will delete all the library files
from the respective destination folder. The point that you need to remember is that it will only delete
the files from the folder but not in the libman.json file. Please look at the following image and see the
Twitter-bootstrap folder; its files are deleted, but the libman.json file is still there.

How to Restore Client-Side Libraries using Libman in ASP.NET Core?

If you want to restore the deleted files, you need to right-click on the libman.json file and select the
“Restore Client-Side Libraries” option from the context menu, as shown in the image below.

Once you click on the “Restore Client-Side Libraries” option, it will again download and install the
required library files into the specified destination folder, as shown in the image below.

68
How to Add a Library using the libman.json file?

Now, we need to add the jQuery Library, but not using the way we add Bootstrap. So, basically, we
want to add the jQuery library using the libman.json file. To do so, modify the libman.json file as
follows.

"version": "1.0",

"defaultProvider": "cdnjs",

"libraries": [

"library": "[email protected]",

"destination": "wwwroot/lib/twitter-bootstrap/"

},

"provider": "cdnjs",

"library": "[email protected]",

"destination": "wwwroot/lib/jqueryui/"

}
Then right-click on the libman.json file and select the “Restore Client-Side Libraries” option from
the context menu, and it should add the respective jQuery library, as shown in the image below.

69
How to Uninstall or Update a Client-Side Library using Libman.json File in ASP.NET Core
MVC?

If you want to uninstall or update a client-side library using the libman.json file, then you need to
follow the below steps.

1. Open the libman.json file.


2. Click on the client-side library which you want to uninstall or update
3. A light bulb icon will appear on the left side
4. Click on the light bulb icon, and then you will see the options of whether to update or
uninstall that specific client-side library, as shown in the below image.

Another approach to uninstall a client-side library is to remove the entry from the libman.json file, and
upon saving the file, the respective client-side libraries are uninstalled from the respective folder
location. For example, if we modify the libman.json file as shown below, you will immediately see the
respective library being deleted from the wwwroot project folder.

"version": "1.0",

"defaultProvider": "cdnjs",

"libraries": [

"library": "[email protected]",

"destination": "wwwroot/lib/twitter-bootstrap/"

}
Now, you can check the lib folder, which is inside the wwwroot folder, and you should see that the
JqueryUI folder was deleted, as shown in the below image.

70
Another approach to upgrade or downgrade a client-side library is to change the version number
directly in the libman.json file, as shown in the below image. The respective client-side library will be
updated to the version you modified after saving the file. While updating the version number, you will
also get the visual studio intelligence shown in the image below.

In the next article, I am going to discuss How to Use Bootstrap in ASP.NET Core MVC Web
Applications. Here, in this article, I try to explain How to Install Bootstrap in ASP.NET Core
MVC Application. I hope you enjoy this How to Install Bootstrap in ASP.NET Core MVC article.

How to Use Bootstrap in ASP.NET Core MVC Application

In this article, I will discuss How to Use Bootstrap in ASP.NET Core MVC Web Applications. Please
read our previous article before proceeding to this article discussing How to Install Bootstrap in
ASP.NET Core MVC Application using Library Manager (LibMan). Here, I will discuss how to use
Bootstrap as well as how to create and use custom CSS in a view.

Creating a New ASP.NET Core MVC Application:

First, create a new ASP.NET Core MVC Application with the name FirstCoreMVCApplication using the
Model-View-Controller Project Template. Once you create the Project, add Bootstrap to your
application using the Library Manager (Libman). Our previous article discussed how to install BootStrap
into the ASP.NET Core MVC Application. So, you must follow the steps below to install Bootstrap on
your application.

1. Right-click on the “Project Name” in the Solution Explorer and then select Add > Client-
Side Library, which will open the “Add Client-Side Library” Window.
2. Leave the default provider as it is, which “cdnjs” is in this case. The other providers
are filesystem, jsdelivr, and unpkg.
3. In the “Library” text box, type “twitter-bootstrap“. You can also get intelligence support
once you start typing. Once you select the matching entry, it will try to install the latest
version of Bootstrap. However, if you want, you can manually type the version number. Here,
we are installing the latest version of Bootstrap, i.e. ([email protected]).
4. There are two radio buttons to select whether you to include “All library files” or “Choose
Specific files“. If you select the “All library files” radio button, all the files will be
downloaded. On the other hand, if you select the Choose Specific Files radio button, you
need to check the selected checkboxes as per your requirements. Here, I am selecting the “All
library files” radio button.
5. In the “Target Location” text box, specify the folder location where you want the library files
to be installed. By default, the static files are only served from the wwwroot folder. I am going
with the default location, i.e., “wwwroot/lib/twitter-bootstrap/”.
6. Finally, click on the “Install” button, as shown in the image below.

71
Once it is successfully installed, you will find two things: the libman.json file and the required bootstrap
files. Please have a look at the following image.

Creating a Custom Style Sheet in ASP.NET Core MVC Application:

First, create a folder with the name CSS within the wwwroot folder. As we are creating the ASP.NET
Core Application using the Model-View-Controller template, by default, the CSS folder should be inside
the wwwroot folder. All the custom CSS files are going to be created within this folder. Once you have
the CSS folder, let’s add a CSS file with the name MyCustomStyleSheet.css.

To create a style sheet, right-click on the CSS folder and then select “ Add – New Item” from the
context menu. Then, search for CSS and select Style Sheet, provide a meaningful name,
i.e., MyCustomStyleSheet.css, and finally click the Add button as shown in the image below.

72
Once you add the MyCustomStyleSheet.css file, then your wwwroot folder should look as shown
below.

Note: All the custom style sheets for our application need to be placed within
the MyCustomStyleSheet.css file. So, open the MyCustomStyleSheet.css file and copy and paste the
following code into it. We are going to use the custom .btn style sheet in our application.

.btn {

width: 80px;

}
How to Use Bootstrap in ASP.NET Core MVC Application?

To use Bootstrap, you first need to include a reference to the bootstrap.css file. You can add the
reference on each individual view. But as we are going to use the Layout file, we will add a reference
to the bootstrap.css file in the _Layout.css file. Along with bootstrap.css, we are also including a
reference to our custom style sheet, i.e., MyCustomStyleSheet.css.

Modifying _Layout.cshtm file:

Please modify the Layout.cshtml file, which is present in the shared folder, as shown below.

<!DOCTYPE html>

<html>

73
<head>

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

<link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />

<link href="~/css/MyCustomStyleSheet.css" rel="stylesheet" />

</head>

<body>

<div class="container">

@RenderBody()

</div>

</body>

</html>
As you can see in the HTML code, we have included references for
both bootstrap.css and MyCustomStyleSheet.css files. We also use the bootstrap container class
to position the elements on the page.

Creating Models:

Within the Models folder, add a class file with the name Student.cs and then copy and paste the
following code into it. As you can see, this is a very simple Student Model having only five properties
holding the Student ID, Name, Branch, Section, and Gender.

namespace FirstCoreMVCApplication.Models

public class Student

public int StudentId { get; set; }

public string? Name { get; set; }

public string? Branch { get; set; }

public string? Section { get; set; }

public string? Gender { get; set; }

}
Modifying the Home Controller:

Next, modify the Home Controller as shown below. As you can see in the code below, we have created
two action methods. 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 then returns that student information
to the view. Here, we have hard-coded the data, but in real time, you will get the data from a
database.

using FirstCoreMVCApplication.Models;

using Microsoft.AspNetCore.Mvc;

using System.Collections.Generic;

namespace FirstCoreMVCApplication.Controllers

public class HomeController : Controller

74
{

public ViewResult Index()

//Create a List of Students

//In Real-Time, you will get the data from the database

List<Student> listStudents = new List<Student>()

new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male"

},

new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male"

},

new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male"

},

new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female"

},

new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female"

};

//Pass the Student List to the View to make the view as a Strongly Typed View

return View(listStudents);

public ViewResult Details(int Id)

//Here, we have hard coded the student details

//In Real-Time, you will get the student information from the database

Student studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section =

"A", Gender = "Male" };

//Pass the Student model to the View to make the view as a Strongly Typed View

return View(studentDetails);

}
Modifying the Index View of the Home Controller:

Please modify the Index view, which is present inside the Home Controller, as shown below. As you
can see in the HTML below, we are using Bootstrap in-built classes like class=”table-responsive”,
class=”table”, class=”text-center” and class=”btn btn-primary.” Here, we are not going to explain the
Bootstrap class. Instead, I am only going to show you how to use Bootstrap in an ASP.NET Core MVC
Application.

@model List<FirstCoreMVCApplication.Models.Student>

@{

ViewBag.Title = "Student List";

Layout = "~/Views/Shared/_Layout.cshtml";

75
}

<div class="table-responsive">

<table class="table">

<thead>

<tr>

<th>ID</th>

<th>Name</th>

<th>View</th>

<th>Update</th>

<th>Delete</th>

</tr>

</thead>

<tbody>

@foreach (var student in Model)

<tr>

<td>@student.StudentId</td>

<td>@student.Name</td>

<td class="text-center"><a href="#" class="btn btn-primary">View</a></td>

<td class="text-center"><a href="#" class="btn btn-primary">Edit</a></td>

<td class="text-center"><a href="#" class="btn btn-danger">Delete</a></td>

</tr>

</tbody>

</table>

</div>
Creating Details View inside the Home Folder:

Next, create a view with the name Details.cshtml and copy and paste the following code. As you can
see in the below HTML, we are using Bootstrap in-built classes such as class=”row justify-content-
center m-3″, class=”col-sm-8″, lass=”card”, class=”card-header text-center”, class=”card-body text-
center”, lass=”card-footer text-center”, class=”btn btn-primary”, etc.

@model FirstCoreMVCApplication.Models.Student

@{

ViewBag.Title = "Student Details";

Layout = "~/Views/Shared/_Layout.cshtml";

<div class="row justify-content-center m-3">

<div class="col-sm-8">

<div class="card">

<div class="card-header text-center">

<h1>@Model?.Name</h1>

76
</div>

<div class="card-body text-center">

<h4>Studnet ID : @Model?.StudentId</h4>

<h4>Branch : @Model?.Branch</h4>

<h4>Section : @Model?.Section</h4>

<h4>Gender : @Model?.Gender</h4>

</div>

<div class="card-footer text-center">

<a href="#" class="btn btn-primary">Back</a>

<a href="#" class="btn btn-primary">Edit</a>

<a href="#" class="btn btn-danger">Delete</a>

</div>

</div>

</div>

</div>
That’s it. Save the changes, run the application, and then visit the Home/Index or the root URL, and
you should get the following output.

Next, visit Home/Details/10 to get the following output.

We have just created the View, Update, Delete, and Back buttons but have not implemented them. In
our upcoming articles, I will show you how to implement the CRUD operation in ASP.NET Core MVC
Application.

77
In the next article, I will discuss the Action Results in ASP.NET Core MVC Web Applications. In this
article, I explain How to Use Bootstrap in ASP.NET Core MVC Applications. I hope you enjoy this
How to Use Bootstrap in ASP.NET Core MVC Web Applications article.

78

You might also like