際際滷

際際滷Share a Scribd company logo
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 its 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. Its 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 thats 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 users 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 users cart, by adding, for example, a new row to a database table holding
the users 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 its 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 dont 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. Its typically some transformation of the data
contained in the application model, plus extra information required
to render the page, such as the pages 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 Pages 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.
Its the view that generates the response.
Putting It All
Together: A Complete
Razor Page Request
Lets 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.
則 Heres 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 files
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 youve 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 applications 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 youre 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 youre mostly displaying
static data, and theres no real logic.
When to choose MVC controllers over Razor Pages
則 When you dont want to render views  Razor Pages are best for page-based
applications, where youre rendering a view for the user. If youre building a
Web API, you should use MVC controllers instead.
則 When youre converting an existing MVC application to ASP.NET Core  If you
already have an ASP.NET application that uses MVC, its probably not worth
converting your existing MVC controllers to Razor Pages.
則 When youre doing a lot of partial page updates  Its 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 youre 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 youre building an app with real-time functionality, youll 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 Pages 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.
則 Its important to realize that a page handler doesnt generate a response
directly; it selects the type of response and prepares the data for it.
 For example, returning a PageResult doesnt generate any HTML at that point; it merely indicates that a
view should be rendered.
則 Its 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 users cart, it shouldnt 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
則 Its 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 (doesnt 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, youll 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 doesnt exist, a 404 HTTP
status code is returned to the browser, and youll 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 its 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 (20)

Programming is Fun with ASP.NET MVC
Programming is Fun with ASP.NET MVCProgramming is Fun with ASP.NET MVC
Programming is Fun with ASP.NET MVC
Ian Carnaghan
MVC
MVCMVC
MVC
Ravi Bansal
Mvc
MvcMvc
Mvc
Furqan Ashraf
Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01
Jennie Gajjar
Mvc
MvcMvc
Mvc
abhigad
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
AHM Pervej Kabir
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
Thomas Robbins
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architecture
ravindraquicsolv
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
Aaron Jacobson
Sitecore mvc
Sitecore mvcSitecore mvc
Sitecore mvc
pratik satikunvar
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
Mohammed Arif
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
Prashant Kumar
Mvc presentation
Mvc presentationMvc presentation
Mvc presentation
MaslowB
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
Surbhi Panhalkar
Aspnet mvc
Aspnet mvcAspnet mvc
Aspnet mvc
Hiep Luong
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
Fajar Baskoro
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...
CrimsonpublishersPRSP
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
Nyros Technologies
Modern webtechnologies
Modern webtechnologiesModern webtechnologies
Modern webtechnologies
Besjan Xhika
Programming is Fun with ASP.NET MVC
Programming is Fun with ASP.NET MVCProgramming is Fun with ASP.NET MVC
Programming is Fun with ASP.NET MVC
Ian Carnaghan
Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01Mvc 130330091359-phpapp01
Mvc 130330091359-phpapp01
Jennie Gajjar
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
AHM Pervej Kabir
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
Thomas Robbins
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architecture
ravindraquicsolv
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
Aaron Jacobson
MVC & backbone.js
MVC & backbone.jsMVC & backbone.js
MVC & backbone.js
Mohammed Arif
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
Prashant Kumar
Mvc presentation
Mvc presentationMvc presentation
Mvc presentation
MaslowB
Asp 1-mvc introduction
Asp 1-mvc introductionAsp 1-mvc introduction
Asp 1-mvc introduction
Fajar Baskoro
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...
CrimsonpublishersPRSP
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
Nyros Technologies
Modern webtechnologies
Modern webtechnologiesModern webtechnologies
Modern webtechnologies
Besjan Xhika

More from L棚 Th動畛ng (18)

Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptxTh叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
L棚 Th動畛ng
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptxPresentation1 gdfgdgdfgdfgdfgdfgdff.pptx
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
L棚 Th動畛ng
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptxTh叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
L棚 Th動畛ng
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
dfgdfgggggggggggggggggdfffffffffffffffffffffdfdfgdfgggggggggggggggggdfffffffffffffffffffffdf
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
L棚 Th動畛ng
ngay hoi hom nay qua da ban da kam gi chua na
ngay hoi hom nay qua da ban da kam gi chua nangay hoi hom nay qua da ban da kam gi chua na
ngay hoi hom nay qua da ban da kam gi chua na
L棚 Th動畛ng
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptxGIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
L棚 Th動畛ng
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
ytyuggtkguygyogugygyuggyguygygtuytt.pptxytyuggtkguygyogugygyuggyguygygtuytt.pptx
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
L棚 Th動畛ng
Lecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdfLecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdf
L棚 Th動畛ng
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
L棚 Th動畛ng
Lecture 01 - WWW.pdf
Lecture 01 - WWW.pdfLecture 01 - WWW.pdf
Lecture 01 - WWW.pdf
L棚 Th動畛ng
Bi 4.pptx
Bi 4.pptxBi 4.pptx
Bi 4.pptx
L棚 Th動畛ng
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
L棚 Th動畛ng
mary nativity.pptx
mary nativity.pptxmary nativity.pptx
mary nativity.pptx
L棚 Th動畛ng
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
L棚 Th動畛ng
Marial Prayer,.pptx
Marial  Prayer,.pptxMarial  Prayer,.pptx
Marial Prayer,.pptx
L棚 Th動畛ng
Bday Prayer.pptx
Bday Prayer.pptxBday Prayer.pptx
Bday Prayer.pptx
L棚 Th動畛ng
synthesis.pptx
synthesis.pptxsynthesis.pptx
synthesis.pptx
L棚 Th動畛ng
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.pptCH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
L棚 Th動畛ng
Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptxTh叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
Th叩nh L畛 dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
L棚 Th動畛ng
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptxPresentation1 gdfgdgdfgdfgdfgdfgdff.pptx
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
L棚 Th動畛ng
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptxTh叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
Th叩nh L畛 shfdshfjadsgdahncvbczvnbcbd.pptx
L棚 Th動畛ng
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
dfgdfgggggggggggggggggdfffffffffffffffffffffdfdfgdfgggggggggggggggggdfffffffffffffffffffffdf
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
L棚 Th動畛ng
ngay hoi hom nay qua da ban da kam gi chua na
ngay hoi hom nay qua da ban da kam gi chua nangay hoi hom nay qua da ban da kam gi chua na
ngay hoi hom nay qua da ban da kam gi chua na
L棚 Th動畛ng
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptxGIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
GIO N NGHE NI 4_TH畉Y DANH TH働畛NG.pptx
L棚 Th動畛ng
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
ytyuggtkguygyogugygyuggyguygygtuytt.pptxytyuggtkguygyogugygyuggyguygygtuytt.pptx
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
L棚 Th動畛ng
Lecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdfLecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 01ascaccacaWsacascascsacascascWW.pdf
L棚 Th動畛ng
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
L棚 Th動畛ng
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
L棚 Th動畛ng
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.pptCH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
CH働NG 6- CNH,HH V H畛I NH畉P KINH T畉 QU畛C T畉 C畛A VN.ppt
L棚 Th動畛ng

Recently uploaded (20)

Proteins, Bio similars & Antibodies.pptx
Proteins, Bio similars &  Antibodies.pptxProteins, Bio similars &  Antibodies.pptx
Proteins, Bio similars & Antibodies.pptx
Ashish Umale
BUSINESS QUIZ | THE QUIZ CLUB OF PSGCAS | 17TH MARCH 2025 .pptx
BUSINESS QUIZ | THE QUIZ CLUB OF PSGCAS | 17TH MARCH 2025 .pptxBUSINESS QUIZ | THE QUIZ CLUB OF PSGCAS | 17TH MARCH 2025 .pptx
BUSINESS QUIZ | THE QUIZ CLUB OF PSGCAS | 17TH MARCH 2025 .pptx
Quiz Club of PSG College of Arts & Science
Using social media to learn from conferences
Using social media to learn from conferencesUsing social media to learn from conferences
Using social media to learn from conferences
Sue Beckingham
Mixed_Sinhala_Dual_Male_Names (1).pdf...
Mixed_Sinhala_Dual_Male_Names (1).pdf...Mixed_Sinhala_Dual_Male_Names (1).pdf...
Mixed_Sinhala_Dual_Male_Names (1).pdf...
keshanf79
2. ES: Application of Number: Units of measure & conversions
2. ES: Application of Number: Units of measure & conversions2. ES: Application of Number: Units of measure & conversions
2. ES: Application of Number: Units of measure & conversions
leigh441292
PUBH1000 際際滷s - Module 7: Ecological Health
PUBH1000 際際滷s - Module 7: Ecological HealthPUBH1000 際際滷s - Module 7: Ecological Health
PUBH1000 際際滷s - Module 7: Ecological Health
Jonathan Hallett
"The Write Path: Navigating Research Writing, Publication, and Professional G...
"The Write Path: Navigating Research Writing, Publication, and Professional G..."The Write Path: Navigating Research Writing, Publication, and Professional G...
"The Write Path: Navigating Research Writing, Publication, and Professional G...
neelottama
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptxO SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
Literature Hero
UNIT 1 Introduction to communication.pptx
UNIT 1 Introduction to communication.pptxUNIT 1 Introduction to communication.pptx
UNIT 1 Introduction to communication.pptx
HARIHARAN A
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. DabhadeSynthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. DabhadeAnti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
A-Z GENERAL QUIZ | THE QUIZ CLUB OF PSGCAS | 14TH MARCH 2025.pptx
A-Z GENERAL QUIZ | THE QUIZ CLUB OF PSGCAS | 14TH MARCH 2025.pptxA-Z GENERAL QUIZ | THE QUIZ CLUB OF PSGCAS | 14TH MARCH 2025.pptx
A-Z GENERAL QUIZ | THE QUIZ CLUB OF PSGCAS | 14TH MARCH 2025.pptx
Quiz Club of PSG College of Arts & Science
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
Nguyen Thanh Tu Collection
10.socialorganisationandsocialsystem .pptx
10.socialorganisationandsocialsystem .pptx10.socialorganisationandsocialsystem .pptx
10.socialorganisationandsocialsystem .pptx
Vivek Bhattji
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdfIB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
Dr. Mahtab Alam
How to manage Customer Tips with Odoo 17 Point Of Sale
How to manage Customer Tips with Odoo 17 Point Of SaleHow to manage Customer Tips with Odoo 17 Point Of Sale
How to manage Customer Tips with Odoo 17 Point Of Sale
Celine George
Strategic Corporate Social Responsibility: Sustainable Value Creation Fourth
Strategic Corporate Social Responsibility: Sustainable Value Creation FourthStrategic Corporate Social Responsibility: Sustainable Value Creation Fourth
Strategic Corporate Social Responsibility: Sustainable Value Creation Fourth
keileyrazawi
How to process Interwarehouse and Intrawarehouse transfers in Odoo
How to process Interwarehouse and Intrawarehouse transfers in OdooHow to process Interwarehouse and Intrawarehouse transfers in Odoo
How to process Interwarehouse and Intrawarehouse transfers in Odoo
Celine George
Test Bank Pharmacology 3rd Edition Brenner Stevens
Test Bank Pharmacology 3rd Edition Brenner  StevensTest Bank Pharmacology 3rd Edition Brenner  Stevens
Test Bank Pharmacology 3rd Edition Brenner Stevens
evakimworwa38
The Effectiveness of Manual Therapies on the Thoracic.pptx
The Effectiveness of Manual Therapies on the Thoracic.pptxThe Effectiveness of Manual Therapies on the Thoracic.pptx
The Effectiveness of Manual Therapies on the Thoracic.pptx
SamarHosni3
Proteins, Bio similars & Antibodies.pptx
Proteins, Bio similars &  Antibodies.pptxProteins, Bio similars &  Antibodies.pptx
Proteins, Bio similars & Antibodies.pptx
Ashish Umale
Using social media to learn from conferences
Using social media to learn from conferencesUsing social media to learn from conferences
Using social media to learn from conferences
Sue Beckingham
Mixed_Sinhala_Dual_Male_Names (1).pdf...
Mixed_Sinhala_Dual_Male_Names (1).pdf...Mixed_Sinhala_Dual_Male_Names (1).pdf...
Mixed_Sinhala_Dual_Male_Names (1).pdf...
keshanf79
2. ES: Application of Number: Units of measure & conversions
2. ES: Application of Number: Units of measure & conversions2. ES: Application of Number: Units of measure & conversions
2. ES: Application of Number: Units of measure & conversions
leigh441292
PUBH1000 際際滷s - Module 7: Ecological Health
PUBH1000 際際滷s - Module 7: Ecological HealthPUBH1000 際際滷s - Module 7: Ecological Health
PUBH1000 際際滷s - Module 7: Ecological Health
Jonathan Hallett
"The Write Path: Navigating Research Writing, Publication, and Professional G...
"The Write Path: Navigating Research Writing, Publication, and Professional G..."The Write Path: Navigating Research Writing, Publication, and Professional G...
"The Write Path: Navigating Research Writing, Publication, and Professional G...
neelottama
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptxO SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
O SWEET SPONTANEOUS BY EDWARD ESTLIN CUMMINGSAN.pptx
Literature Hero
UNIT 1 Introduction to communication.pptx
UNIT 1 Introduction to communication.pptxUNIT 1 Introduction to communication.pptx
UNIT 1 Introduction to communication.pptx
HARIHARAN A
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. DabhadeSynthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Synthesis for VIth SEM 21-2-25.pptx by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. DabhadeAnti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Anti-Protozoal Agents.pptx by Mrs. Manjushri P. Dabhade
Dabhade madam Dabhade
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
TI LI畛U CHUYN SU L畛P 12 THEO CH働NG TRNH M畛I DNG CHO C畉 3 B畛 SCH N THI...
Nguyen Thanh Tu Collection
10.socialorganisationandsocialsystem .pptx
10.socialorganisationandsocialsystem .pptx10.socialorganisationandsocialsystem .pptx
10.socialorganisationandsocialsystem .pptx
Vivek Bhattji
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdfIB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
IB-Unit-5 BBA BVIMR 2022 Syllabus_watermark.pdf
Dr. Mahtab Alam
How to manage Customer Tips with Odoo 17 Point Of Sale
How to manage Customer Tips with Odoo 17 Point Of SaleHow to manage Customer Tips with Odoo 17 Point Of Sale
How to manage Customer Tips with Odoo 17 Point Of Sale
Celine George
Strategic Corporate Social Responsibility: Sustainable Value Creation Fourth
Strategic Corporate Social Responsibility: Sustainable Value Creation FourthStrategic Corporate Social Responsibility: Sustainable Value Creation Fourth
Strategic Corporate Social Responsibility: Sustainable Value Creation Fourth
keileyrazawi
How to process Interwarehouse and Intrawarehouse transfers in Odoo
How to process Interwarehouse and Intrawarehouse transfers in OdooHow to process Interwarehouse and Intrawarehouse transfers in Odoo
How to process Interwarehouse and Intrawarehouse transfers in Odoo
Celine George
Test Bank Pharmacology 3rd Edition Brenner Stevens
Test Bank Pharmacology 3rd Edition Brenner  StevensTest Bank Pharmacology 3rd Edition Brenner  Stevens
Test Bank Pharmacology 3rd Edition Brenner Stevens
evakimworwa38
The Effectiveness of Manual Therapies on the Thoracic.pptx
The Effectiveness of Manual Therapies on the Thoracic.pptxThe Effectiveness of Manual Therapies on the Thoracic.pptx
The Effectiveness of Manual Therapies on the Thoracic.pptx
SamarHosni3

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 its 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. Its 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 thats 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 users 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 users cart, by adding, for example, a new row to a database table holding the users 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 its 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 dont 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. Its typically some transformation of the data contained in the application model, plus extra information required to render the page, such as the pages 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 Pages 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. Its the view that generates the response.
  • 21. Putting It All Together: A Complete Razor Page Request Lets 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. 則 Heres 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 files 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 youve 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 applications 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 youre 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 youre mostly displaying static data, and theres no real logic.
  • 35. When to choose MVC controllers over Razor Pages 則 When you dont want to render views Razor Pages are best for page-based applications, where youre rendering a view for the user. If youre building a Web API, you should use MVC controllers instead. 則 When youre converting an existing MVC application to ASP.NET Core If you already have an ASP.NET application that uses MVC, its probably not worth converting your existing MVC controllers to Razor Pages. 則 When youre doing a lot of partial page updates Its 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 youre 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 youre building an app with real-time functionality, youll 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 Pages 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. 則 Its important to realize that a page handler doesnt generate a response directly; it selects the type of response and prepares the data for it. For example, returning a PageResult doesnt generate any HTML at that point; it merely indicates that a view should be rendered. 則 Its 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 users cart, it shouldnt 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 則 Its 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 (doesnt 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, youll 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 doesnt exist, a 404 HTTP status code is returned to the browser, and youll 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 its been generated and provide a user-friendly HTML response for it.