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

Unit 3

Uploaded by

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

Unit 3

Uploaded by

nkpatel2355
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

ASP.

NET Core - I
#2101CS511

Unit-3
Views, Helpers &
Routing

Prof. Naimish R. Vadodariya


Computer Science & Engineering
Department
Darshan University, Rajkot
Naimish.vadodariya@darshan.ac.in
8866215253
 Outline
Looping
• Views
• Introduction to Views
• Advantages of Views
• Types of Views
• Helpers
• Overview
• HTML Helpers
• Tag Helpers
• Routing
• Overview of Routing
• Conventional Routing
• Attribute Routing
• Routing Constraints
Views
Section – 1.1
Introduction : View
 The Views in ASP.NET Core MVC are HTML templates with embedded Razor markup
which generate content that sends to the client.
 A view is a file with a “.cshtml” (for C# language) extension.
 The meaning of cshtml = CS (C Sharp) + HTML
 That means the view is a combination of programming language (C#) and HTML (Hypertext
Mark-up Language).
 The Views in ASP.NET Core MVC Application are generally returned from the Controller
Action Method.
 A view in ASP.NET Core MVC Application is responsible for UI i.e. Data Presentation.
 That means we display information about the application on the browser using the views
only.
 A user generally performs all the actions on a view such as a button click, forms, list, and
other UI elements.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 4
Introduction : View Cont..
 By default, Views are available inside the Views folder at the root, if you have created Areas
then it associated with specific areas views folder.
 Usually, views are grouped into folder names with the applications controller.
 Each controller will have its own folder in which the controller-specific view files are going
to be stored.
 The controller-specific folders are going to be created within the Views folder only.
 View file name is the same as the action method name of a controller with the “.cshtml”
extension.
 For example, if the controller action method is Index, the view file would be Index.cshtml.
 This makes your application easier to maintain and develop.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 5
Views : Example
 Let’s say, we have an ASP.NET Core
MVC application with two controllers
 i.e. HomeController and
StudentController. Views
 The HomeController is created with the
following three action methods.
 AboutUs()
 ContactUs()
 Index() Views

 On the other hand, the


StudentController is created with the
following four action methods.
 Index()
 Details()
 Edit()
 Delete()
#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &
Prof. Naimish R. Vadodariya 6
Views with Area : Example
 Let’s say, we have an ASP.NET Core
Country Area
MVC Areas.
 i.e. Areas created as Country and Student.
 The Country Area is with the following
three action methods in their Views.
 Index() Views
 Edit()
 Delete()
Student Area
 The Student Area is with the following
four action methods in their Views.
 Delete()
 Edit()
 Index()
 Search() Views

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 7
View (Code) : Example

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 8
Advantages of Views
 Views are an important part of the ASP.NET Core MVC framework.
 They allow you to separate the presentation layer of application from the business logic and
data access layers.
 With the help of views, application is easy to maintain and develop.
 Separation of concerns:
 Views are responsible for the presentation layer of the application, while controllers are responsible for the
business logic and data access layers.
 Reusability:
 Views can be reused in different parts of the application.
 This can save time and effort when developing the application.
 Flexibility:
 Views can be customized to meet the specific needs of the application.
 This makes the application more flexible and adaptable.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 9
Remember!!!
Adding a
View
 Click on your Views Folder, Inside Views folder there is controller specific folder 📁.
 On that specific controller folder 📁, right click on it and go to AddViewRazor View – Empty.
 Give view name and press Add.

Searching View
Behavior
 The default behavior of the View method (i.e., return View();) is to return a view with the same name as
the action method name from which it is being called.
 For example, the Index ActionResult method of the Home controller is used to search for a view file with
the name Index.cshtml in the following two locations.
1. First, it will look for the “Index.cshtml” file within the /Views/Home, i.e., Views/[ControllerName]
folder, as the action method belongs to 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.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 10
Different types of Razor files
Section – 1.2
Different types of Razor files
 All Razor files end with .cshtml. Most Razor files are intended to be browsable and contain a
mixture of client-side and server-side code, which, when processed, results in HTML being
sent to the browser.
 These pages are usually referred to as "content pages".
 Other Razor files have a leading underscore (_) in their file name.
 The leading underscore is often used for naming partial pages, but below mentioned three
files named in this way have a particular function within a Razor Pages application.
 _Layout.cshtml
 _ViewStart.cshtml
 _ViewImports.cshtml
 The leading underscore in the file name indicates that these files are not intended to be served
directly by the browser.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 12
_Layout.cshtml
 The _Layout.cshtml file acts a template for all
content pages that reference it.
 Consistent part of a site's design are declared in
the _Layout.cshtml file.
 These can include the header, footer, site
navigation, main content area and so on.
 Typically, the _Layout.cshtml file also includes
the <head> section of the page, so they also
reference the common CSS style sheet files and
JavaScript files. In ASP.NET Core MVC, creating multiple
 If you want to make changes to the overall layout files for a single application is possible.
For example, you may have one layout file for
design of the site, you often only need to make the admin users and another layout file for non-
adjustments to the content of the admin users of your application.
_Layout.cshtml.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 13
_Layout.cshtml
 We can say that the common UI code,
which can be used in many views, can go
into a common view called _Layout in
application.
 As the layout views are not specific to any
controller.
 As the layout view will be used across
multiple views of our application, we
usually place the layout views in
a Shared subfolder within
the Views folder.
 By default, in ASP.NET Core MVC App,
the layout view file is named
_Layout.cshtml. But you can change the
name if you wish.
#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &
Prof. Naimish R. Vadodariya 14
_ViewStart.cshtml
 The _ViewStart.cshtml file contains code that executes after the code in any content page in
the same folder or any child folders.
 It provides a convenient location to specify the layout file for all content pages that are
affected by it, and that is typically what you see in the _ViewStart.cshtml file that comes with
any Razor Pages (or MVC) template.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 15
_ViewImports.cshtml
 It is a special Razor view file that allows us to specify the common namespaces, directives,
and other elements, that will be automatically imported and applied to all views within a
specific directory and its subdirectories.
 It helps us to simplify the Razor syntax and reduce repetitive code by centralizing the import
statements in one place.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 16
Partial Views
Section – 1.3
Introduction : Partial View
 A partial view is a regular view that can be used multiple times in an application and it has
the file extension .cshtml.
 We need to develop a partial view when we need a common part of the user interface on
multiple pages in a web application.
 Sometimes we also use a partial view to divide a web page into small parts such as
header, footer, and menu on Layout.
 Partial views help us to reduce code duplication.
 Partial Views are the views that are rendered within another view.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 18
Partial View Example

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 19
Views v/s Partial Views
Views Partial Views
View contains the layout page Partial View does not contain the layout page
Before any view is rendered, viewstart page is rendered Partial view does not verify for a viewstart.cshtml page
View might have markup tags like body, html, head, title, Partial view is designed specially to render within the view
Meta etc. and just because of that it does not consist any mark up tag
View is not lightweight as compare to Partial View Partial view is lightweight
A "View" in the context of web development typically refers Partial view is a reusable piece of a view that can be
to the template or markup that defines the structure and included in multiple views.
presentation of the entire page.
Views are typically rendered as complete pages. Partial Views are embedded within views and can be
dynamically loaded or included where needed.
Views are typically not as reusable as partial views because Partial Views are designed for reusability, you can include
they often encapsulate a specific page's structure and the same partial view in multiple views to maintain
content. consistent UI elements across different parts of your
application.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 20
Helpers
Section 2.1
Introduction: Helpers
 HTML Helpers are classes that can generate html tags in Razor view pages.
 An HTML Helper is just a method that returns a HTML string.
 The string can represent any type of content that you want.
 For example, you can use HTML Helpers to render standard HTML tags like HTML <input>,
<button> and <img> tags etc.
 It also binds the model object to HTML controls to display the value of model properties
into those controls and also assigns the value of the controls to the model properties while
submitting a web form.
 So, we can always use the HtmlHelper class in razor view instead of writing HTML tags
manually.
 Starts with @Html is an object of the HtmlHelper class. (@ symbol is used to access server-
side object in razor syntax)

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 22
Built-In Html Helpers
1. Standard Html Helpers
2. Strongly Typed HTML Helpers (Model)

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 23
Standard Html Helpers
Section 2.2
1. Standard Html Helpers
HTML Element Example
@Html.TextBox("txtLastName", “Last Name")
TextBox
<input id="txtLastName" name="LastName" type="text" value="Last Name" />
@Html.TextArea("txtAddress", "Enter Address", 5, 15, null)
TextArea
<textarea id="txtAddress" name="Address" rows="5" cols="15">Enter Address</textarea>
@Html.Password("txtPassword", "123")
Password
<input id="txtPassword" name="Password" type="password" value="123" />
@Html.Hidden("Hidden1", "val")
Hidden Field
<input id="Hidden1" name="Hidden1" type="hidden" value="val" />

@Html.CheckBox("Checkbox1", false)
CheckBox <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />

@Html.RadioButton("Radiobutton1", "val", true)


RadioButton
<input checked="checked" id="Radiobutton1" name="Radiobutton1" type="radio" value="val" />

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 25
1. Standard Html Helpers Cont..
HTML Element Example
Drop-down list @Html.DropDownList("DropDownList1", new SelectList(new [] {"Male", "Female"}))
<select id="DropDownList1" name="DropDownList1">
<option>Male</option>
<option>Female</option>
</select>
Multiple-select @Html.ListBox("ListBox1", new MultiSelectList(new [] {"Cricket", "Chess"}))
<select id="ListBox1" multiple="multiple" name="ListBox1">
<option>Cricket</option>
<option>Chess</option>
</select>

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 26
Example: Standard Html Helpers

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 27
Strongly Typed HTML Helpers
Section 2.3
2. Strongly Typed HTML Helpers
HTML Element Example
@Html.TextBoxFor(m=>m.Name)
TextBoxFor
<input id="Name" name="Name" type="text" value="Name-val" />
@Html.TextAreaFor(m=>m.Address, 5, 15, new{}))
TextAreaFor
<textarea cols="15" id="Address" name=" Address " rows="5">Addressvalue</textarea>
@Html.PasswordFor(m=>m.Password)
PasswordFor
<input id="Password" name="Password" type="password" />
@Html.HiddenFor(m=>m.StudentId)
HiddenFor
<input id="StudentId" name="StudentId" type="hidden" value="StudentId-val" />

@Html.CheckBoxFor(m=>m.IsDetained)
CheckBoxFor <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />

@Html.RadioButtonFor(m=>m.IsDetained, "val")
RadioButtonFor
<input checked="checked" id="Radiobutton1" name="Radiobutton1" type="radio" value="val" />

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 29
2. Strongly Typed HTML Helpers
HTML Element Example
DropDownListFor @Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male", "Female"}))
<select id="Gender" name="Gender">
<option>Male</option>
<option>Female</option>
</select>
ListBoxFor @Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {"Cricket", "Chess"}))
<select id="Hobbies" multiple="multiple" name="Hobbies">
<option>Cricket</option>
<option>Chess</option>
</select>
ActionLink @Html.ActionLink("Click here", // <-- Link text
"About", // <-- Action Method Name
"Home", // <-- Controller Name
null, // <-- Route value
null // <-- html Arguments )

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 30
Student Model (StudentModel.cs)

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 31
2. Strongly Typed HTML Helpers

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 32
2. Strongly Typed HTML Helpers

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 33
Example: Strongly Typed HTML Helpers

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 34
Anchor Tag Helper
 This tag helper is used generate href attributes to link to a particular controller action or MVC
route.
 This tag helper is an alternative to using @Html.ActionLinkor @Url.Action helper methods.
 For example, the following code in a Razor view:
 @Html.ActionLink("Register Yourself","RegisterMethod", "Account")
<a href="@Url.Action("RegisterMethod", "Account")">Register Yourself</a>
 It will generate two identical anchor html tags.
 <a href="/Account/RegisterMethod">Register Yourself </a>
<a href="/Account/RegisterMethod">Register Yourself </a>
 Using the anchor tag helper, we can generate the same HTML as above by adding the asp-
controller and asp-action attributes to an anchor tag as follows:
 <a asp-controller="Account“ asp-action="RegisterMethod">Register Yourself</a>

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 35
Link to Controller Actions from Views
 There are at least three different ways to make links in ASP.NET MVC Core:
 HtmlHelperLinkExtensions.ActionLink @Html.ActionLink extension method
 Anchor tag helper, <a asp-* ...>
 Url.Action() extension method

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 36
ActionLink Extension Method
 ActionLink (IHtmlHelper, String, String)
 ActionLink (IHtmlHelper, String, String, Object)
 ActionLink (IHtmlHelper, String, String, String)
 ActionLink (IHtmlHelper, String, String, Object, Object)
 ActionLink (IHtmlHelper, String, String, String, Object)
 ActionLink (IHtmlHelper, String, String, String, Object, Object)

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 37
ActionLink Extension Method Cont..
Get a link to the current controller’s
action
1 @Html.ActionLink("Link to Index action", "Index")
Get a link to specific controller and
action:
1 @Html.ActionLink("Link to Index action of Home controller", "Index", "Home")
Get a link to specific controller and action with
parameters
1 @Html.ActionLink("Link to Index action of Home controller with id=100500 and
2 name='John Doe'", "Index", "Home",
3 new { id = 100500, name = "John Doe" })

Get a link to specific controller and action and set css class for the
link
1 @Html.ActionLink("Link to Index action of Home controller with id=100500 and
2 name='John Doe' and CSS class", "Index", "Home",
3 new { id = 100500, name = "John Doe" },
4 new { @class="css-class"})

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 38
Anchor Extension Methods Cont..
Using ActionLink
1 <p>This link is generated in the View:</p>
2 @Html.ActionLink("Simple link to a 'Home' controller 'Index' action",
3 “Index”, "Home")
4 </p>
Using Anchor
Tag
1 <p>This link is generated in the View:</p>
2 <a asp-controller="Home"
3 asp-action="Index">Simple link to a 'Home' controller 'Index' action
4 </a>
5 </p>
Using URL
Action
1 <p>This link is generated in the View:</p>
2 <a href="@Url.Action("Index", "Home")">
3 Simple link to a 'Home' controller 'Index' action
4 </a>
5 </p>

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 39
Summary

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 40
Tag Helpers
Section 2.4
Tag Helpers
 Tag Helpers are classes written in C# but are attached to HTML elements in order to run
server-side code from Razor view.
 It enable server-side code to participate in creating and rendering HTML elements in Razor
files.
 Tag helpers are a new feature and similar to HTML helpers, which help us render HTML.
 There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading
assets etc.
 Tag Helpers are authored in C#, and they target HTML elements based on the element name,
the attribute name, or the parent tag.
 For example, the built-in LabelTagHelper can target the HTML <label> element when the
LabelTagHelper attributes are applied.
 If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between
HTML and C# in Razor views.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 42
Using a Tag Helpers
 To use the inbuilt or custom Tag Helpers, one has to first reference Tag Helper library named
Microsoft.AspNetCore.Mvc.TagHelpers.
 It can also be taken from Nuget.
 Once referenced, import it using @AddTagHelper directive as shown below inside
_ViewImports.cshtml,

 In the above line, all the Tag helpers will be imported which are mentioned in
'Microsoft.AspNetCore.Mvc.TagHelpers' assembly.
 Whatever is referenced/imported inside _ViewImports.cshtml will be available for all the
views.
#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &
Prof. Naimish R. Vadodariya 43
Common Built-in Tag Helpers
 These Tag Helpers are provided by default as part of the ASP.NET Core framework.
 They cover common scenarios and tasks, making generating HTML with dynamic behavior
easier, such as generating links, creating forms, loading assets, showing validation messages,
etc. Some examples of built-in Tag Helpers include:
 <a asp-controller=”Home” asp-action=”Index”>Link</a>: Generates a link with a URL
that’s generated by routing based on the specified controller and action.
 <img src=”~/images/pic.jpg” asp-append-version=”true” />: Generates a <img> tag with
a cache-busting query string to ensure the latest version of the image is fetched.
 <form asp-controller=”Account” asp-action=”Login”
method=”post”>…</form>: Generates a form element with the appropriate action attribute
for the specified controller and action.
 <input asp-for=”Username” />: Generates an input field with attributes based on the model
property specified by asp-for.
 <span asp-validation-for="Username" class="text-danger"></span>: Generates a
username validation message with specified control.
#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &
Prof. Naimish R. Vadodariya 44
Built-in Tag Helpers Cont..
Attribute Asp Attribute Name Description
action asp-action The name of the action method on an MVC controller
all-route-data asp-all-route-data Multiple route parameter values
area asp-area The name of the Area
Controller asp-controller The name of the MVC controller
Fragment asp-fragment The fragment in the URL
host asp-host The domain
page asp-page The Razor page to link to
page-handler asp-page-handler The Razor page handler method to invoke
protocol asp-protocol The protocol (http, https, ftp etc)
route asp-route The name of the route
route- asp-route-* A single route parameter value

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 45
Routing
Section 3.1
Introduction: Routing
 The Routing in the ASP.NET Core MVC Web Application is a mechanism in which it will
inspect the incoming HTTP Requests (i.e. URLs) and then mapped that HTTP request to the
controller’s action method.
 It is the process through which the application matches an incoming URL path and executes
the corresponding action methods.
 You can configure multiple routes for your application and for each route, you can also set
some specific configurations such as default values, constraints, etc.
 We can define the routes either in the startup code or as attributes.
 It describes how we can match the URL paths with the action methods.
 We can also use routes to generate URLs for links that are sent out in responses.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 47
Types of Routing
 There are two types of routing for action methods:
 Conventional Routing OR Convention-Based Routing
 Attribute Routing OR Attribute-Based Routing

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 48
Conventional Routing
Section 3.2
1. Conventional Routing
 In Conventional Based Routing, the route is determined based on the conventions defined in
the Routing Middleware which will map the incoming HTTP Requests (i.e. URLs) to
controller action methods.
 From .NET 6, you can configure the Convention Based Routes within the Main method of the
Program class.
 In the ASP.NET Core MVC Web Application, it is the controller action method that is going
to handle the incoming HTTP Requests i.e. URLs.
 For example, if we issue a request to the /Home/Index URL, then it is the Index action
method of the Home Controller class that is going to handle the request as shown in the
below image.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 50
1. Conventional Routing Cont..
 Similarly, if we issue a request to the /Home/Details/2 URL, then it is the Details action
method of the Home Controller class that is going to handle the request as shown in the
below image.
 Here the parameter value 2 is automatically mapped to the id parameter of the Details
action method.
This is actually done by
the MVC Middleware
Component which we
registered in the
application’s Request
Processing Pipeline.

 Now, the question that should come to your mind is, we have not explicitly defined any
routing rules for the application, then how does this mapping is done i.e.
 How the /Home/Index URL is mapped to the Index action method and
how /Home/Details/2 URL is mapped to the Details action method of the Home Controller
class.
Prof. Naimish R. Vadodariya
#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &
51
Program.cs
 The default route is
created with the
following URL
Pattern.
 So, if we don’t specify
anything in the URL,
then by default the
Index action method
of the Home
Controller class is
going to handle the
This is Required for Routing
request.
 {controller=Home}/
This will define the route
pattern along with the Default {action=Index}/{id?}
Route

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 52
Example
public class StudentController : Controller
{
public string Index()
{
return "Index() Action Method of StudentController";

public string Details(int? id)


{

return $"Details({id}) Action Method of StudentController";


}
}
 Now, the URL “/student/index” is mapped to the Index() action method of
the StudentController class, and the URL “/student/details” or “/student/details/5” both are
mapped to the Details(int? id) action method of the StudentController.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 53
Attribute Routing
Section 3.3
2. Attribute Routing
 With the help of ASP.NET Core Attribute
Routing, you can use the Route attribute
to define routes for your application.
 You can use the Route attribute either at
the Controller level or at the Controller
Action Methods level.
 When you apply the Route attribute at
the Controller level, then it is applicable
for all the action methods of that
controller.
 Let us modify the Home Controller as
shown here.
 Here we have applied the Route Attribute
at the Action method.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 55
2. Attribute Routing Cont..
 If you notice, here we applied
the Route() attribute 3 times on
the Index() action method of Home
Controller.
 The point that you need to remember
is, with each instance of the Route
attribute we specified a different route
template.
 With the above three Route attribute,
now we can access the Index() action
method of the HomeController using the
following 3 URLs.
 http://localhost:5280/
 http://localhost:5280/Home
 http://localhost:5280/Home/Index

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 56
2. Attribute Routing (With Parameters) Cont..
 With conventional based routing, we can
specify the route parameters as part of
the route template.
 We can also do the same with attribute
routing. That means we can also define
Route Attribute with parameters.
 To understand this, modify the Home
Controller as shown here.
 This is done by a process called Model
binding.
Output

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 57
2. Attribute Routing (With Optional Parameters) Cont..
 Like conventional based routing, we can
also make a parameter as optional in
Attribute Routing.
 To make the Route parameter optional,
simply add a question mark “?” at the
end of the parameter.
 Now, we check the output with given
images.

Outpu
t

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 58
2. Attribute Routing (At Controller Level) Cont..
 In the ASP.NET Core MVC application,
it is also possible to apply the Route()
attribute on the Controller class as well
as on individual action methods.
 If you want to make the attribute routing
less repetitive, then you need to use the
route attributes on the controller level as
well as on the individual action methods
level.
 The Route template applied on the
controller level is prepended to the route
template applied to the action method
level.

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 59
How to ignore the Route Template placed at the Controller Level?
 In order to ignore the Route Template
placed at the Controller level, you need
to use / or ~/ at the action method level.
 If the action method route template starts
with / or ~/, then the controller route
template is not going to be combined
with the action method route template.
 Output

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 60
Adding Route Parameters
 In some cases, you might need to specify additional parameters for the controller action that
you are binding to.
 You can specify values for these parameters by adding attributes with the asp-
route- prefix.
 For example, you might need to specify the id of a product you are linking to, you would add
a asp-route-id attribute as follows:
<a asp-controller="Product"
asp-action="Display"
asp-route-id="@ViewBag.ProductId"> View Details
</a>
 It will generate the following html when ViewBag.Id = 1:
 <a href="/Product/Display/1">View Details</a>

#2101CS511 (ASP.NET Core - I)  Unit -3 Views, Helpers &


Prof. Naimish R. Vadodariya 61
ASP.NET Core - I
#2101CS511

Thank
You

Prof. Naimish R. Vadodariya


Computer Science & Engineering
Department
Darshan University, Rajkot
Naimish.vadodariya@darshan.ac.in
8866215253

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy