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

Chapter 05 - Building Websites Using ASP.NET Core Razor Pages

The document provides an overview of ASP.NET Core Razor Pages, a server-side framework for building dynamic web applications with a focus on separation of concerns. It covers key concepts such as Razor syntax, Page Models, Tag Helpers, View Components, routing, and the use of dependency injection. The content is structured to guide developers in utilizing Razor Pages effectively for web development.

Uploaded by

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

Chapter 05 - Building Websites Using ASP.NET Core Razor Pages

The document provides an overview of ASP.NET Core Razor Pages, a server-side framework for building dynamic web applications with a focus on separation of concerns. It covers key concepts such as Razor syntax, Page Models, Tag Helpers, View Components, routing, and the use of dependency injection. The content is structured to guide developers in utilizing Razor Pages effectively for web development.

Uploaded by

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

Building Websites Using ASP.

NET
Core Razor Pages
Objectives

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
04/24/2025 2
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.

04/24/2025 3
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.

04/24/2025 4
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

04/24/2025 5
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

04/24/2025 6
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.

04/24/2025 7
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.

04/24/2025 8
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"); }

04/24/2025 9
Different types of Razor files - 3

The layout page acts as a template for all pages that reference it.
_MasterLayout.cshtml _SubLayout1.cshtml

04/24/2025 10
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

04/24/2025 11
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 @*...*@.

04/24/2025 12
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.

04/24/2025 13
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.
04/24/2025 14
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.

04/24/2025 15
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.cs
Index1.cshtml

04/24/2025 16
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.
04/24/2025 17
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.

04/24/2025 18
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.

04/24/2025 19
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.

04/24/2025 20
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.

04/24/2025 21
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
04/24/2025 22
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"
04/24/2025 23
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

04/24/2025 24
2
Tag Helpers - 4 Code generation
1
4

04/24/2025 25
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.

04/24/2025 26
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
04/24/2025 27
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"

04/24/2025 28
The Program.cs Class - 1

ASP.NET Core makes extensive use of dependency injection (DI) - a technique
that facilitates loose coupling of code.
Initializes a new instance of the
WebApplicationBuilder class. This is the starting
point for configuring the application.

Key Components Initialized:


• Configuration: Sets up app configuration (e.g.,
reading from appsettings.json, environment
variables, etc.).
• Logging: Sets up logging providers.
• Services: Registers services into the
Dependency Injection (DI) container.

04/24/2025 29
The Program.cs Class - 2

Adds Razor Pages services to the DI container.

Registers services for Razor Pages to function,


including support for MVC-style patterns, routing,
and Razor compilation.

Constructs the WebApplication instance based on


the configured builder. This is the application that
will handle incoming HTTP requests.

04/24/2025 30
The Program.cs Class - 3
• The middleware pipeline handles how HTTP
requests are processed and responses are
generated.
o Environment-Specific Error Handling
o Serving Static Files
o Enable Routing
o Authorization Middleware

• Mapping Razor Pages


• Running the Application

04/24/2025 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
04/24/2025 32
Configuration In Razor Pages - 2

The appsettings.json file includes
a section that configures logging
for the application.

04/24/2025 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");

04/24/2025 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.

04/24/2025 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.
04/24/2025 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.
04/24/2025 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.
04/24/2025 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.

04/24/2025 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
04/24/2025 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.

04/24/2025 41
Validating User Input in Razor Pages – 3

An example of DataAnnotation attributes

04/24/2025 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

04/24/2025 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.
04/24/2025 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
04/24/2025 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.

04/24/2025 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.

04/24/2025 47
Model Binding - 4

Binding posted form values to PageModel properties (contd.)

04/24/2025 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

04/24/2025 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.

04/24/2025 50
State Management in Razor Pages - 3

Configuring Sessions


Using Session Variables

04/24/2025
State Management in Razor Pages - 4

ASP.NET Core uses cookies to tie multiple
request together in a session.


List of properties of Cookie

04/24/2025
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.

04/24/2025 53
Working with AJAX in Razor Pages - 2
1 2

04/24/2025 54
Working with AJAX in Razor Pages - 3
3 4

04/24/2025 55
Working with AJAX in Razor Pages - 3
7

04/24/2025 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.

04/24/2025 57
Razor Pages Demo
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.

04/24/2025 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.)

04/24/2025 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.

04/24/2025 61
Demo 1.

Step 03. Create
custom validation class

04/24/2025 62
Demo 1.

Step 04. Create a
Model using
DataAnnotations and
custom validation.

04/24/2025 63
Demo 1.

Step 05. Create Razor Page (Empty)

04/24/2025 64
Demo 1.

Step 05. (contd.)

04/24/2025 65
Demo 1.

Step 06. Create Razor Page
(Empty) for uploading files

04/24/2025 66
Demo 1.

04/24/2025 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.

04/24/2025 68
Demo 2. Razor Pages with Entity Framework

Manage NuGet packages for Solution/Project

04/24/2025 69
Demo 2. Razor Pages with Entity Framework

The scaffolding process will provide these files (creates Razor pages in the
Pages/Students folder)

04/24/2025 70
Demo 3

Razor Pages with Entity Framework CRUD (includes search, sorting and paging)

04/24/2025 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

72

You might also like