SlideShare a Scribd company logo
1 of 44
Download to read offline
Creating a website with Razor Pages
Instructor: MSc. Hoang Ngoc Long
Objective
§ Creating a website with Razor Pages
Agenda
§ Exploring a typical Razor Page
§ The MVC design pattern
§ Applying the MVC design pattern to Razor Pages
§ Adding Razor Pages to your application
§ MVC controllers in ASP.NET Core
§ Razor Pages and page handlers
An introduction to Razor Pages
§ The Razor Pages programming model was introduced in ASP.NET
Core 2.0 as a way to build server-side rendered “page-based”
websites.
§ It builds on top of the ASP.NET Core infrastructure to provide a
streamlined experience, using conventions where possible to reduce
the amount of boilerplate code and configuration required.
§ A page-based website is one in which the user browses between
multiple pages, enters data into forms, and generally consumes
content. This contrasts with applications like games or single-page
applications (SPAs), which are heavily interactive on the client side.
Exploring a typical Razor Page
§ A Razor Page for viewing all to-do items in a given category
Exploring a typical Razor Page
§ A Razor Page for viewing all to-do items in a given category
• The pattern of interactions in the Razor Page shows a common pattern.
• The page handler is the central controller for the Razor Page. It receives an input from the user (the
category method parameter), calls out to the “brains” of the application (the ToDoService) and
passes data (by exposing the Items property) to the Razor view, which generates the HTML
response.
The MVC design pattern
§ In web development, MVC is a common paradigm and is used in
frameworks such as Django, Rails, and Spring MVC. But as it’s such a
broad concept, you can find MVC in everything from mobile apps to
rich-client desktop applications.
§ The original MVC pattern has many different interpretations, each of
which focuses on a slightly different aspect of the pattern.
• For example, the original MVC design pattern was specified with rich-client graphical user
interface (GUI) apps in mind, rather than web applications, so it uses terminology and
paradigms associated with a GUI environment. Fundamentally, though, the pattern aims to
separate the management and manipulation of data from its visual representation.
The MVC design pattern
§ The Model-View-Controller (MVC) pattern has been around since the
1970s, originally created as a pattern for use in Smalltalk.
• The pattern has made a resurgence recently, with implementations in many different and
varied languages, including Java (Spring Framework), Ruby (Ruby on Rails), and .NET (ASP.NET
MVC)
§ Controller is centerpiece that decouples the Model and View
§ Control flow:
• User interaction event
• Controller handles event and converts it to a user action the Model can understand
• Model manages the behavior and data of the application domain
• The View interacts with the Controller and Model to generate a user interface
Client/Server vs MVC
Controller
Model
View
Client
-----------------------
Business Objects
Server
-----------------------
Business Objects
Data
MVC Observer Pattern
Controller
Model
View
The MVC design pattern
Figure shows how a
Razor Page handles
different aspects of a
request, all of which
combine to generate
the final response.
The MVC design pattern
§ Each component in the MVC design pattern is responsible for a
single aspect of the overall system, which, when combined, can be
used to generate a UI.
• Model — This is the data that needs to be displayed, the global state of the
application. It’s accessed via the ToDoService in above figure.
• View — The template that displays the data provided by the model.
• Controller — This updates the model and provides the data for display to the
view. This role is taken by the page handler in Razor Pages. This is the OnGet
method in above figure.
• The to-do list example considers MVC in terms of a web application using
Razor Pages, but a request could also be equivalent to the click of a button in
a desktop GUI application.
The MVC design pattern
In general, the order of events when an application responds to a user
interaction or request is as follows:
1) The controller (the Razor Page handler) receives the request.
2) Depending on the request, the controller either fetches the
requested data from the application model using injected services,
or it updates the data that makes up the model.
3) The controller selects a view to display and passes a representation
of the model to it.
4) The view uses the data contained in the model to generate the UI.
The MVC design pattern
§ Depending on the nature of the request, the controller may take a variety of
actions, but the key point is that the actions are undertaken using the application
model.
• Consider a request to view a product page for an e-commerce application. The controller would
receive the request and would know how to contact some product service that’s part of the
application model. This might fetch the details of the requested product from a database and
return them to the controller.
• Alternatively, imagine that a controller receives a request to add a product to the user’s shopping
cart. The controller would receive the request and most likely would invoke a method on the
model to request that the product be added. The model would then update its internal
representation of the user’s cart, by adding, for example, a new row to a database table holding
the user’s data.
§ You can think of each Razor Page handler as a mini controller focused on a single
page. Every web request is another independent call to a controller that
orchestrates the response. Although there are many different controllers, the
handlers all interact with the same application model.
Applying the MVC design pattern to Razor Pages
§ ASP.NET Core implements
Razor Page endpoints using a
combination of
RoutingMiddleware and
EndpointMiddleware
Directing a Request to a Razor Page and Building a
Binding Model
§ Routing takes the headers and path of the request, for example
/category/Simple, and maps it against a preregistered list of
patterns. These patterns each match a path to a single Razor Page
and page handler.
§ Once a page handler is selected, the binding model (if applicable) is
generated. This model is built based on the incoming request, the
properties of the PageModel marked for binding, and the method
parameters required by the page handler
§ A binding model is normally one or more standard C# objects, with
properties that map to the requested data.
Directing A Request To A Razor Page And Building A
Binding Model
§ Routing a request to a
controller and building a
binding model. A request
to the /category/Simple
URL results in the
CategoryModel.OnGet
page handler being
executed, passing in a
populated binding model,
category.
Executing A Handler Using The Application Model
§ The role of the page handler as the controller in the MVC pattern is to coordinate
the generation of a response to the request it’s handling
• Validate that the data contained in the binding model provided is valid for the request
• Invoke the appropriate actions on the application model using services
• Select an appropriate response to generate based on the response from the application model
When executed, an action will
invoke the appropriate methods in
the application model
The domain model encapsulates
complex business logic in a series of
classes that don’t depend on any
infrastructure and can be easily
tested..
Building HTML Using The View Model
§ A view model in the MVC pattern is all the data required by the view
to render a UI. It’s typically some transformation of the data
contained in the application model, plus extra information required
to render the page, such as the page’s title.
§ The term view model is used extensively in ASP.NET Core MVC,
where it typically refers to a single object that is passed to the Razor
view to render. However, with Razor Pages, the Razor view can access
the Razor Page’s page model class directly.
§ The Razor Page PageModel typically acts as the view model in Razor
Pages, with the data required by the Razor view exposed via
properties.
Building HTML Using The View Model
The page handler builds a view model by setting properties on the PageModel.
It’s the view that generates the response.
Putting It All
Together: A Complete
Razor Page Request
Let’s put it all together from
request to response. The figure
shows how the steps combine to
handle the request to display the
list of to-do items for the
“Simple” category.
Adding Razor Pages to your application
§ The MVC infrastructure, whether used by Razor Pages or MVC/API
controllers, is a foundational aspect of all but the simplest ASP.NET
Core applications, so virtually all templates include it configured by
default in some way.
§ Here’s how you add Razor Pages to your application:
1) In Visual Studio 2019, choose File > New > Project or choose Create a New Project from the
splash screen.
2) From the list of templates, choose ASP.NET Core Web Application, ensuring you select the
C# language template
3) On the next screen, enter a project name, location, and solution name, and click Create.
4) On the following screen, create a basic template without MVC or Razor Pages by selecting
the ASP.NET Core Empty project template in Visual Studio. You can create a similar empty
project using the .NET CLI with the dotnet new web command.
Adding Razor Pages to your application
Adding Razor Pages to your application
5) Add the necessary Razor Page services (shown in bold) in your Startup.cs file’s
ConfigureServices method:
6) Replace the existing basic endpoint configured in the EndpointMiddleware at the end of your
middleware pipeline with the MapRazorPages() extension method. For simplicity, also remove
the existing error handler middleware from the Configure method of Startup.cs for now:
Adding Razor Pages to your application
7) Right-click your project in Solution Explorer and choose Add > New Folder to add a new
folder to the root of your project. Name the new folder “Pages”.
8) Right-click the new pages folder and choose Add > Razor Page
Adding Razor Pages to your application
9) On the following page, select Razor Page – Empty and click Add. In the following dialog box,
name your page Index.cshtml
Adding Razor Pages to your application
10) After Visual Studio has finished generating the file, open the Index.cshtml file, and update the
HTML to say Hello World! by replacing the file contents with the following:
Adding Razor Pages to your application
§ Once you’ve completed all these steps, you should be able to restore, build, and
run your application.
• You can run your project by pressing F5 from within Visual Studio (or by calling dotnet run at
the command line from the project folder). This will restore any referenced NuGet packages,
build your project, and start your application. Visual Studio will automatically open a browser
window to access your application’s home page.
MVC controllers in ASP.NET Core
§ In previous section we looked at the MVC design pattern, and at
how it applies to Razor Pages in ASP.NET Core. Perhaps
unsurprisingly, you can use the ASP.NET Core MVC framework in
almost exactly the same way.
• Use Razor Pages for server-side rendered applications, and use the MVC framework for
building Web APIs.
§ Instead of a PageModel and page handler, MVC uses the concept of
controllers and action methods. These are almost directly analogous
to their Razor Pages counterparts.
§ An action (or action method) is a method that runs in response to a
request. An MVC controller is a class that contains a number of
logically grouped action methods.
MVC controllers in ASP.NET Core
A complete MVC
controller request for a
category. The MVC
controller pattern is
almost identical to that
of Razor Pages. The
controller is equivalent
to a Razor Page, and
the action is equivalent
to a page handler.
An MVC controller for viewing all to-do items in a given category
Comparing the folder
structure for an MVC
project to the folder
structure for a Razor
Pages project
The benefits of Razor Pages
The benefits of Razor Pages
§ The MVC approach traditionally groups classes by type (controller, view, view
model), while the Razor Page approach groups by function — everything
related to a specific page is co-located.
• Using Razor Pages means much less scrolling up and down between the controller, views, and
view model folders whenever you’re working on a particular page. Everything you need is
found in two files, the .cshtml Razor view and the .cshtml.cs PageModel file.
§ Each Razor Page is cohesive for a particular feature, such as displaying a to-do
item. MVC controllers contain action methods that handle multiple different
features for a more abstract concept, such as all the features related to to-do
items.
§ The benefits of using Razor Pages are particularly noticeable when you have
“content” websites, such as marketing websites, where you’re mostly displaying
static data, and there’s no real logic.
When to choose MVC controllers over Razor Pages
§ When you don’t want to render views — Razor Pages are best for page-based
applications, where you’re rendering a view for the user. If you’re building a
Web API, you should use MVC controllers instead.
§ When you’re converting an existing MVC application to ASP.NET Core — If you
already have an ASP.NET application that uses MVC, it’s probably not worth
converting your existing MVC controllers to Razor Pages.
§ When you’re doing a lot of partial page updates — It’s possible to use JavaScript
in an application to avoid doing full page navigations by only updating part of
the page at a time. This approach, halfway between fully server-side rendered
and a client-side application may be easier to achieve with MVC controllers than
Razor Pages.
When not to use Razor Pages or MVC controllers
§ If you’re building small, light-weight apps for the cloud, you might consider
using custom middleware directly or an alternative protocol like gRPC
• https://docs.microsoft.com/aspnet/core/grpc
§ If you’re building an app with real-time functionality, you’ll probably want to
consider using WebSockets instead of traditional HTTP requests.
• ASP.NET Core SignalR can be used to add real-time functionality to your app by providing an abstraction over
WebSockets.
• SignalR also provides simple transport fallbacks and a remote procedure call (RPC) app model. For details, see the
documentation at https://docs.microsoft.com/aspnet/core/signalr
§ Another option available in ASP.NET Core 5.0 is Blazor.
• This framework allows you to build interactive client-side web applications by either leveraging the WebAssembly
standard to run .NET code directly in your browser, or by using a stateful model with SignalR.
• See the documentation for details, at https://docs.microsoft.com/aspnet/core/blazor/
Razor Pages and page handlers
§ In the MVC design pattern, the controller receives a request and is the entry
point for UI generation. For Razor Pages, the entry point is a page handler that
resides in a Razor Page’s PageModel. A page handler is a method that runs in
response to a request.
• By default, the path of a Razor Page on disk controls the URL path that the Razor Page
responds to. For example, a request to the URL /products/list corresponds to the Razor Page
at the path pages/Products/List.cshtml.
§ The responsibility of a page handler is generally threefold:
• Confirm that the incoming request is valid.
• Invoke the appropriate business logic corresponding to the incoming request.
• Choose the appropriate kind of response to return.
Razor Pages and page handlers
§ Page handlers typically return one of three things:
• A PageResult object —This causes the associated Razor view to generate an HTML response.
• Nothing (the handler returns void or Task) —This is the same as the previous case, causing the Razor
view to generate an HTML response.
• A RedirectToPageResult — This indicates that the user should be redirected to a different page in your
application.
§ It’s important to realize that a page handler doesn’t generate a response
directly; it selects the type of response and prepares the data for it.
• For example, returning a PageResult doesn’t generate any HTML at that point; it merely indicates that a
view should be rendered.
§ It’s also worth bearing in mind that page handlers should generally not be
performing business logic directly. Instead, they should call appropriate services
in the application model to handle requests.
• If a page handler receives a request to add a product to a user’s cart, it shouldn’t directly manipulate the
database or recalculate cart totals, for example. Instead, it should make a call to another class to handle
the details.
Accepting parameters to page handlers
§ The request may contain additional values from a variety of different
sources. They could be part of the URL, the query string, headers, or
the body of the request itself.
§ The process of extracting values from a request and converting them
to .NET types is called model binding.
§ ASP.NET Core can bind two different targets in Razor Pages:
• Method arguments — If a page handler has method arguments, the values from the request
are used to create the required parameters.
• Properties marked with a [BindProperty] attribute —Any properties marked with the attribute
will be bound.
§ Model-bound values can be simple types, such as strings and
integers, or they can be a complex type.
Example Razor Page handlers
Returning responses with ActionResults
§ It’s the IActionResult returned by a page handler that, when executed by the
Razor Pages infrastructure using the view engine, will generate the response
§ ASP.NET Core has many different types of IActionResult:
• PageResult — Generates an HTML view for an associated page in Razor Pages
• ViewResult — Generates an HTML view for a given Razor view when using MVC controllers
• RedirectToPageResult — Sends a 302 HTTP redirect response to automatically send a user to
another page
• RedirectResult — Sends a 302 HTTP redirect response to automatically send a user to a
specified URL (doesn’t have to be a Razor Page)
• FileResult — Returns a file as the response
• ContentResult — Returns a provided string as the response
• StatusCodeResult — Sends a raw HTTP status code as the response, optionally with associated
response body content
• NotFoundResult — Sends a raw 404 HTTP status code as the response
PageResult and
RedirectToPageResult
A typical POST,
REDIRECT, GET flow
through a website. A
user sends their
shopping basket to a
checkout page, which
validates its contents
and redirects to a
payment page without
the user having to
manually change the
URL.
NotFoundResult and StatusCodeResult
§ As well as HTML and redirect responses, you’ll occasionally need to send
specific HTTP status codes.
• If you request a page for viewing a product on an e-commerce application, and that product doesn’t exist, a 404 HTTP
status code is returned to the browser, and you’ll typically see a “Not found” web page.
• Razor Pages can achieve this behavior by returning a NotFoundResult, which will return a raw 404 HTTP status code.
• You could achieve a similar result using StatusCodeResult and setting the status code returned explicitly to 404.
• You can use the StatusCodePagesMiddleware to intercept this raw 404 status code after it’s been generated and
provide a user-friendly HTML response for it.
End of Lecture

