SlideShare a Scribd company logo
Building Websites Using ASP.NET
Core Razor Pages
2
◆ Overview ASP.NET Core Razor Pages
◆ Introduce Razor Page files and Razor syntax
◆ Work with Page Models (Handler Methods, ViewData, Action Results)
◆ Understand Tag Helpers in Razor Pages
◆ Understand and work with View Components
◆ Apply Routing and URLs in Razor Pages
◆ Apply and configure the Startup with Razor Pages
◆ Validate input data with Validation and Model Binding in Razor Pages
◆ Understand and work with State Management in Razor Pages
◆ Scaffolding for Razor Pages
◆ Demo
08/21/21
Objectives
08/21/21 3
ASP.NET Core Razor Pages - 1
◆ ASP.NET Razor Pages is a server-side, page-focused framework that enables
building dynamic, data-driven web sites with clean separation of concerns.
◆ Part of the ASP.NET Core web development framework from Microsoft, Razor
Pages supports cross platform development and can be deployed to Windows,
Unix and Mac operating systems.
◆ The Razor Pages framework is lightweight and very flexible.
◆ It provides the developer with full control over rendered HTML.
◆ Razor Pages is the recommended framework for cross-platform server-side
HTML generation.
08/21/21 4
ASP.NET Core Razor Pages - 2
◆ Razor Pages makes use of the popular C# programming language for server-
side programming, and the easy-to-learn Razor templating syntax for
embedding C# in HTML mark-up to generate content for browsers dynamically.
◆ Architecturally, Razor Pages is an implementation of the MVC pattern and
encourages separation of concerns.
◆ Razor Pages is included within .NET Core from version 2.0 onwards, which is
available as a free download as either an SDK or a Runtime.
08/21/21 5
Razor Pages
◆ Razor is a markup syntax for embedding server-based code into webpages.
◆ The Razor syntax consists of Razor markup, C#, and HTML. Files containing
Razor generally have a .cshtml file extension.
◆ The default Razor language is HTML. Rendering HTML from Razor markup is
no different than rendering HTML from an HTML file. HTML markup in .cshtml
◆ Razor files is rendered by the server unchanged.
◆ Different types of ASP.NET Razor
◆ Razor Page (Single Page Model) – Demo1.cshtml
◆ Razor Page (with Page Model) – Demo2.cshtml + Demo2.cshtml.cs
◆ Razor with MVC
08/21/21 6
Razor Pages – Single File Approach
◆ The Razor code block is denoted by an opening
@{ and is terminated with a closing }. The
content within the block is standard C# code.
◆ Functions blocks
08/21/21 7
Razor Pages – PageModel Files
◆ Any code relating to the processing of user input
or data should be placed in PageModel files,
which share a one-to-one mapping with their
associated content page.
◆ They even share the same file name, albeit with
an additional .cs.
08/21/21 8
Different types of Razor files - 1
◆ Razor files have a leading underscore (_) in their file name. These files are not
intended to be browsable.
◆ The _Layout.cshtml file acts a template for all content pages that reference it.
Consistent part of a site's design are declared in this file.
◆ 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.
◆ The _ViewImports.cshtml file provides a mechanism to make directives
available to Razor pages globally so that you don't have to add them to pages
individually.
08/21/21 9
Different types of Razor files - 2
◆ Partial Pages or Views are Razor files containing snippets of HTML and server-
side code to be included in any number of pages or layouts.
◆ Partial pages can be used to break up complex pages into smaller units,
thereby reducing the complexity and allowing teams to work on different units
concurrently.
◆ Partial pages are cshtml files that do not take part in routing. Rendering Partial
Pages:
◆ <partial name="_MenuPartial" />
◆ @Html.Partial("_MenuPartial")
◆ @{ Html.RenderPartial("_MenuPartial"); }
◆
08/21/21 10
Different types of Razor files - 3
◆ The layout page acts as a template for all pages that reference it.
_SubLayout1.cshtml
_MasterLayout.cshtml
08/21/21 11
Different types of Razor files - 4
◆ _ViewImports.cshtml file provides a mechanism to centralize directives that
apply to Razor pages.
◆ The default Razor Pages template includes a _ViewImports.cshtml file in the
Pages folder - the root folder for Razor pages.
◆ The _ViewImports.cshtml file supports the following directives:
◆ @addTagHelper, @removeTagHelper, @tagHelperPrefix
◆ @inherits, @namespace
◆ @inject, @model, @using
08/21/21 12
Razor Syntax
◆ A Razor content page acts as a template for generating HTML. The typical
content page includes static HTML, tag helpers that emit HTML dynamically,
and C# code.
◆ The C# code is embedded within the static content and tag helpers according
to a set of rules, or syntax.
◆ All code blocks must appear within @{ ... C# code } brackets.
◆ Comments within a code block can be denoted by two forward slashes //.
Alternatively, you can use /*...*/ or @*...*@.
08/21/21 13
The Razor Pages PageModel - 1
◆ The main purpose of the Razor Pages PageModel class is to provide clear
separation between the UI layer (the .cshtml view file) and processing logic for
the page. There are a number of reasons why this separation is beneficial:
◆ It reduces the complexity of the UI layer making it easier to maintain.
◆ It facilitates automated unit testing.
◆ It enables greater flexibility for teams in that one member can work on the
view while another can work on the processing logic.
◆ It encourages smaller, reusable units of code for specific purposes, which
aids maintenance and scalability.
08/21/21 14
The Razor Pages PageModel - 2
◆ The PageModel class is a combination of a Controller and a ViewModel.
◆ Controllers feature in a number of design and architectural patterns concerned
with the presentation layer of an application. They are most commonly found in
the Model-View-Controller (MVC) pattern, where the controller can be
implemented as a Front Controller or a Page Controller.
◆ A front controller is defined as "a controller that handles all requests for a
website". A page controller is "an object that handles a request for a specific
page or action on a website". A Razor PageModel class is an implementation of
the Page Controller pattern.
◆ The Page Controller pattern is characterized by the fact that there is a one-to-
one mapping between pages and their controllers.
08/21/21 15
The Razor Pages PageModel - 3
◆ A View Model is an implementation of the Presentation Model design pattern.
◆ It is a self-contained class that represents the data and behaviour of a specific
"view" or page. The view model pattern is used extensively in MVC application
development, where it mainly represents data, but typically little behaviour.
◆ In Razor Pages, the PageModel is also the view model.
◆ Razor Pages is sometimes described as implementing the MVVM (Model, View
ViewModel) pattern. It doesn't. The MVVM pattern is applied to applications
where the presentation and model share the same layer.
08/21/21 16
The Razor Pages PageModel - 4
◆ The following code shows the content that is generated for each file when you
use the Razor Page (with page model) option to add a new page to a Razor
Pages application
Index1.cshtml
Index1.cshtml.cs
08/21/21 17
Handler Methods in Razor Pages - 1
◆ Handler methods in Razor Pages are methods that are
automatically executed as a result of a request. The
Razor Pages framework uses a naming convention to
select the appropriate handler method to execute.
◆ The name of the method, which is prefixed with "On":
OnGet(), OnPost(), OnPut() etc.
◆ Handler methods also have optional asynchronous
equivalents: OnPostAsync(), OnGetAsync() etc
(methods that contain asynchronous code).
◆ As far as the Razor Pages framework is concerned,
OnGet and OnGetAsync are the same handler.
08/21/21 18
Working With ViewData in Razor Pages - 1
◆ ViewData is a container for data to be passed from the PageModel to the
content page.
◆ ViewData is a dictionary of objects with a string-based key.
08/21/21 19
Working With ViewData in Razor Pages - 2
◆ ViewData Attribute
◆ ViewBag is a wrapper around the ViewData dictionary and provides an
alternative way to access ViewData contents within ASP.NET Core MVC
controllers using dynamic properties instead of string-based indexes.
08/21/21 20
Action Results in Razor Pages - 1
◆ Action results in Razor Pages are commonly used as the return type of handler
methods and are responsible for generating responses and appropriate status
codes.
◆ Action results implement either the abstract
Microsoft.AspNetCore.Mvc.ActionResult class, or the
Microsoft.AspNetCore.Mvc.IActionResult interface.
08/21/21 21
Action Results in Razor Pages - 2
◆ ASP.NET Core includes more than three dozen ActionResult classes covering
a wide range of needs, including but not limited to executing and returning the
content of a Razor page, returning the content of a file, redirecting to another
resource or simply returning a specific HTTP status code.
08/21/21 22
Tag Helpers - 1
◆ Tag helpers are reusable components for automating the generation of HTML
in Razor Pages.
◆ Tag helpers target specific HTML tags. The ASP.NET Core framework includes
a number of predefined tag helpers targeting many commonly used HTML
elements as well as some custom tags:
◆ Anchor tag helper, Cache tag helper, Environment tag helper,
◆ Form Action tag helper, Form tag helper, Image tag helper,
◆ Input tag helper, Label tag helper, Link tag helper, Option tag helper
◆ Partial tag helper, Script tag helper, Select tag helper
◆ Textarea tag helper, Validation tag helper, Validation Summary tag helper
08/21/21 23
Tag Helpers - 2
◆ The Tag helpers used in Razor Pages were introduced as part of ASP.NET
MVC Core and are found in the Microsoft.AspNetCore.Mvc.TagHelpers
package which is included as part of the Microsoft.AspNetCore.All meta-
package.
◆ Enabling Tag Helpers
◆ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
◆ @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
◆ Selective tag processing - Use the @addTagHelper and @removeTagHelper
directives to opt in or opt out of
◆ @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
◆ @removeTagHelper "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper,
Microsoft.AspNetCore.Mvc.TagHelpers"
08/21/21 24
Tag Helpers - 3
◆ The Input tag helper generates appropriate name and id attribute values based
on the PageModel property that is assigned to it.
◆ It will also generate an appropriate value for the type attribute, based on the
property's meta data. The tag helper will also emit attributes that provide
support for unobtrusive client-side validation.
◆ Type attribute based on data annotations
08/21/21 25
Tag Helpers - 4
1
2
3
4
Code generation
08/21/21 26
View Components in Razor Pages - 1
◆ View Components perform a similar role to Tag Helpers and Partial Pages.
◆ View components are recommended instead of partial pages or tag helpers
whenever any form of logic is required to obtain data for inclusion in the
resulting HTML snippet, specifically calls to an external resource such as a file,
database or web service.
◆ View components also lend themselves to unit testing.
◆ View components are particularly useful for data-driven features in a layout
page where there is no related page model or controller class.
08/21/21 27
View Components in Razor Pages - 2
◆ View components consist of a class file and a .cshtml view file. The class file
contains the logic for generating the model. It can be thought of as a mini-
controller, just as the Razor PageModel file is considered to be a controller.
The view file contains the template used to generate the HTML to be plugged in
to the page that hosts the view component.
◆ The class file must conform to the following rules:
1. It must derive from the ViewComponent class
2. It must have "ViewComponent" as a suffix to the class name or it must be
decorated with the [ViewComponent] attribute
3. It must implement a method named Invoke with a return type of
IViewComponentResult
08/21/21 28
Razor Pages Routing
◆ Routing is the system that matches URLs to Razor pages (matching URLs to
file paths, starting from the root Razor Pages folder)
◆ When a Razor Pages application starts up, a collection of Attribute Routes is
constructed, using the file and folder paths rooted in the Pages folder as the
basis for each route's template.
◆ Index.cshtml - you can access Index.cshtml by browsing to both
http://yourdomain.com/ and http://yourdomain.com/Index.
◆ If you create a folder named Demo and add a file named Index.cshtml to it, a
further two routes will be defined with the following templates: "Demo",
"Demo/Index"
08/21/21 29
The Startup Class - 1
◆ ASP.NET Core makes extensive use of dependency injection (DI) - a technique
that facilitates loose coupling of code. Components, or "services" are
represented as abstractions, typically interfaces, as you have already seen in
the Configure method with IApplicationBuilder.
◆ The primary purpose of the ConfigureServices method is as a place to register
implementation types for services that are needed by the application. It is also
used to configure any options related to those services.
◆ If it has been added to the Startup class, the ConfigureServices method is
called before the Configure method. That makes sense, because the Configure
method may attempt to reference services which need to be registered
beforehand so that they can be resolved.
08/21/21 30
The Startup Class – 2
◆ This is the case with the default template where Razor Pages is registered:
◆ If you want to configure the root folder for Razor Pages to be something other
than the default Pages, this is where you would do that
08/21/21 31
Configuration In Razor Pages - 1
◆ ASP.NET Core includes an API for managing configuration settings needed by
the application which includes a number of providers for retrieving data in a
variety of different formats.
◆ Configuration is set up as part of the WebHost.CreateDefaultBuilder method
called in Program.cs, the entry point to the application. Various key/value
stores are added to configuration by default
◆ appsettings.json
◆ User Secrets (if the environment is Development)
◆ Environment variables
◆ Command line arguments
08/21/21 32
Configuration In Razor Pages - 2
◆ The appsettings.json file includes
a section that configures logging
for the application.
08/21/21 33
Configuration In Razor Pages - 3
◆ The IConfiguration object enables you to access
configuration settings in a variety of ways once it has
been injected into your PageModel's constructor.
◆ Add a using directive for
Microsoft.Extensions.Configuration to the
PageModel class file.
◆ The Configuration class includes a convenience
method for retrieving connection strings:
◆ var conn =
Configuration.GetConnectionString("DefaultConnection");
08/21/21 34
Configuration In Razor Pages - 4
◆ Configuring your Razor Pages site to run under HTTPS
◆ Running a site under HTTPS used to be something that only big online
merchants worried about.
◆ The RequireHttps attribute is an authorization filter whose role is to confirm that
requests are received over HTTPS. If the request was not made over HTTPS,
the client will be redirected to the HTTPS version of the request URI if the GET
method was used. Non-HTTPS requests made using any other verb (e.g.
POST) will receive a 403 Forbidden result.
08/21/21 35
Dependency Injection in Razor Pages
◆ Dependency Injection (DI) is a technique that promotes loose coupling of
software through separation of concerns.
◆ In the context of a Razor Pages application, DI encourages you to develop
discrete components for specific tasks, which are then injected into classes that
need to use their functionality.
◆ This results in an application that is easier to maintain and test.
◆ Developers are advised to implement the SOLID principals of software design
to ensure that their applications are robust and easier to maintain and extend.
Another important guiding principal for developers is Don't Repeat Yourself
(DRY), which states that should aim to reduce code repetition wherever
possible.
08/21/21 36
Using Forms in Razor Pages - 1
◆ Forms are used for transferring data from the browser to the web server for
further processing, such as saving it to a database, constructing an email, or
simply subjecting the data to some kind of algorithm and then displaying the
result.
◆ The HTML <form> element is used to create a form on a web page. The form
element has a number of attributes, the most commonly used of which are
method and action. The method attribute determines the HTTP verb to use
when the form is submitted.
◆ By default, the GET verb is used and the form values are appended to the
receiving page's URL as query string values. If the action attribute is omitted,
the form will be submitted to the current URL i.e. the page that the form is in.
08/21/21 37
Using Forms in Razor Pages - 2
◆ Access the user input. User input is only available to server-side code if the
form control has a value applied to the name attribute. There are several ways
to reference posted form values:
◆ Accessing the Request.Form collection via a string-based index, using the name
attribute of the form control as the index value.
◆ Leveraging Model Binding to map form fields to handler method parameters.
◆ Leveraging Model Binding to map form fields to public properties on a PageModel
class.
08/21/21 38
Using Forms in Razor Pages - 3
◆ Leveraging Model Binding to map form fields to handler method parameters.
◆ Leveraging Model Binding to map form fields to public properties on a
PageModel class.
08/21/21 39
Validating User Input in Razor Pages – 1
◆ Validate user input in two places in a web application: in the browser using
client-side script or the browser's in-built data type validation; and on the
server.
◆ The MVC framework, on which Razor Pages is built, includes a robust
validation framework that works against inbound model properties on the client-
side and on the server.
◆ The key players in the input validation framework are:
◆ DataAnnotation Attributes, Tag Helpers
◆ jQuery Unobtrusive Validation
◆ ModelState
◆ Route Constraints
08/21/21 40
Validating User Input in Razor Pages – 2
◆ The primary building
block of the validation
framework is a set of
attributes that inherit
from
ValidationAttribute.
◆ Most of these
attributes reside in the
System.ComponentMo
del.DataAnnotations
namespace.
08/21/21 41
Validating User Input in Razor Pages – 3
◆ An example of DataAnnotation attributes
08/21/21 42
Validating User Input in Razor Pages – 4
◆ Client-side validation support is provided by the jQuery Unobtrusive Validation
library, developed by Microsoft.
◆ Must include jQuery Unobtrusive Validation within the page containing the form
for client side validation to work. This is most easily accomplished by the
inclusion of the _ValidationScriptsPartial.cshtml file (located in the Shared
folder) within the page
08/21/21 43
Validating User Input in Razor Pages – 5
◆ Because it is so easy to circumvent client-side
validation, server-side validation is included as
part of the ASP.NET Core validation framework.
◆ Once property values have been bound, the
framework looks for all validation attributes on
those properties and executes them.
◆ Any failures result in an entry being added to a
ModelStateDictionary. This is made available in
the PageModel class via ModelState, which has
a property named IsValid that returns false if
any of the validation tests fail.
08/21/21 44
Model Binding - 1
◆ Model Binding in Razor Pages is the process that takes values from HTTP
requests and maps them to handler method parameters or PageModel
properties.
◆ Model binding reduces the need for the developer to manually extract values
from the request and then assign them, one by one, to variables or properties
for later processing.
◆ This work is repetitive, tedious and error prone, mainly because request values
are usually only exposed via string-based indexes.
◆ Model binding approaches:
◆ Binding posted form values to Handler Method parameters
◆ Binding posted form values to PageModel properties
08/21/21 45
Model Binding - 2
◆ Binding posted form values to Handler Method parameters
◆ The parameters are named after the form fields, and given an appropriate type
for the expected data. To see this approach in action, remove the assignment
code in the OnPost handler method and add two parameters to the method
◆ When the form is posted, the Razor Pages framework calls the OnPost method
and sees that it has two parameters.
08/21/21 46
Model Binding - 3
◆ Binding posted form values to PageModel properties
◆ This approach is more suitable if you need to access the values outside of the
handler method (for display on the page or binding to tag helpers), or if you
prefer to work in a strongly typed manner within the Razor content page.
◆ This approach involves adding public properties to the PageModel (or to a
@functions block if you don't want to use the PageModel approach) and then
decorating them with the BindProperty attribute.
08/21/21 47
Model Binding - 4
◆ Binding posted form values to PageModel properties (contd.)
08/21/21 48
State Management in Razor Pages - 1
◆ Managing state in Razor Pages is the process of retaining user or application-
related data over the duration of a number of requests.
◆ Razor Pages, along with its underlying MVC framework provides a number of
mechanisms for retaining information (or state) across requests, each with its
benefits and drawbacks:
◆ Hidden Form Fields
◆ Query Strings
◆ Route Data
◆ Cookies
◆ TempData, Session Variables, Application Variables, Caching
◆
08/21/21 49
State Management in Razor Pages - 2
◆ Session state is a mechanism that enables you to store and retrieve user
specific values temporarily. These values can be stored for the duration of the
visitor's session on your site.
◆ Session management in ASP.NET Core is included in the
Microsoft.AspNetCore.All metapackage, but is not enabled by default. Must
enable Session State in the Startup file.
08/21/21
State Management in Razor Pages - 3
◆ Configuring Sessions
◆ Using Session Variables
08/21/21
State Management in Razor Pages - 4
◆ ASP.NET Core uses cookies to tie multiple
request together in a session.
◆ List of properties of Cookie
08/21/21 52
Working with AJAX in Razor Pages - 1
◆ AJAX is a technique used for making requests from the browser to the server
for various purposes such as the retrieval of assorted content including data,
HTML, XML, posting form values and so on.
◆ Requests are initiated from client script (usually JavaScript) once the page has
already been loaded in the browser.
◆ If you wanted to update parts of the page as a result of choices that the user
made, those choices would have to be sent to the server as a form post and
the page would be regenerated on the web server in its entirety.
◆ The use of AJAX in a web page eliminates this stop-start approach to working
in a web page.
08/21/21 53
Working with AJAX in Razor Pages - 2
1 2
08/21/21 54
Working with AJAX in Razor Pages - 3
3 4
5
6
08/21/21 55
Working with AJAX in Razor Pages - 3
7
08/21/21 56
Scaffolding Razor Pages
◆ Scaffolding in ASP.NET Core is a technique used to generate code at design
time to support a number of common application scenarios when working with
Entity Framework Core.
◆ The code generation tool is available as a Nuget package.
Razor Pages Demo
08/21/21 58
Demo 1.
◆ Step 01. Create ASP.NET Core Web App
◆ Step 02. Using Model Binding in Razor Pages to takes
values from HTTP requests and maps them to handler
method parameters or PageModel properties.
◆ Step 03. Create custom validation class
◆ Step 04. Create a Model using DataAnnotations and
custom validation.
◆ Step 05. Create Razor Page (Empty) for form validation
◆ Step 06. Create Razor Page (Empty) for uploading files
◆ Step 07. Build and run Project.
08/21/21 59
Demo 1.
◆ Step 01. Create ASP.NET Core Web App (A project template for creating an
ASP.NET application with example ASP.NET Razor Pages content.)
◆
08/21/21 60
Demo 1.
◆ Step 02. Using Model Binding in Razor Pages to takes values from HTTP
requests and maps them to handler method parameters or PageModel
properties.
08/21/21 61
Demo 1.
◆ Step 03. Create
custom validation class
08/21/21 62
Demo 1.
◆ Step 04. Create a
Model using
DataAnnotations and
custom validation.
08/21/21= 63
Demo 1.
◆ Step 05. Create Razor Page (Empty)
08/21/21 64
Demo 1.
◆ Step 05. (contd.)
08/21/21 65
Demo 1.
◆ Step 06. Create Razor Page
(Empty) for uploading files
08/21/21 66
Demo 1.
◆
08/21/21 67
Demo 2. Razor Pages with Entity Framework
◆ Step 01. Create ASP.NET Core Web
Application
◆ Step 02. Add model – Student, Course,
Enrolment.
◆ Step 03. Manage NuGet packages for
Solution/Project
◆ Step 04. Add Connection string
(appsettings.json file)
◆ Step 05. Scaffold Student pages
◆ Step 06. Change the code on Startup.cs and
Program.cs
◆ Step 07. Build and run Program.
08/21/21 68
Demo 2. Razor Pages with Entity Framework
◆ Manage NuGet packages for Solution/Project
08/21/21 69
Demo 2. Razor Pages with Entity Framework
◆ The scaffolding process will provide these files (creates Razor pages in the
Pages/Students folder)
08/21/21 70
Demo 3
◆ Razor Pages with Entity Framework CRUD (includes search, sorting and paging)
Summary
◆ Concepts were introduced:
◆ Razor Page files and Razor syntax
◆ Page Models (Handler Methods, ViewData, Action Results)
◆ Tag Helpers
◆ View Components
◆ Routing and URLs
◆ Startup with Razor Pages and Configuration
◆ Validation and Model Binding
◆ State Management
◆ Scaffolding
71

More Related Content

PPTX
Asp.net With mvc handson
PDF
Asp 1a-aspnetmvc
PDF
Aspnetmvc 1
PPTX
PPTX
Session 1
PDF
Asp.Net 3 5 Part 1
PPT
Ruby On Rails Siddhesh
Asp.net With mvc handson
Asp 1a-aspnetmvc
Aspnetmvc 1
Session 1
Asp.Net 3 5 Part 1
Ruby On Rails Siddhesh

Similar to Building Websites Using ASP.NET Core Razor Pages (20)

PPTX
Introduction Asp.Net Core, MVC, Docker (Linux), Postman and Swagger
PPTX
Asp.net mvc presentation by Nitin Sawant
PDF
Asp.netrole
PPTX
Using MVC with Kentico 8
PPTX
Asp.net c# MVC-5 Training-Day-2 of Day-9
PPTX
Overview of ASP.Net by software outsourcing company india
PDF
Lecture 05 - Creating a website with Razor Pages.pdf
PPTX
Overview of MVC Framework - by software outsourcing company india
DOCX
JOB PORTALProject SummaryTitle JOB-PORT.docx
PDF
Aspose pdf
PDF
What are razor pages?
PDF
Top 10 - ASP.NET Interview Questions And Answers 2023.pdf
PPT
Super billing asp.net
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
PDF
Beyond rails new
PPTX
Asp.net mvc 5 course module 1 overview
PPT
Asp.net architecture
PPTX
ASP.NET Presentation
DOCX
Beginners introduction to asp.net
PDF
Asp 1-mvc introduction
Introduction Asp.Net Core, MVC, Docker (Linux), Postman and Swagger
Asp.net mvc presentation by Nitin Sawant
Asp.netrole
Using MVC with Kentico 8
Asp.net c# MVC-5 Training-Day-2 of Day-9
Overview of ASP.Net by software outsourcing company india
Lecture 05 - Creating a website with Razor Pages.pdf
Overview of MVC Framework - by software outsourcing company india
JOB PORTALProject SummaryTitle JOB-PORT.docx
Aspose pdf
What are razor pages?
Top 10 - ASP.NET Interview Questions And Answers 2023.pdf
Super billing asp.net
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
Beyond rails new
Asp.net mvc 5 course module 1 overview
Asp.net architecture
ASP.NET Presentation
Beginners introduction to asp.net
Asp 1-mvc introduction
Ad

More from ssusere19c741 (19)

PDF
0-Slot21-22-Strings.pdf
PDF
0-Slot18-19-20-ContiguousStorage.pdf
PDF
0-Slot14-15-16-Libraries.pdf
PDF
0-Slot13-Programming-With-Menu.pdf
PDF
0-Slot11-12-Pointers.pdf
PDF
0-Slot08-09-10-Module-Functions.pdf
PDF
0-Slot05-06-07-Basic-Logics.pdf
PDF
0-Slot02-Introduction-to-PFC.pdf
PDF
Intro-InstallingTool-FirstProgram
PPTX
Background Tasks with Worker Service
PPTX
Real-Time Communication
PPTX
Dependency Injection in .NET
PPTX
Asynchronous and Parallel Programming in .NET
PPTX
Networking Programming
PPTX
Working with XML and JSON Serializing
PPTX
Building Windows Presentation Foundation (WPF) Application
PPTX
Course Introduction
PPTX
Building Windows Presentation Foundation (WPF) Application
PPTX
Course Introduction
0-Slot21-22-Strings.pdf
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot14-15-16-Libraries.pdf
0-Slot13-Programming-With-Menu.pdf
0-Slot11-12-Pointers.pdf
0-Slot08-09-10-Module-Functions.pdf
0-Slot05-06-07-Basic-Logics.pdf
0-Slot02-Introduction-to-PFC.pdf
Intro-InstallingTool-FirstProgram
Background Tasks with Worker Service
Real-Time Communication
Dependency Injection in .NET
Asynchronous and Parallel Programming in .NET
Networking Programming
Working with XML and JSON Serializing
Building Windows Presentation Foundation (WPF) Application
Course Introduction
Building Windows Presentation Foundation (WPF) Application
Course Introduction
Ad

Recently uploaded (20)

PDF
Close Enough S3 E7 "Bridgette the Brain"
PDF
The-Art-of-Storytelling-in-Cinema (1).pdf
PPSX
Multiple scenes in a single painting.ppsx
PDF
Slide_BIS 2020 v2.pdf....................................
PPTX
DIMAYUGA ANDEA MAE P. BSED ENG 3-2 (CHAPTER 7).pptx
PDF
Love & Romance in Every Sparkle_ Discover the Magic of Diamond Painting.pdf
PPTX
Military history & Evolution of Armed Forces of the Philippines
PPTX
Lc 10hhjkhhjjkkkkjhhuiooopojjjoookjji.pptx
PDF
630895715-Romanesque-Architecture-ppt.pdf
PPTX
Socio ch 1 characteristics characteristics
PPTX
CPAR-ELEMENTS AND PRINCIPLE OF ARTS.pptx
PPTX
573393963-choose-your-own-adventure(2).pptx
PPTX
Physical Education and Health Q4-CO4-TARPAPEL
PPTX
Review1_Bollywood_Project analysis of bolywood trends from 1950s to 2025
PPTX
Brown and Beige Vintage Scrapbook Idea Board Presentation.pptx.pptx
PPTX
Copy of liver-cancer-case-study.pptx.pptx
PPTX
Theatre Studies - Powerpoint Entertainmn
PPTX
Presentation on tradtional textiles of kutch
PPTX
Neoclassical and Mystery Plays Entertain
PPTX
Green and Orange Illustration Understanding Climate Change Presentation.pptx
Close Enough S3 E7 "Bridgette the Brain"
The-Art-of-Storytelling-in-Cinema (1).pdf
Multiple scenes in a single painting.ppsx
Slide_BIS 2020 v2.pdf....................................
DIMAYUGA ANDEA MAE P. BSED ENG 3-2 (CHAPTER 7).pptx
Love & Romance in Every Sparkle_ Discover the Magic of Diamond Painting.pdf
Military history & Evolution of Armed Forces of the Philippines
Lc 10hhjkhhjjkkkkjhhuiooopojjjoookjji.pptx
630895715-Romanesque-Architecture-ppt.pdf
Socio ch 1 characteristics characteristics
CPAR-ELEMENTS AND PRINCIPLE OF ARTS.pptx
573393963-choose-your-own-adventure(2).pptx
Physical Education and Health Q4-CO4-TARPAPEL
Review1_Bollywood_Project analysis of bolywood trends from 1950s to 2025
Brown and Beige Vintage Scrapbook Idea Board Presentation.pptx.pptx
Copy of liver-cancer-case-study.pptx.pptx
Theatre Studies - Powerpoint Entertainmn
Presentation on tradtional textiles of kutch
Neoclassical and Mystery Plays Entertain
Green and Orange Illustration Understanding Climate Change Presentation.pptx

Building Websites Using ASP.NET Core Razor Pages

  • 1. Building Websites Using ASP.NET Core Razor Pages
  • 2. 2 ◆ Overview ASP.NET Core Razor Pages ◆ Introduce Razor Page files and Razor syntax ◆ Work with Page Models (Handler Methods, ViewData, Action Results) ◆ Understand Tag Helpers in Razor Pages ◆ Understand and work with View Components ◆ Apply Routing and URLs in Razor Pages ◆ Apply and configure the Startup with Razor Pages ◆ Validate input data with Validation and Model Binding in Razor Pages ◆ Understand and work with State Management in Razor Pages ◆ Scaffolding for Razor Pages ◆ Demo 08/21/21 Objectives
  • 3. 08/21/21 3 ASP.NET Core Razor Pages - 1 ◆ ASP.NET Razor Pages is a server-side, page-focused framework that enables building dynamic, data-driven web sites with clean separation of concerns. ◆ Part of the ASP.NET Core web development framework from Microsoft, Razor Pages supports cross platform development and can be deployed to Windows, Unix and Mac operating systems. ◆ The Razor Pages framework is lightweight and very flexible. ◆ It provides the developer with full control over rendered HTML. ◆ Razor Pages is the recommended framework for cross-platform server-side HTML generation.
  • 4. 08/21/21 4 ASP.NET Core Razor Pages - 2 ◆ Razor Pages makes use of the popular C# programming language for server- side programming, and the easy-to-learn Razor templating syntax for embedding C# in HTML mark-up to generate content for browsers dynamically. ◆ Architecturally, Razor Pages is an implementation of the MVC pattern and encourages separation of concerns. ◆ Razor Pages is included within .NET Core from version 2.0 onwards, which is available as a free download as either an SDK or a Runtime.
  • 5. 08/21/21 5 Razor Pages ◆ Razor is a markup syntax for embedding server-based code into webpages. ◆ The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a .cshtml file extension. ◆ The default Razor language is HTML. Rendering HTML from Razor markup is no different than rendering HTML from an HTML file. HTML markup in .cshtml ◆ Razor files is rendered by the server unchanged. ◆ Different types of ASP.NET Razor ◆ Razor Page (Single Page Model) – Demo1.cshtml ◆ Razor Page (with Page Model) – Demo2.cshtml + Demo2.cshtml.cs ◆ Razor with MVC
  • 6. 08/21/21 6 Razor Pages – Single File Approach ◆ The Razor code block is denoted by an opening @{ and is terminated with a closing }. The content within the block is standard C# code. ◆ Functions blocks
  • 7. 08/21/21 7 Razor Pages – PageModel Files ◆ Any code relating to the processing of user input or data should be placed in PageModel files, which share a one-to-one mapping with their associated content page. ◆ They even share the same file name, albeit with an additional .cs.
  • 8. 08/21/21 8 Different types of Razor files - 1 ◆ Razor files have a leading underscore (_) in their file name. These files are not intended to be browsable. ◆ The _Layout.cshtml file acts a template for all content pages that reference it. Consistent part of a site's design are declared in this file. ◆ 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. ◆ The _ViewImports.cshtml file provides a mechanism to make directives available to Razor pages globally so that you don't have to add them to pages individually.
  • 9. 08/21/21 9 Different types of Razor files - 2 ◆ Partial Pages or Views are Razor files containing snippets of HTML and server- side code to be included in any number of pages or layouts. ◆ Partial pages can be used to break up complex pages into smaller units, thereby reducing the complexity and allowing teams to work on different units concurrently. ◆ Partial pages are cshtml files that do not take part in routing. Rendering Partial Pages: ◆ <partial name="_MenuPartial" /> ◆ @Html.Partial("_MenuPartial") ◆ @{ Html.RenderPartial("_MenuPartial"); } ◆
  • 10. 08/21/21 10 Different types of Razor files - 3 ◆ The layout page acts as a template for all pages that reference it. _SubLayout1.cshtml _MasterLayout.cshtml
  • 11. 08/21/21 11 Different types of Razor files - 4 ◆ _ViewImports.cshtml file provides a mechanism to centralize directives that apply to Razor pages. ◆ The default Razor Pages template includes a _ViewImports.cshtml file in the Pages folder - the root folder for Razor pages. ◆ The _ViewImports.cshtml file supports the following directives: ◆ @addTagHelper, @removeTagHelper, @tagHelperPrefix ◆ @inherits, @namespace ◆ @inject, @model, @using
  • 12. 08/21/21 12 Razor Syntax ◆ A Razor content page acts as a template for generating HTML. The typical content page includes static HTML, tag helpers that emit HTML dynamically, and C# code. ◆ The C# code is embedded within the static content and tag helpers according to a set of rules, or syntax. ◆ All code blocks must appear within @{ ... C# code } brackets. ◆ Comments within a code block can be denoted by two forward slashes //. Alternatively, you can use /*...*/ or @*...*@.
  • 13. 08/21/21 13 The Razor Pages PageModel - 1 ◆ The main purpose of the Razor Pages PageModel class is to provide clear separation between the UI layer (the .cshtml view file) and processing logic for the page. There are a number of reasons why this separation is beneficial: ◆ It reduces the complexity of the UI layer making it easier to maintain. ◆ It facilitates automated unit testing. ◆ It enables greater flexibility for teams in that one member can work on the view while another can work on the processing logic. ◆ It encourages smaller, reusable units of code for specific purposes, which aids maintenance and scalability.
  • 14. 08/21/21 14 The Razor Pages PageModel - 2 ◆ The PageModel class is a combination of a Controller and a ViewModel. ◆ Controllers feature in a number of design and architectural patterns concerned with the presentation layer of an application. They are most commonly found in the Model-View-Controller (MVC) pattern, where the controller can be implemented as a Front Controller or a Page Controller. ◆ A front controller is defined as "a controller that handles all requests for a website". A page controller is "an object that handles a request for a specific page or action on a website". A Razor PageModel class is an implementation of the Page Controller pattern. ◆ The Page Controller pattern is characterized by the fact that there is a one-to- one mapping between pages and their controllers.
  • 15. 08/21/21 15 The Razor Pages PageModel - 3 ◆ A View Model is an implementation of the Presentation Model design pattern. ◆ It is a self-contained class that represents the data and behaviour of a specific "view" or page. The view model pattern is used extensively in MVC application development, where it mainly represents data, but typically little behaviour. ◆ In Razor Pages, the PageModel is also the view model. ◆ Razor Pages is sometimes described as implementing the MVVM (Model, View ViewModel) pattern. It doesn't. The MVVM pattern is applied to applications where the presentation and model share the same layer.
  • 16. 08/21/21 16 The Razor Pages PageModel - 4 ◆ The following code shows the content that is generated for each file when you use the Razor Page (with page model) option to add a new page to a Razor Pages application Index1.cshtml Index1.cshtml.cs
  • 17. 08/21/21 17 Handler Methods in Razor Pages - 1 ◆ Handler methods in Razor Pages are methods that are automatically executed as a result of a request. The Razor Pages framework uses a naming convention to select the appropriate handler method to execute. ◆ The name of the method, which is prefixed with "On": OnGet(), OnPost(), OnPut() etc. ◆ Handler methods also have optional asynchronous equivalents: OnPostAsync(), OnGetAsync() etc (methods that contain asynchronous code). ◆ As far as the Razor Pages framework is concerned, OnGet and OnGetAsync are the same handler.
  • 18. 08/21/21 18 Working With ViewData in Razor Pages - 1 ◆ ViewData is a container for data to be passed from the PageModel to the content page. ◆ ViewData is a dictionary of objects with a string-based key.
  • 19. 08/21/21 19 Working With ViewData in Razor Pages - 2 ◆ ViewData Attribute ◆ ViewBag is a wrapper around the ViewData dictionary and provides an alternative way to access ViewData contents within ASP.NET Core MVC controllers using dynamic properties instead of string-based indexes.
  • 20. 08/21/21 20 Action Results in Razor Pages - 1 ◆ Action results in Razor Pages are commonly used as the return type of handler methods and are responsible for generating responses and appropriate status codes. ◆ Action results implement either the abstract Microsoft.AspNetCore.Mvc.ActionResult class, or the Microsoft.AspNetCore.Mvc.IActionResult interface.
  • 21. 08/21/21 21 Action Results in Razor Pages - 2 ◆ ASP.NET Core includes more than three dozen ActionResult classes covering a wide range of needs, including but not limited to executing and returning the content of a Razor page, returning the content of a file, redirecting to another resource or simply returning a specific HTTP status code.
  • 22. 08/21/21 22 Tag Helpers - 1 ◆ Tag helpers are reusable components for automating the generation of HTML in Razor Pages. ◆ Tag helpers target specific HTML tags. The ASP.NET Core framework includes a number of predefined tag helpers targeting many commonly used HTML elements as well as some custom tags: ◆ Anchor tag helper, Cache tag helper, Environment tag helper, ◆ Form Action tag helper, Form tag helper, Image tag helper, ◆ Input tag helper, Label tag helper, Link tag helper, Option tag helper ◆ Partial tag helper, Script tag helper, Select tag helper ◆ Textarea tag helper, Validation tag helper, Validation Summary tag helper
  • 23. 08/21/21 23 Tag Helpers - 2 ◆ The Tag helpers used in Razor Pages were introduced as part of ASP.NET MVC Core and are found in the Microsoft.AspNetCore.Mvc.TagHelpers package which is included as part of the Microsoft.AspNetCore.All meta- package. ◆ Enabling Tag Helpers ◆ @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ◆ @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" ◆ Selective tag processing - Use the @addTagHelper and @removeTagHelper directives to opt in or opt out of ◆ @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" ◆ @removeTagHelper "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers"
  • 24. 08/21/21 24 Tag Helpers - 3 ◆ The Input tag helper generates appropriate name and id attribute values based on the PageModel property that is assigned to it. ◆ It will also generate an appropriate value for the type attribute, based on the property's meta data. The tag helper will also emit attributes that provide support for unobtrusive client-side validation. ◆ Type attribute based on data annotations
  • 25. 08/21/21 25 Tag Helpers - 4 1 2 3 4 Code generation
  • 26. 08/21/21 26 View Components in Razor Pages - 1 ◆ View Components perform a similar role to Tag Helpers and Partial Pages. ◆ View components are recommended instead of partial pages or tag helpers whenever any form of logic is required to obtain data for inclusion in the resulting HTML snippet, specifically calls to an external resource such as a file, database or web service. ◆ View components also lend themselves to unit testing. ◆ View components are particularly useful for data-driven features in a layout page where there is no related page model or controller class.
  • 27. 08/21/21 27 View Components in Razor Pages - 2 ◆ View components consist of a class file and a .cshtml view file. The class file contains the logic for generating the model. It can be thought of as a mini- controller, just as the Razor PageModel file is considered to be a controller. The view file contains the template used to generate the HTML to be plugged in to the page that hosts the view component. ◆ The class file must conform to the following rules: 1. It must derive from the ViewComponent class 2. It must have "ViewComponent" as a suffix to the class name or it must be decorated with the [ViewComponent] attribute 3. It must implement a method named Invoke with a return type of IViewComponentResult
  • 28. 08/21/21 28 Razor Pages Routing ◆ Routing is the system that matches URLs to Razor pages (matching URLs to file paths, starting from the root Razor Pages folder) ◆ When a Razor Pages application starts up, a collection of Attribute Routes is constructed, using the file and folder paths rooted in the Pages folder as the basis for each route's template. ◆ Index.cshtml - you can access Index.cshtml by browsing to both http://yourdomain.com/ and http://yourdomain.com/Index. ◆ If you create a folder named Demo and add a file named Index.cshtml to it, a further two routes will be defined with the following templates: "Demo", "Demo/Index"
  • 29. 08/21/21 29 The Startup Class - 1 ◆ ASP.NET Core makes extensive use of dependency injection (DI) - a technique that facilitates loose coupling of code. Components, or "services" are represented as abstractions, typically interfaces, as you have already seen in the Configure method with IApplicationBuilder. ◆ The primary purpose of the ConfigureServices method is as a place to register implementation types for services that are needed by the application. It is also used to configure any options related to those services. ◆ If it has been added to the Startup class, the ConfigureServices method is called before the Configure method. That makes sense, because the Configure method may attempt to reference services which need to be registered beforehand so that they can be resolved.
  • 30. 08/21/21 30 The Startup Class – 2 ◆ This is the case with the default template where Razor Pages is registered: ◆ If you want to configure the root folder for Razor Pages to be something other than the default Pages, this is where you would do that
  • 31. 08/21/21 31 Configuration In Razor Pages - 1 ◆ ASP.NET Core includes an API for managing configuration settings needed by the application which includes a number of providers for retrieving data in a variety of different formats. ◆ Configuration is set up as part of the WebHost.CreateDefaultBuilder method called in Program.cs, the entry point to the application. Various key/value stores are added to configuration by default ◆ appsettings.json ◆ User Secrets (if the environment is Development) ◆ Environment variables ◆ Command line arguments
  • 32. 08/21/21 32 Configuration In Razor Pages - 2 ◆ The appsettings.json file includes a section that configures logging for the application.
  • 33. 08/21/21 33 Configuration In Razor Pages - 3 ◆ The IConfiguration object enables you to access configuration settings in a variety of ways once it has been injected into your PageModel's constructor. ◆ Add a using directive for Microsoft.Extensions.Configuration to the PageModel class file. ◆ The Configuration class includes a convenience method for retrieving connection strings: ◆ var conn = Configuration.GetConnectionString("DefaultConnection");
  • 34. 08/21/21 34 Configuration In Razor Pages - 4 ◆ Configuring your Razor Pages site to run under HTTPS ◆ Running a site under HTTPS used to be something that only big online merchants worried about. ◆ The RequireHttps attribute is an authorization filter whose role is to confirm that requests are received over HTTPS. If the request was not made over HTTPS, the client will be redirected to the HTTPS version of the request URI if the GET method was used. Non-HTTPS requests made using any other verb (e.g. POST) will receive a 403 Forbidden result.
  • 35. 08/21/21 35 Dependency Injection in Razor Pages ◆ Dependency Injection (DI) is a technique that promotes loose coupling of software through separation of concerns. ◆ In the context of a Razor Pages application, DI encourages you to develop discrete components for specific tasks, which are then injected into classes that need to use their functionality. ◆ This results in an application that is easier to maintain and test. ◆ Developers are advised to implement the SOLID principals of software design to ensure that their applications are robust and easier to maintain and extend. Another important guiding principal for developers is Don't Repeat Yourself (DRY), which states that should aim to reduce code repetition wherever possible.
  • 36. 08/21/21 36 Using Forms in Razor Pages - 1 ◆ Forms are used for transferring data from the browser to the web server for further processing, such as saving it to a database, constructing an email, or simply subjecting the data to some kind of algorithm and then displaying the result. ◆ The HTML <form> element is used to create a form on a web page. The form element has a number of attributes, the most commonly used of which are method and action. The method attribute determines the HTTP verb to use when the form is submitted. ◆ By default, the GET verb is used and the form values are appended to the receiving page's URL as query string values. If the action attribute is omitted, the form will be submitted to the current URL i.e. the page that the form is in.
  • 37. 08/21/21 37 Using Forms in Razor Pages - 2 ◆ Access the user input. User input is only available to server-side code if the form control has a value applied to the name attribute. There are several ways to reference posted form values: ◆ Accessing the Request.Form collection via a string-based index, using the name attribute of the form control as the index value. ◆ Leveraging Model Binding to map form fields to handler method parameters. ◆ Leveraging Model Binding to map form fields to public properties on a PageModel class.
  • 38. 08/21/21 38 Using Forms in Razor Pages - 3 ◆ Leveraging Model Binding to map form fields to handler method parameters. ◆ Leveraging Model Binding to map form fields to public properties on a PageModel class.
  • 39. 08/21/21 39 Validating User Input in Razor Pages – 1 ◆ Validate user input in two places in a web application: in the browser using client-side script or the browser's in-built data type validation; and on the server. ◆ The MVC framework, on which Razor Pages is built, includes a robust validation framework that works against inbound model properties on the client- side and on the server. ◆ The key players in the input validation framework are: ◆ DataAnnotation Attributes, Tag Helpers ◆ jQuery Unobtrusive Validation ◆ ModelState ◆ Route Constraints
  • 40. 08/21/21 40 Validating User Input in Razor Pages – 2 ◆ The primary building block of the validation framework is a set of attributes that inherit from ValidationAttribute. ◆ Most of these attributes reside in the System.ComponentMo del.DataAnnotations namespace.
  • 41. 08/21/21 41 Validating User Input in Razor Pages – 3 ◆ An example of DataAnnotation attributes
  • 42. 08/21/21 42 Validating User Input in Razor Pages – 4 ◆ Client-side validation support is provided by the jQuery Unobtrusive Validation library, developed by Microsoft. ◆ Must include jQuery Unobtrusive Validation within the page containing the form for client side validation to work. This is most easily accomplished by the inclusion of the _ValidationScriptsPartial.cshtml file (located in the Shared folder) within the page
  • 43. 08/21/21 43 Validating User Input in Razor Pages – 5 ◆ Because it is so easy to circumvent client-side validation, server-side validation is included as part of the ASP.NET Core validation framework. ◆ Once property values have been bound, the framework looks for all validation attributes on those properties and executes them. ◆ Any failures result in an entry being added to a ModelStateDictionary. This is made available in the PageModel class via ModelState, which has a property named IsValid that returns false if any of the validation tests fail.
  • 44. 08/21/21 44 Model Binding - 1 ◆ Model Binding in Razor Pages is the process that takes values from HTTP requests and maps them to handler method parameters or PageModel properties. ◆ Model binding reduces the need for the developer to manually extract values from the request and then assign them, one by one, to variables or properties for later processing. ◆ This work is repetitive, tedious and error prone, mainly because request values are usually only exposed via string-based indexes. ◆ Model binding approaches: ◆ Binding posted form values to Handler Method parameters ◆ Binding posted form values to PageModel properties
  • 45. 08/21/21 45 Model Binding - 2 ◆ Binding posted form values to Handler Method parameters ◆ The parameters are named after the form fields, and given an appropriate type for the expected data. To see this approach in action, remove the assignment code in the OnPost handler method and add two parameters to the method ◆ When the form is posted, the Razor Pages framework calls the OnPost method and sees that it has two parameters.
  • 46. 08/21/21 46 Model Binding - 3 ◆ Binding posted form values to PageModel properties ◆ This approach is more suitable if you need to access the values outside of the handler method (for display on the page or binding to tag helpers), or if you prefer to work in a strongly typed manner within the Razor content page. ◆ This approach involves adding public properties to the PageModel (or to a @functions block if you don't want to use the PageModel approach) and then decorating them with the BindProperty attribute.
  • 47. 08/21/21 47 Model Binding - 4 ◆ Binding posted form values to PageModel properties (contd.)
  • 48. 08/21/21 48 State Management in Razor Pages - 1 ◆ Managing state in Razor Pages is the process of retaining user or application- related data over the duration of a number of requests. ◆ Razor Pages, along with its underlying MVC framework provides a number of mechanisms for retaining information (or state) across requests, each with its benefits and drawbacks: ◆ Hidden Form Fields ◆ Query Strings ◆ Route Data ◆ Cookies ◆ TempData, Session Variables, Application Variables, Caching ◆
  • 49. 08/21/21 49 State Management in Razor Pages - 2 ◆ Session state is a mechanism that enables you to store and retrieve user specific values temporarily. These values can be stored for the duration of the visitor's session on your site. ◆ Session management in ASP.NET Core is included in the Microsoft.AspNetCore.All metapackage, but is not enabled by default. Must enable Session State in the Startup file.
  • 50. 08/21/21 State Management in Razor Pages - 3 ◆ Configuring Sessions ◆ Using Session Variables
  • 51. 08/21/21 State Management in Razor Pages - 4 ◆ ASP.NET Core uses cookies to tie multiple request together in a session. ◆ List of properties of Cookie
  • 52. 08/21/21 52 Working with AJAX in Razor Pages - 1 ◆ AJAX is a technique used for making requests from the browser to the server for various purposes such as the retrieval of assorted content including data, HTML, XML, posting form values and so on. ◆ Requests are initiated from client script (usually JavaScript) once the page has already been loaded in the browser. ◆ If you wanted to update parts of the page as a result of choices that the user made, those choices would have to be sent to the server as a form post and the page would be regenerated on the web server in its entirety. ◆ The use of AJAX in a web page eliminates this stop-start approach to working in a web page.
  • 53. 08/21/21 53 Working with AJAX in Razor Pages - 2 1 2
  • 54. 08/21/21 54 Working with AJAX in Razor Pages - 3 3 4 5 6
  • 55. 08/21/21 55 Working with AJAX in Razor Pages - 3 7
  • 56. 08/21/21 56 Scaffolding Razor Pages ◆ Scaffolding in ASP.NET Core is a technique used to generate code at design time to support a number of common application scenarios when working with Entity Framework Core. ◆ The code generation tool is available as a Nuget package.
  • 58. 08/21/21 58 Demo 1. ◆ Step 01. Create ASP.NET Core Web App ◆ Step 02. Using Model Binding in Razor Pages to takes values from HTTP requests and maps them to handler method parameters or PageModel properties. ◆ Step 03. Create custom validation class ◆ Step 04. Create a Model using DataAnnotations and custom validation. ◆ Step 05. Create Razor Page (Empty) for form validation ◆ Step 06. Create Razor Page (Empty) for uploading files ◆ Step 07. Build and run Project.
  • 59. 08/21/21 59 Demo 1. ◆ Step 01. Create ASP.NET Core Web App (A project template for creating an ASP.NET application with example ASP.NET Razor Pages content.) ◆
  • 60. 08/21/21 60 Demo 1. ◆ Step 02. Using Model Binding in Razor Pages to takes values from HTTP requests and maps them to handler method parameters or PageModel properties.
  • 61. 08/21/21 61 Demo 1. ◆ Step 03. Create custom validation class
  • 62. 08/21/21 62 Demo 1. ◆ Step 04. Create a Model using DataAnnotations and custom validation.
  • 63. 08/21/21= 63 Demo 1. ◆ Step 05. Create Razor Page (Empty)
  • 64. 08/21/21 64 Demo 1. ◆ Step 05. (contd.)
  • 65. 08/21/21 65 Demo 1. ◆ Step 06. Create Razor Page (Empty) for uploading files
  • 67. 08/21/21 67 Demo 2. Razor Pages with Entity Framework ◆ Step 01. Create ASP.NET Core Web Application ◆ Step 02. Add model – Student, Course, Enrolment. ◆ Step 03. Manage NuGet packages for Solution/Project ◆ Step 04. Add Connection string (appsettings.json file) ◆ Step 05. Scaffold Student pages ◆ Step 06. Change the code on Startup.cs and Program.cs ◆ Step 07. Build and run Program.
  • 68. 08/21/21 68 Demo 2. Razor Pages with Entity Framework ◆ Manage NuGet packages for Solution/Project
  • 69. 08/21/21 69 Demo 2. Razor Pages with Entity Framework ◆ The scaffolding process will provide these files (creates Razor pages in the Pages/Students folder)
  • 70. 08/21/21 70 Demo 3 ◆ Razor Pages with Entity Framework CRUD (includes search, sorting and paging)
  • 71. Summary ◆ Concepts were introduced: ◆ Razor Page files and Razor syntax ◆ Page Models (Handler Methods, ViewData, Action Results) ◆ Tag Helpers ◆ View Components ◆ Routing and URLs ◆ Startup with Razor Pages and Configuration ◆ Validation and Model Binding ◆ State Management ◆ Scaffolding 71