Unit-3 Net Core Framework
Unit-3 Net Core Framework
Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR
Let’s say we have an ASP.NET Core MVC application with two controllers,
i.e., HomeController and StudentController. The HomeController is created
with the following three action methods.
1. AboutUs()
2. ContactUs()
3. Index()
As you can see in the above image, a separate folder is created for each
controller within the Views Folder.
The Home folder represents the HomeController, and the Student folder
represents the Student Controller.
The Home folder contains the views for the Index, AboutUs, and
ContactUs webpages. Whenever a user requests one of these web
pages, the Home Controller action method determines which of the
above three views to use to build the webpage and return it to the
user.
Similarly, the Student folder contains the Index, Details, Edit, and
Delete web page views. So, whenever a user requests any of these
web pages, the Student Controller action method determines which
of the above views to use to build the webpage and return to the user.
Open HomeController and then copy and paste the following code into it.
As you can see in the above HomeController class, we have only one action
method, Index. The return type of the Index() action method is ViewResult,
which means it will return a view. To return a view, we use
the View() extension method, which belongs to the Controller Base Class.
Now run the application and navigate to the “/Home/Index” URL or the
default URL, and you will see the following error.
Why Did We Get the Above Invalid Operation Exception?
Let us understand why we got the above exception. As we return a view
from the Index action method of Home Controller, by default, the ASP.NET
Core MVC Framework will look for a file with the name Index.cshtml in the
following three locations.
1. First, it will look for the “Index.cshtml” file within the
“/Views/Home” folder, as the action method belongs to the Home
Controller.
2. Then it will look for the “Index.cshtml” file in the “/Views/Shared/”
folder.
3. Then it will look for the “Index.cshtml” file in the “/Pages/Shared/”
folder.
If the requested “.cshtml” file is found in any of the above folders, the View
generates the HTML and sends it back to the client who initially made the
request. On the other hand, if the requested file is not found in any of the
above locations, we will get the above error.
As we already discussed, the Action Views will be created inside the folder
whose name is the same as the Controller’s name. We want to create a view
for the Index action method of the Home Controller. So, let us first add
the Home folder inside the View folder. To do so, right-click on
the Views folder and then select the Add => New Folder option to add a
new folder. Then, rename the folder Home.
Once you have created the Home folder, then we need to create a view
within this Home folder. In ASP.NET Core MVC, we can add views in many
different ways, and we will discuss them one by one.
So, right-click on the Home folder and then select the Add => View option,
which will open the Add View window, as shown in the image below. You
need to select the Razor View and click the Add button, as shown in the
image below.
Once you click the Add button, it will open the Add Razor View window.
Here, you need to give the View name as Index, select the Empty (without
model) template, uncheck the creation of a partial view, use a layout page
checkbox, and then click on the Add button as shown below.
Once you click the Add button, the Index.cshtml view should be created
within the Home folder, as shown in the image below.
Now open Index.cshtml file and then copy and paste the following code
into it.
With the above changes in place, run the application, and you should get
the expected output, as shown in the image below.
For example, in the code below, we are using the View() extension method,
which does not take any parameter to return a view from the Index action
method of the Home Controller. So, by default, the ASP.NET Core MVC
framework will look for a view with the name Index.cshtml within the
“Views/Home” folder.
Note: When using the absolute path, the .cshtml extension is mandatory.
When using an absolute path to reach the project’s root directory, you can
use / or ~/. You can also use any of the following, which will do the same
thing.
Now, right-click anywhere within the About action method and click on the
Add View from the context menu, as shown in the image below.
Once you click on the Add View, it will open the Add New Scaffolded Item
window, as shown below. In this window, you need to select the Razor
View and click the Add button, as shown in the image below.
Once you click on the Add button, the Add Razor View window will open.
By default, the View will be named About (action method name). Finally,
click the Add button, as shown in the image below.
Once you click the Add button, it will add the About.cshtml file within the
View/Home folder, as shown in the below image.
Program.cs:
In the Program class, we need to do two things. First, we need to configure
the required MVC service to the IoC Container, and then we need to add the
MVC Middleware to the request processing pipeline. So, modify the
Program class as shown below.
Without Dependency Injection:
Create a folder named Controllers in your project. Then, add a class file
named HomeController.cs within the Controllers folder and copy-paste
the following code. Here, you can see that within the Index and
GetStudentDetails action methods, we are creating an instance of the
StudentRepository class and calling the respective methods.
With the above changes in place, now run the application and check the
above two methods. it should work as expected, as shown in the image
below.
Let’s first understand the problem in the above implementation. Then, we
will discuss how to overcome it by using the Dependency Injection Design
Pattern in the ASP.NET Core application.
Singleton:
Services registered as Singleton are instantiated once per application and
shared throughout its lifetime. It is Ideal for configuration services, logging,
or other services where a single instance is sufficient and expensive to
create. All requests for the service within the application receive the same
instance. The container ensures thread safety when accessing the singleton
instance. Exists for the entire duration of the application. This can be
achieved by adding the service as a singleton through the AddSingleton
method of the IServiceCollection.
Transient:
Services registered as Transient are created each time they are requested.
This method is suitable for lightweight, stateless services with short-lived
and transient behavior. A new instance is created every time the service is
requested, and instances are not shared among different consumers. This
can be achieved by adding the service through the AddTransient method of
the IServiceCollection.
Scoped:
Services registered as Scoped are created once per request (in a web
application, this typically means per HTTP request). It is used for services
that should be reused within a single request, maintaining state across
different components of the request, but should not be shared across
different requests. Instances are disposed of at the end of the request.
Common examples include data access operations within a single
transaction. This can be achieved by adding the service through the
AddScoped method of the IServiceCollection.
Registering the StudentRepository with ASP.NET Core Dependency
Injection
We need to register the service to the built-in dependency injection
container with the program class. The following code shows how to
register a service with different lifetimes:
Code Explanation:
In the above example, the IoC container will automatically inject an
instance of the StudentRepository into the constructor of HomeController.
We don’t need to do anything else. The IoC container will create and
dispose of an instance of the IStudentRepository based on the registered
lifetime. Injecting the dependency object through a constructor is called a
constructor dependency injection.
Run the application, and you will get the expected output, as shown below.
What is the FromServices in ASP.NET Core Dependency Injection?
The [FromServices] attribute in ASP.NET Core explicitly indicates that a
parameter of an action method should be resolved from the Dependency
Injection (DI) container. This attribute is useful when we need to inject
services directly into action methods instead of through the constructor.
When you decorate a parameter in an action method with the
[FromServices] attribute, ASP.NET Core’s dependency injection system will
resolve and inject the specified service directly into the action method.
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:
If you don’t have a layout view for your website, then you need to repeat
the required HTML for the above-mentioned sections in each and every
view of your application. This violates the DRY (Don’t Repeat
Yourself) principle as we are repeating the same code in multiple views.
As a result, it isn’t easy to maintain the application code. For example,
suppose we have to remove or add a menu item from the list of navigation
menus or even if we want to change the header or footer of our website. In
that case, we need to do this in every view, which is tedious, time-
consuming, and error-prone.
Instead of putting all the sections (i.e., the HTML) in every view page, it is
always better and advisable to put them in a layout view and then inherit
that layout view in every view where we want that look and feel. With the
help of layout views, it is now easier to maintain our application’s
consistent look and feel. This is because if we need to make any changes,
we need to do it only in one place, i.e., in the layout view, and the changes
will be reflected immediately across all the views inherited from the layout
view.
How Do We Create a Layout View in ASP.NET Core MVC Application?
First, create a new ASP.NET Core Application
named FirstCoreMVCApplication using the Model-View-Controller
Template. Next, follow the steps below to create a layout view in ASP.NET
Core MVC.
1. The layout view is usually placed in the Views/Shared folder and
named _Layout.cshtml by convention. Right-click on the “Views”
folder and then add a new folder named “Shared” if not already
added. If you are creating the ASP.NET Core Web Application using
Model-View-Controller, the Shared folder will be there with
the _Layout.cshtml file by default.
2. Next, Right-click on the “Shared” folder and select the “Add” – “New
Item” option from the context menu. This will open the Add New
Item window.
3. From the “Add New Item” window, search for Layout and then
select “Razor Layout“, give your layout view a meaningful name
(_Layout.cshtml), and finally, click on the “Add” button, as shown
below. This should add the _Layout.cshtml file to the Shared folder.
So, once you add the _Layout.cshtml file, your Views folder should look as
shown below.
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.
Index.cshtml:
Please modify the Index.cshtml view as shown below to use the layout
view. Here, we are setting the Page Title using the ViewBag.Title property,
i.e., ViewBag.Title = “Home Page”; and we are also setting the Layout for
our view as Layout = “~/Views/Shared/_Layout.cshtml”;
Details.cshtml:
Please create the Details.cshtml view within the Views/Home folder and
then copy and paste the following code to use the layout view. Here, we are
setting the Page Title using the ViewBag.Title property, i.e., ViewBag.Title
= “Details Page”; and we are also setting the Layout for our view
as Layout = “~/Views/Shared/_Layout.cshtml”;
Now run the application and navigate to the Home/Index URL, which
should display the page below.
Next, navigate to the Home/Details URL, which should display the page
below.
If you compare both pages, you will see that only the Page Title and Main
Content area are changed; the rest, like the Footer, Menus, and Header, will
be the same. Here, we are not repeating the HTML code in both the Index
and Details View; rather, we are using the Layout view, which contains the
common HTML Elements.
In general, all the static files of our ASP.NET Core MVC Application need to
be placed within this wwwroot folder. Once you have created the
“wwwroot” folder, create a subfolder within it with the name “js” if it is not
already there, and then add a Javascript file with the
name “CustomJavascript.js” within the js folder.
To do so, right-click on the js folder and select Add => New Item from the
context menu, which will open the Add New Item window. Here, search
javascript, select Javascript File, give the file name CustomJavascript.js,
and finally click the Add button, as shown in the image below.
Once you add the CustomJavascript.js file, your wwwroot folder should
look as shown in the image below.
Situation 1:
If we have a custom Javascript file (e.g., CustomJavascript.js) and all the
views of our application require that file, we need to place that file in the
Layout View of our application. Let us add that CustomJavascript.js file
within our _Layout.cshtml file. So, modify the _Layout.cshtml file as
follows.
Note: Putting all the script files before the closing body tag is always a good
programming practice.
Situation 2:
Suppose we have a custom Javascript file (e.g., CustomJavascript.js), and we
want this file to be used in some specific views. Let’s assume we want this
file in the Index view but not in the Details view of the Home Controller. In
such scenarios, we can use the Layout Section in ASP.NET Core MVC
Applications.
To use Section in ASP.NET Core MVC Layout Views, we are provided with
the RenderSection and RenderSectionAsync methods. Let us look at the
signatures of the RenderSection and RenderSectionAsync methods, shown
below.
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.
But, when you navigate the Home/Details URL, you will get the following
error page.
The reason for getting the above exception is the section is mandatory, and
we have not specified the section content in the Details view. To verify this,
go to the definition of the RenderSection(“Scripts”) method, which takes
the string file name as a parameter, and you will see the following.
As you can see, this method takes only the name parameter, and internally,
it sets the required parameter value to true, making it mandatory to
include the section in the child view. And in the Details view, we have not
included any section.
With the above changes in place, run the application and navigate to both
URLs. You should get the expected output.
With the above changes in place, run the application and navigate to both
URLs. You should get the expected output.
ViewStart in ASP.NET Core MVC Application
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.
From the New Item window, search for Razor and then select the Razor
View Start template, provide the name as _ViewStart.cshtml, and click on
the Add button as shown in the below image, which should create
the _ViewStart.cshtml file within the Views folder of your project.
If you are creating the ASP.NET Core Application using the Model-View-
Controller Project template, then by default, the _ViewStart.cshtml file is
added within the Views folder, as shown in the image below.
How to Set the Layout Property in _ViewStart.cshtml file in ASP.NET
Core MVC Application?
Once the _ViewStart.cshtml file is created, modify it as shown below to set
the Layout property. Here, you can see that we are specifying the layout
file path using the Layout property. Layout files are typically in
the Views/Shared folder and have the .cshtml file extension.
With the above changes in place, run the application and navigate
to Home/Index and Home/Details. It should display the output as
expected.
The _ViewStart.cshtml file can be placed in the Views root directory or any
subdirectory under Views. ASP.NET Core MVC applications search for the
_ViewStart.cshtml file using a top-down approach, starting from the
specific view’s directory to the root of the Views directory.
Let us understand this with an example. First, create another layout file
named _MyLayout.cshtml within the Shared folder. To do so, right-click on
the Shared folder and then select Add => New Item from the context menu,
which will open the following Add New Item window. Here, search
for Layout and then select Razor Layout template, give the view name
as _MyLayout.cshtml, and finally click on the Add button as shown below
image, which should add _MyLayout.cshtml file within the Shared folder.
Once you create the _MyLayout.cshtml file, copy and paste the following
code.
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.
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.
Now, run the application and navigate to Home/Details. You should get
the following output, which means the Details view now uses the Layout,
which is specified in the Details view only.
Now, if you don’t want to use any layout or want to render a view without a
layout, then you need to set the Layout property to null. For example, if you
don’t want to use a Layout in Details View, you need to modify
the Details.cshtml view as follows.
Now, run the application and navigate to the Home/Details URL. You
should see the output without using any layout page.
When you work with a Real-Time ASP.NET Core MVC application, you may
have multiple layout views. Let’s say we have two Layouts, such
as _NonAdminLayout and _AdminLayout. If you want to select the layout
based on the user role, i.e., if the user role is Admin, then
use _AdminLayout; otherwise, use the _NonAdminLayout. Then, you need
to write the following conditional logic within the _ViewStart.cshtml file,
which will select the layout based on the logged-in user’s role.
Real-Time Example: Setting Up a Default Layout and Initializing ViewData
Let’s assume we are developing a content management system (CMS) for a
small news website. We want to ensure that all views use a consistent
layout called _Layout.cshtml. Additionally, we want to initialize some
ViewData properties that should be available across all views, such as the
title suffix and a generic message.
Configure _ViewStart.cshtml
Now, we need to set up the _ViewStart.cshtml file to specify that
_Layout.cshtml should be the default layout for all views. We also initialize
ViewData with a default title, header, and application name that will be
consistent across the website. We have already created
the _ViewStart.cshtml file within the Views folder, so modify the file as
follows:
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 _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
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.
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.
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
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.
Partial Views are similar to regular views, but they do not run on their own;
they must be embedded within other views. This makes them ideal for
rendering portions of HTML that are reusable across different parts of an
application, such as headers, footers, or complex form elements. For
example, if you have a section that displays user information that is
required on multiple pages, you can create a Partial View for that section
and include it wherever needed.
Example to Understand Partial Views in ASP.NET MVC:
It is a common task in Web Applications to use the same code repeatedly to
display/render information. For example, an e-commerce web application
would probably render each product similarly on multiple web pages, like
the Product details page, cart page, and checkout page. Let’s understand
how we can implement this using Partial Views in an ASP.NET Core MVC
Application. First, let’s create a new ASP.NET Core MVC Web Application
named “PartialViewInMVC” using the Model View Controller Project
Template.
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.
So, right-click on the /Views/Shared folder, then select the Add ->
View option from the context menu. It will open the following window.
Here, we need to select Razor View and click the Add button, as shown in
the image below.
Once you click on the Add button, it will open the following window: Here,
please provide the View name as _ProductDetails without .cshtml
extension, check the Create as a partial view check box, and then click on
the Add button as shown in the image below.
This will create a Partial view. Once you create
the _ProductDetails.cshtml Partial View, open the view file, and copy and
paste the following code. Here, you can see we are using Product as the
model and then displaying Product information. This is similar to our Main
views, which can have a Model, and they can have both Razor Syntax and
HTML Markup to generate dynamic views.
@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.
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); }
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”
/>
Let us render the partial view using the PartialAsync helper method. To
use this Partial HTML Helper method, we need to pass the name of the
partial view as a parameter. As our partial view, expecting the Product
model, we need to pass the Product object as the second parameter, such
as @await Html.PartialAsync(“_ProductDetails”, Model). As it is an
asynchronous method, we need to use the await keyword when calling the
method. So, modify the Details.cshtml View as follows.
Now, run your application and see that everything is working as expected.
But this time, you can re-use this partial view wherever you want, and
moreover, if you decide to change how product details should be rendered,
the only View you need to change is the _ProductDetails.cshtml Partial
View. The above @Html.PartialAsync helper method passed a Product
object to the “_ProductDetails” partial view. The partial view was
dynamically rendered.
Now, let us see how we can use the same Partial View from another View.
Let us first modify the Product Controller as follows. Here, you can see we
have added the Index action method, which is going to render all the
product details.
Next, add the Index.cshhtml view within the Views => Product folder.
Once you add the view, copy and paste the following code.
As you can see in the above code, each loop item calls the same partial view
by passing the product object, which will act as the model in the partial
view. With the above changes in place, run the application and navigate to
the Product/Index action method, and you will see the data as expected,
as shown in the image below.
Using Partial HTML Helper Method in ASP.NET Core MVC:
Now, let us use the Partial HTML Helper method to render the Partial View.
So, modify the Index.cshtml view of the Product Controller as follows. Here,
you can see, we are using the Html.Partial HTML Helper method.
With the above changes in place, run the application and access
the Product/Index URL, and you should get the output as
expected. However, Microsoft does not recommend the use
of HTML.Partial HTML helper method to render partial view. If you move
the mouse pointer over the Partial Method, you will see the following
warning. The first part of the warning message says that you may get
Application Deadlocks.
An application deadlock is a situation in computer programming where
two or more processes or threads become permanently blocked because
each process is waiting for resources or conditions that are being held by
the other processes.
The second part of the warning message says that instead of using the
Partial Method, please use the Partial Tag Helper or PartialAsync method.
We have already discussed rendering the Partial View using the
PartialAsync HTML helper method; now, let us proceed with how to use the
The Partial Tag Helper renders partial views synchronously. So, modify the
Index View of the Product Controller as follows. The model attribute is
assigned a Product instance to be binding to the partial view.
With the above changes in place, run the application, and you should get
the output as expected.
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.
@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.
HTML Helpers in ASP.NET Core MVC simplify the process of creating HTML
elements on a web page and binding data to them. Using HTML Helpers
reduces the chances of introducing typos or errors when manually writing
HTML code. Additionally, HTML Helpers facilitate model binding,
validation, and integration with ASP.NET Core features such as tag helpers,
form validation, and data annotations. They also promote code reusability
and maintainability, making views cleaner and easier to manage.
However, in ASP.NET Core MVC, you can use the TextBox HTML helper
method to generate a text box as follows.
@Html.TextBox(“firtsname”)
Several overloaded versions of the above TextBox HTML helper method are
available, which you can use according to your requirements. For example,
you can use the following overloaded version of the TextBox helper method
to set the value and name.
@Html.TextBox(“firtsname”, “Pranaya”)
At runtime, the above TextBox HTML helper method generates the
following HTML
It is also possible to set the HTML attributes of a text box. If you want to do
so, you need to use the following overloaded version of the TextBox HTML
helper method.
Notice that we are passing the HTML attributes title and style to the
TextBox helper method as an anonymous type. Some HTML attributes are
reserved keywords, such as readonly, class, etc. If you want to use these
attributes within a Helper method (which is a C# method), you must prefix
them with the @ symbol, as shown in the example below.
Html.TextBox()
Html.TextArea()
Html.DropDownList()
These helpers are associated with a specific data model and allow for
compile-time checking of model properties. They use lambda expressions
to refer to model properties directly. Examples include:
The HTML Helper methods in ASP.NET Core MVC can be categorized based
on the types of HTML they generate. They are as follows:
Html.TextBox()
Html.CheckBox()
Html.RadioButton()
Html.Label()
Html.DisplayFor()
Html.DisplayTextFor()
Form Helpers:
Html.BeginForm()
Html.EndForm()
Validation Helpers:
Html.ValidationMessageFor()
Html.ValidationSummary()
Link HTML Helpers:
The Link HTML Helpers generate anchor (<a>) tags that create hyperlinks
to different pages within your application. The following are the examples:
Html.ActionLink
Html.RouteLink
Let us understand how to create a text box using the TextBox Helper
method with an example. First, create a new ASP.NET Core Web
Application using the Model-View-Controller Project template named
HTML_HELPER.
Once you create the project, create a class file with the name Employee.cs
within the Models folder and then copy and paste the following code into it.
We will use the above Employee model with TextBox() and TextBoxFor() HTML Helper
methods.
Parameters:
value: This parameter is the initial value the input field will display when
rendered. It populates the <input> element with a value. It provides a way
to pre-fill the input field, such as when editing a form with existing data.
Please modify the Index View of the Home Controller as shown below to
use the TextBox Helper method.
EmployeeName: The name of the input element. If you are binding to a model,
this should match the property’s name in your model.
null: This is where you can specify the value of the TextBox. Passing null means,
it will be empty by default or filled with data from the model if the name
matches.
Run the application and view the page source. The textbox will be produced
using the following HTML.
You can also apply the format parameter to specify how to display the data.
For example, modify the Index.cshtml view as follows. Here, we display the
date time values in yyyy-MM-dd format.
Parameters:
format: This optional parameter specifies the format in which the value of
the bound model property should be displayed in the input field. It is
commonly used for formatting dates, numbers, or other data types. The
format ensures that the value of the bound property is displayed in a user-
friendly or standardized way, such as formatting a date to MM/dd/yyyy or
a number to a currency format.
Please modify the Index View of the Home Controller as shown below to
use the TextBoxFor Helper method. Here, we are creating
HTML_HELPER.Models.Employee model.
Here,
Run the application and inspect the element, and you will see that it will
produce the following HTML
<input class=”form-control” id=”EmployeeName” name=”EmployeeName”
type=”text” value=”” />
In the above example, the first parameter in TextBoxFor() HTML Helper
Method is a lambda expression that specifies the EmployeeName property
of the Model object to bind with the textbox. It generates an input-type text
element with id and name property, and the property’s value is set to
EmployeeName. The value attribute will be set to the value of the
EmployeeName property of the Model Object.
You can also apply the optional format parameter to specify how to display
the data. For example, modify the Index.cshtml view as follows. Here, we
display the date-time values in yyyy-MM-dd format.
TextArea HTML Helper in ASP.NET Core MVC
The TextArea element is defined in HTML using the <textarea> tag. This tag
can include attributes to control its appearance and functionality, such as
rows and cols to specify its size, placeholder for placeholder text,
maxlength to limit the number of characters a user can enter, and readonly
or disabled to control user interaction.
The Html.TextArea method is used when you want to specify the name of
the form field manually, while Html.TextAreaFor is used with model
properties, providing a strongly typed approach. That means the
TextArea() HTML Helper method is loosely typed, whereas the
TextAreaFor() HTML Helper method is strongly typed.
htmlHelper:
Here, Html is an instance of the htmlHelper, and you are calling the
TextArea method on it to generate a <textarea> element.
expression:
In the context of the TextArea helper method, the expression refers to the
name of the form field or model property to which the generated
<textarea> will be bound. It is a string that specifies the name or the
“expression” that will map to a key in the form’s posted data.
value:
The value parameter in the TextArea method refers to the initial content or
value to be displayed inside the <textarea> element. This could be a
predefined string or some dynamic data you want to show to the user when
the form is rendered.
htmlAttributes:
In this case:
Let’s see an example of the TextArea HTML Helper Method in the ASP.NET
Core MVC Application. First, modify the Employee Model, as shown below.
If you inspect the text area, then you will see that it will produce the
following HTML
In the above example, the first parameter is the “Address” property of the
Employee model class, which will be set as the name and id of the textarea.
The second parameter is the value to display in the textarea, which is null
in the above example because the TextArea() method will automatically
display a value of the Address property in the textarea. The third
parameter will be set as a class attribute. The HtmlAttributes parameter is
an object type so it will be an anonymous object, and the attribute name
will be its properties starting with @ symbol.
We can also specify any name for the textarea. However, it will not be
bound to a model.
It will produce the HTML: <textarea class=”form-control”
id=”MyTextArea” name=”MyTextArea”>This is value</textarea>
If you want, then you can also specify the rows and cols size of the text area
as follows:
In this example:
“MyTextArea“ is the name of the text area which will be used in the
form submission.
new { @class = “form-control”, @rows = “4”, @cols = “20” } is an
object initializer that sets HTML attributes like class, rows, and
columns for the TextArea.
In this example:
Countries
States or regions within a country
Categories or types of items
Settings options that have predefined choices
Modify the Index.cshtml view as follows. The following code will generate a
department dropdown list. The first item in the drop-down list will be
Select Department. Here, we have used the Selected property to true for the
IT element, so the “IT” element will be selected by default when the page
loads.
Explanation of Parameters
This is the name of the form element that will be generated. The name
attribute in HTML is used to identify form elements when submitting data.
In this case, the form will send the selected department’s value (e.g., “1” for
IT, “2” for HR, etc) as the Departments field when submitted.
This is the list of options for the dropdown. Each SelectListItem object
represents an item in the dropdown with the following properties:
Text: The text that will be displayed to the user in the dropdown
(e.g., “IT”, “HR”, “Payroll”).
Value: The actual value that will be submitted when the user selects
this option (e.g., “1” for IT, “2” for HR, “3” for Payroll).
Selected: A Boolean value indicates whether this option is selected
by default. In our case, “IT” is selected by default because
Selected=true is set for the first item.
This default text will be shown when no option is selected. This acts as a
placeholder for the dropdown and is displayed as an option that cannot be
selected. It encourages the user to select an actual department. If the user
selects no value, this option will be shown in the dropdown.
HTML Output
Now, run the application and access the Index Page. The helper method
should generate an HTML <select> element with options corresponding to
the list’s items as follows. To see this, please view the page source code in
the browser:
Here,
Use Tag Helpers: Use Tag Helpers directly (HTML-like syntax) in the
Razor views by adding them as HTML attributes. They will be processed on
the server side and rendered as HTML. For example, use asp-action, asp-
controller, or asp-for attributes to generate links or bind data to input
fields.
Example to Understand Built-in Tag Helpers in ASP.NET Core MVC:
create a new ASP.NET Core Application named TagHelpersDemo using the
Model-View-Controller Project template. To make the Built-in Tag Helpers
available for all views of our application, we need to import
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
directive inside the _ViewImports.cshtml file.
If you open the _ViewImports.cshtml file, you will see the following code:
@using TagHelpersDemo
@using TagHelpersDemo.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Here,
@addTagHelper: This directive includes specific Tag Helpers in the Razor
view.
Many different methods are available for generating a link in the ASP.NET
Core MVC Application.
Let’s discuss all the possible options and why we should use Tag Helper
over others.
Method 1: Using HTML Element:
In this case, we need to use the anchor tag, and in the href attribute, we
need to specify the path of the details action method (i.e., the Controller
Name and Action Name) along with the student id like <a
href=”/home/details/@student.StudentId”>View</a>. So, modify the
Index action method of the Home Controller as follows.
With the above changes, run the application and navigate to the Root
or Home/Index URL. You should see the following page on the web
browser.
Once you click the View button, the Home Controller’s Details action
method will execute by passing the corresponding Student ID value. If you
click the View button of Student ID 1, you will see the following Details
view of the Home Controller showing the Student details.
Method 2: Using HTML Helpers
Using HTML Helper methods, we can also generate the link. In this case, we
need to use the ActionLink Helper method to generate the link
like @Html.ActionLink(“View”, “Details”, “Home”, new { id =
student.StudentId }, new { @class = “btn btn-primary” }).
Here, the parameter View is nothing but the link text; the second
parameter Details is the Action method name; the third
parameter Home is the controller’s name.
The fifth parameter is the HTML attributes, and here, we are applying the
BootStarp class. So, modify the Index.cshtml View of the Home Controller
as follows to use the HTML Helper Method to generate the link.
With the above changes, run the application and see if everything works as
expected.
As you can see in the above image, manually generating the links is much
easier than using HTML Helpers or Tag Helpers. So why should we use
HTML helpers or Tag Helpers instead of manually generating these links in
ASP.NET Core?
Why should we use Tag Helpers over manually generating these links
in ASP.NET Core?
In ASP.NET Core MVC, Tag Helpers generate links based on the application
routing configuration. That means if we change the routing configuration in
the future, the links generated by tag helpers will automatically reflect
those changes. So, the generated links work as expected without any
trouble.
<a href=”/Home/Details/@student.StudentId”>View</a>
As you can see with Tag Helper, we have not hardcoded the URL paths.
Here, we only specify the controller and action name, route parameters,
and their values. When the tag helpers are executed on the server, they
automatically look at the route templates and generate the correct URLs.
So, to better understand, modify the Index View as follows:
Here, both the techniques generate the same URL path, i.e.
(/Home/Details/101), and it also works with the current route template,
i.e. ({controller=Home}/{action=Index}/{id?})
In the Tag Helper example, the code looks like standard HTML and the
attributes are more self-explanatory (asp-action, asp-controller, asp-route-
id). In contrast, the HTML Helper syntax is more complex and harder to
read, especially for designers or developers coming from an HTML
background.
The code in the Tag Helper version is cleaner and follows an HTML-first
approach. In contrast, the HTML Helper version embeds C# logic in the
markup, which can make the view more difficult to maintain, especially as
the form’s complexity grows.
Navigation-Menus in ASP.NET Core MVC Application
How to Create Responsive Navigation-Menus in ASP.NET Core MVC
Applications using Bootstrap and jQuery.
But when we open our website on a small screen device like a mobile, we want to show
the navigation menus like the one below. Here, you can see the menus List, Create,
About, and Contact are not visible; instead, the hamburger menu (three horizontal lines)
is visible, and once we click on the three horizontal lines, it will display all the menus.
Please modify the _Layout.cshtml file, which is present inside the Views
=> Shared folder, as shown below.
Next, open the Gender.cs class file and copy and paste the following code.
As you can see, we have created the Gender enum with two named
constants, i.e., Male and Female.
Student Model:
We want to display the student information on the web page. So, create a
class file named Student.cs within the Models folder and copy and paste the
following code.
Let us proceed and implement this step by step. First, create a new
ASP.NET Core MVC Application using the Model View Controller Project
template and give the project name FormTagHelperDemo.
Creating Models:
First, we need to create two Enums to hold the Gender and Branch-named
constants and the Student model, which will hold the student data.
The asp-action Tag Helper specifies the name of the action method to which
the form will submit its data. When this form is submitted, the data will be
sent to the Register action method of the specified controller (in this case,
the StudentController).
The asp-for Tag Helper automatically binds the form element to a model
property. It generates the appropriate id, name, and value attributes for the
HTML element based on the bound property in the Student model. For
example, asp-for=”FullName” binds the <input> element to the FullName
property of the Student model. It also generates the correct label text and
sets for attributes in <label> elements.
The asp-for Tag Helper, in this case, binds the radio buttons to the Gender
property in the model. Each radio button is created dynamically for each
enum value (Male, Female, etc.). The value=”@gender” sets the value of
each radio button to the corresponding gender enum value.
The asp-for Tag Helper binds the <select> dropdown to the Branch
property in the Student model. The Tag Helper generates the necessary
name, id, and value attributes, and the dropdown options are dynamically
populated using a foreach loop that iterates over the Branch enum values.
The asp-for Tag Helper binds the multi-select dropdown to the Skills list in
the Student model. When the form is submitted, the selected values from
the multi-select dropdown are bound to the Skills list in the model. The
multiple attribute allows multiple options to be selected.
This Tag Helper binds the <textarea> element to the Address property of
the Student model. It handles multi-line input and ensures the correct ID,
name, and initial value are set from the model data.
The asp-for Tag Helper binds the <input> element to the Password
property of the model, ensuring that the name and id attributes are set
correctly. The type=”password” attribute ensures that the input will be
treated as a password field, hiding the user’s input.
Now, click the Add New Student menu to open the Student Registration
page. Please fill out the form and click on the Register button as shown in
the image below:
Once you click on the Register button, it should Register the new Student
and navigate to the Student list Page, where you should see the newly
created student as shown in the image below:
Partial Tag Helper in ASP.NET Core MVC
What is a Partial View in ASP.NET Core MVC?
A Partial View in ASP.NET Core MVC is a reusable View Component that can
be embedded within other views. It is essentially a smaller view or part of a
view rendered inside a parent view. Partial Views are useful when we want
to break down large views into smaller, manageable components that can
be reused across different views in our application.
Partial Views are similar to regular views but do not have a layout by
default.
They typically render a portion of the view or page, like headers, footers,
forms, or other sections.
You can pass data to Partial Views using the parent model or passing a
separate one.
Rendering Without a Model: If the partial view does not require any
specific model, you can render it like the below example:
<partial name=”_FooterPartial” />
Note: The name attribute specifies the name of the partial view, and the
model attribute provides the model data to be used within it.
First, create a new ASP.NET Core Project using the Model View Controller
Template and name it PartialTagHelperDemo.