More Related Content

Similar to Lecture 05 - Creating a website with Razor Pages.pdf

Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01
Jennie Gajjar
 
Mvc presentation
Mvc presentationMvc presentation
Mvc presentation
MaslowB
 

Similar to Lecture 05 - Creating a website with Razor Pages.pdf (20)

MVC
MVCMVC
MVC
 
Mvc
MvcMvc
Mvc
 
Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01
 
Mvc
MvcMvc
Mvc
 
Asp.net c# MVC-5 Training-Day-1 of Day-9
Asp.net c# MVC-5 Training-Day-1 of Day-9Asp.net c# MVC-5 Training-Day-1 of Day-9
Asp.net c# MVC-5 Training-Day-1 of Day-9
 
Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013Getting started with MVC 5 and Visual Studio 2013
Getting started with MVC 5 and Visual Studio 2013
 
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architecture
 
Technoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development servicesTechnoligent providing custom ASP.NET MVC development services
Technoligent providing custom ASP.NET MVC development services
 
Sitecore mvc
Sitecore mvcSitecore mvc
Sitecore mvc
 
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
 
Mvc presentation
Mvc presentationMvc presentation
Mvc presentation
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Aspnet mvc
Aspnet mvcAspnet mvc
Aspnet mvc
 
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
 
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
MVC Architecture: A Detailed Insight to the Modern Web Applications Developme...
 
MVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperMVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros Developer
 
Modern webtechnologies
Modern webtechnologiesModern webtechnologies
Modern webtechnologies
 
MVC 4
MVC 4MVC 4
MVC 4
 

More from Lê Thưởng

More from Lê Thưởng (11)

Lecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdfLecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdf
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Lecture 01 - WWW.pdf
Lecture 01 - WWW.pdfLecture 01 - WWW.pdf
Lecture 01 - WWW.pdf
 
Bài 4.pptx
Bài 4.pptxBài 4.pptx
Bài 4.pptx
 
Lady who sets out in haste.pptx
Lady who sets out in haste.pptxLady who sets out in haste.pptx
Lady who sets out in haste.pptx
 
mary nativity.pptx
mary nativity.pptxmary nativity.pptx
mary nativity.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Marial Prayer,.pptx
Marial  Prayer,.pptxMarial  Prayer,.pptx
Marial Prayer,.pptx
 
Bday Prayer.pptx
Bday Prayer.pptxBday Prayer.pptx
Bday Prayer.pptx
 
synthesis.pptx
synthesis.pptxsynthesis.pptx
synthesis.pptx
 
CHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.ppt
CHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.pptCHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.ppt
CHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.ppt
 

Recently uploaded

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

Lecture 05 - Creating a website with Razor Pages.pdf

  • 1. Creating a website with Razor Pages Instructor: MSc. Hoang Ngoc Long
  • 2. Objective § Creating a website with Razor Pages
  • 3. Agenda § Exploring a typical Razor Page § The MVC design pattern § Applying the MVC design pattern to Razor Pages § Adding Razor Pages to your application § MVC controllers in ASP.NET Core § Razor Pages and page handlers
  • 4. An introduction to Razor Pages § The Razor Pages programming model was introduced in ASP.NET Core 2.0 as a way to build server-side rendered “page-based” websites. § It builds on top of the ASP.NET Core infrastructure to provide a streamlined experience, using conventions where possible to reduce the amount of boilerplate code and configuration required. § A page-based website is one in which the user browses between multiple pages, enters data into forms, and generally consumes content. This contrasts with applications like games or single-page applications (SPAs), which are heavily interactive on the client side.
  • 5. Exploring a typical Razor Page § A Razor Page for viewing all to-do items in a given category
  • 6. Exploring a typical Razor Page § A Razor Page for viewing all to-do items in a given category • The pattern of interactions in the Razor Page shows a common pattern. • The page handler is the central controller for the Razor Page. It receives an input from the user (the category method parameter), calls out to the “brains” of the application (the ToDoService) and passes data (by exposing the Items property) to the Razor view, which generates the HTML response.
  • 7. The MVC design pattern § In web development, MVC is a common paradigm and is used in frameworks such as Django, Rails, and Spring MVC. But as it’s such a broad concept, you can find MVC in everything from mobile apps to rich-client desktop applications. § The original MVC pattern has many different interpretations, each of which focuses on a slightly different aspect of the pattern. • For example, the original MVC design pattern was specified with rich-client graphical user interface (GUI) apps in mind, rather than web applications, so it uses terminology and paradigms associated with a GUI environment. Fundamentally, though, the pattern aims to separate the management and manipulation of data from its visual representation.
  • 8. The MVC design pattern § The Model-View-Controller (MVC) pattern has been around since the 1970s, originally created as a pattern for use in Smalltalk. • The pattern has made a resurgence recently, with implementations in many different and varied languages, including Java (Spring Framework), Ruby (Ruby on Rails), and .NET (ASP.NET MVC) § Controller is centerpiece that decouples the Model and View § Control flow: • User interaction event • Controller handles event and converts it to a user action the Model can understand • Model manages the behavior and data of the application domain • The View interacts with the Controller and Model to generate a user interface
  • 9. Client/Server vs MVC Controller Model View Client ----------------------- Business Objects Server ----------------------- Business Objects Data
  • 11. The MVC design pattern Figure shows how a Razor Page handles different aspects of a request, all of which combine to generate the final response.
  • 12. The MVC design pattern § Each component in the MVC design pattern is responsible for a single aspect of the overall system, which, when combined, can be used to generate a UI. • Model — This is the data that needs to be displayed, the global state of the application. It’s accessed via the ToDoService in above figure. • View — The template that displays the data provided by the model. • Controller — This updates the model and provides the data for display to the view. This role is taken by the page handler in Razor Pages. This is the OnGet method in above figure. • The to-do list example considers MVC in terms of a web application using Razor Pages, but a request could also be equivalent to the click of a button in a desktop GUI application.
  • 13. The MVC design pattern In general, the order of events when an application responds to a user interaction or request is as follows: 1) The controller (the Razor Page handler) receives the request. 2) Depending on the request, the controller either fetches the requested data from the application model using injected services, or it updates the data that makes up the model. 3) The controller selects a view to display and passes a representation of the model to it. 4) The view uses the data contained in the model to generate the UI.
  • 14. The MVC design pattern § Depending on the nature of the request, the controller may take a variety of actions, but the key point is that the actions are undertaken using the application model. • Consider a request to view a product page for an e-commerce application. The controller would receive the request and would know how to contact some product service that’s part of the application model. This might fetch the details of the requested product from a database and return them to the controller. • Alternatively, imagine that a controller receives a request to add a product to the user’s shopping cart. The controller would receive the request and most likely would invoke a method on the model to request that the product be added. The model would then update its internal representation of the user’s cart, by adding, for example, a new row to a database table holding the user’s data. § You can think of each Razor Page handler as a mini controller focused on a single page. Every web request is another independent call to a controller that orchestrates the response. Although there are many different controllers, the handlers all interact with the same application model.
  • 15. Applying the MVC design pattern to Razor Pages § ASP.NET Core implements Razor Page endpoints using a combination of RoutingMiddleware and EndpointMiddleware
  • 16. Directing a Request to a Razor Page and Building a Binding Model § Routing takes the headers and path of the request, for example /category/Simple, and maps it against a preregistered list of patterns. These patterns each match a path to a single Razor Page and page handler. § Once a page handler is selected, the binding model (if applicable) is generated. This model is built based on the incoming request, the properties of the PageModel marked for binding, and the method parameters required by the page handler § A binding model is normally one or more standard C# objects, with properties that map to the requested data.
  • 17. Directing A Request To A Razor Page And Building A Binding Model § Routing a request to a controller and building a binding model. A request to the /category/Simple URL results in the CategoryModel.OnGet page handler being executed, passing in a populated binding model, category.
  • 18. Executing A Handler Using The Application Model § The role of the page handler as the controller in the MVC pattern is to coordinate the generation of a response to the request it’s handling • Validate that the data contained in the binding model provided is valid for the request • Invoke the appropriate actions on the application model using services • Select an appropriate response to generate based on the response from the application model When executed, an action will invoke the appropriate methods in the application model The domain model encapsulates complex business logic in a series of classes that don’t depend on any infrastructure and can be easily tested..
  • 19. Building HTML Using The View Model § A view model in the MVC pattern is all the data required by the view to render a UI. It’s typically some transformation of the data contained in the application model, plus extra information required to render the page, such as the page’s title. § The term view model is used extensively in ASP.NET Core MVC, where it typically refers to a single object that is passed to the Razor view to render. However, with Razor Pages, the Razor view can access the Razor Page’s page model class directly. § The Razor Page PageModel typically acts as the view model in Razor Pages, with the data required by the Razor view exposed via properties.
  • 20. Building HTML Using The View Model The page handler builds a view model by setting properties on the PageModel. It’s the view that generates the response.
  • 21. Putting It All Together: A Complete Razor Page Request Let’s put it all together from request to response. The figure shows how the steps combine to handle the request to display the list of to-do items for the “Simple” category.
  • 22. Adding Razor Pages to your application § The MVC infrastructure, whether used by Razor Pages or MVC/API controllers, is a foundational aspect of all but the simplest ASP.NET Core applications, so virtually all templates include it configured by default in some way. § Here’s how you add Razor Pages to your application: 1) In Visual Studio 2019, choose File > New > Project or choose Create a New Project from the splash screen. 2) From the list of templates, choose ASP.NET Core Web Application, ensuring you select the C# language template 3) On the next screen, enter a project name, location, and solution name, and click Create. 4) On the following screen, create a basic template without MVC or Razor Pages by selecting the ASP.NET Core Empty project template in Visual Studio. You can create a similar empty project using the .NET CLI with the dotnet new web command.
  • 23. Adding Razor Pages to your application
  • 24. Adding Razor Pages to your application 5) Add the necessary Razor Page services (shown in bold) in your Startup.cs file’s ConfigureServices method: 6) Replace the existing basic endpoint configured in the EndpointMiddleware at the end of your middleware pipeline with the MapRazorPages() extension method. For simplicity, also remove the existing error handler middleware from the Configure method of Startup.cs for now:
  • 25. Adding Razor Pages to your application 7) Right-click your project in Solution Explorer and choose Add > New Folder to add a new folder to the root of your project. Name the new folder “Pages”. 8) Right-click the new pages folder and choose Add > Razor Page
  • 26. Adding Razor Pages to your application 9) On the following page, select Razor Page – Empty and click Add. In the following dialog box, name your page Index.cshtml
  • 27. Adding Razor Pages to your application 10) After Visual Studio has finished generating the file, open the Index.cshtml file, and update the HTML to say Hello World! by replacing the file contents with the following:
  • 28. Adding Razor Pages to your application § Once you’ve completed all these steps, you should be able to restore, build, and run your application. • You can run your project by pressing F5 from within Visual Studio (or by calling dotnet run at the command line from the project folder). This will restore any referenced NuGet packages, build your project, and start your application. Visual Studio will automatically open a browser window to access your application’s home page.
  • 29. MVC controllers in ASP.NET Core § In previous section we looked at the MVC design pattern, and at how it applies to Razor Pages in ASP.NET Core. Perhaps unsurprisingly, you can use the ASP.NET Core MVC framework in almost exactly the same way. • Use Razor Pages for server-side rendered applications, and use the MVC framework for building Web APIs. § Instead of a PageModel and page handler, MVC uses the concept of controllers and action methods. These are almost directly analogous to their Razor Pages counterparts. § An action (or action method) is a method that runs in response to a request. An MVC controller is a class that contains a number of logically grouped action methods.
  • 30. MVC controllers in ASP.NET Core
  • 31. A complete MVC controller request for a category. The MVC controller pattern is almost identical to that of Razor Pages. The controller is equivalent to a Razor Page, and the action is equivalent to a page handler.
  • 32. An MVC controller for viewing all to-do items in a given category
  • 33. Comparing the folder structure for an MVC project to the folder structure for a Razor Pages project The benefits of Razor Pages
  • 34. The benefits of Razor Pages § The MVC approach traditionally groups classes by type (controller, view, view model), while the Razor Page approach groups by function — everything related to a specific page is co-located. • Using Razor Pages means much less scrolling up and down between the controller, views, and view model folders whenever you’re working on a particular page. Everything you need is found in two files, the .cshtml Razor view and the .cshtml.cs PageModel file. § Each Razor Page is cohesive for a particular feature, such as displaying a to-do item. MVC controllers contain action methods that handle multiple different features for a more abstract concept, such as all the features related to to-do items. § The benefits of using Razor Pages are particularly noticeable when you have “content” websites, such as marketing websites, where you’re mostly displaying static data, and there’s no real logic.
  • 35. When to choose MVC controllers over Razor Pages § When you don’t want to render views — Razor Pages are best for page-based applications, where you’re rendering a view for the user. If you’re building a Web API, you should use MVC controllers instead. § When you’re converting an existing MVC application to ASP.NET Core — If you already have an ASP.NET application that uses MVC, it’s probably not worth converting your existing MVC controllers to Razor Pages. § When you’re doing a lot of partial page updates — It’s possible to use JavaScript in an application to avoid doing full page navigations by only updating part of the page at a time. This approach, halfway between fully server-side rendered and a client-side application may be easier to achieve with MVC controllers than Razor Pages.
  • 36. When not to use Razor Pages or MVC controllers § If you’re building small, light-weight apps for the cloud, you might consider using custom middleware directly or an alternative protocol like gRPC • https://docs.microsoft.com/aspnet/core/grpc § If you’re building an app with real-time functionality, you’ll probably want to consider using WebSockets instead of traditional HTTP requests. • ASP.NET Core SignalR can be used to add real-time functionality to your app by providing an abstraction over WebSockets. • SignalR also provides simple transport fallbacks and a remote procedure call (RPC) app model. For details, see the documentation at https://docs.microsoft.com/aspnet/core/signalr § Another option available in ASP.NET Core 5.0 is Blazor. • This framework allows you to build interactive client-side web applications by either leveraging the WebAssembly standard to run .NET code directly in your browser, or by using a stateful model with SignalR. • See the documentation for details, at https://docs.microsoft.com/aspnet/core/blazor/
  • 37. Razor Pages and page handlers § In the MVC design pattern, the controller receives a request and is the entry point for UI generation. For Razor Pages, the entry point is a page handler that resides in a Razor Page’s PageModel. A page handler is a method that runs in response to a request. • By default, the path of a Razor Page on disk controls the URL path that the Razor Page responds to. For example, a request to the URL /products/list corresponds to the Razor Page at the path pages/Products/List.cshtml. § The responsibility of a page handler is generally threefold: • Confirm that the incoming request is valid. • Invoke the appropriate business logic corresponding to the incoming request. • Choose the appropriate kind of response to return.
  • 38. Razor Pages and page handlers § Page handlers typically return one of three things: • A PageResult object —This causes the associated Razor view to generate an HTML response. • Nothing (the handler returns void or Task) —This is the same as the previous case, causing the Razor view to generate an HTML response. • A RedirectToPageResult — This indicates that the user should be redirected to a different page in your application. § It’s important to realize that a page handler doesn’t generate a response directly; it selects the type of response and prepares the data for it. • For example, returning a PageResult doesn’t generate any HTML at that point; it merely indicates that a view should be rendered. § It’s also worth bearing in mind that page handlers should generally not be performing business logic directly. Instead, they should call appropriate services in the application model to handle requests. • If a page handler receives a request to add a product to a user’s cart, it shouldn’t directly manipulate the database or recalculate cart totals, for example. Instead, it should make a call to another class to handle the details.
  • 39. Accepting parameters to page handlers § The request may contain additional values from a variety of different sources. They could be part of the URL, the query string, headers, or the body of the request itself. § The process of extracting values from a request and converting them to .NET types is called model binding. § ASP.NET Core can bind two different targets in Razor Pages: • Method arguments — If a page handler has method arguments, the values from the request are used to create the required parameters. • Properties marked with a [BindProperty] attribute —Any properties marked with the attribute will be bound. § Model-bound values can be simple types, such as strings and integers, or they can be a complex type.
  • 40. Example Razor Page handlers
  • 41. Returning responses with ActionResults § It’s the IActionResult returned by a page handler that, when executed by the Razor Pages infrastructure using the view engine, will generate the response § ASP.NET Core has many different types of IActionResult: • PageResult — Generates an HTML view for an associated page in Razor Pages • ViewResult — Generates an HTML view for a given Razor view when using MVC controllers • RedirectToPageResult — Sends a 302 HTTP redirect response to automatically send a user to another page • RedirectResult — Sends a 302 HTTP redirect response to automatically send a user to a specified URL (doesn’t have to be a Razor Page) • FileResult — Returns a file as the response • ContentResult — Returns a provided string as the response • StatusCodeResult — Sends a raw HTTP status code as the response, optionally with associated response body content • NotFoundResult — Sends a raw 404 HTTP status code as the response
  • 42. PageResult and RedirectToPageResult A typical POST, REDIRECT, GET flow through a website. A user sends their shopping basket to a checkout page, which validates its contents and redirects to a payment page without the user having to manually change the URL.
  • 43. NotFoundResult and StatusCodeResult § As well as HTML and redirect responses, you’ll occasionally need to send specific HTTP status codes. • If you request a page for viewing a product on an e-commerce application, and that product doesn’t exist, a 404 HTTP status code is returned to the browser, and you’ll typically see a “Not found” web page. • Razor Pages can achieve this behavior by returning a NotFoundResult, which will return a raw 404 HTTP status code. • You could achieve a similar result using StatusCodeResult and setting the status code returned explicitly to 404. • You can use the StatusCodePagesMiddleware to intercept this raw 404 status code after it’s been generated and provide a user-friendly HTML response for it.