23. Using Razor Pages Flashcards

1
Q

What are Razor Pages?

A

Razor Pages are a simplified way of generating HTML responses.
Razor Pages are interesting because of the developer experience and not the way they are implemented.
For many features, a single action method will be used to handle a wide range of requests, all of which are dealt with using the same view. Razor Pages offer a more focused approach that ties together markup and C# code, sacrificing flexibility for focus.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why are they useful?

A

The simplicity of Razor Pages means you can start getting results sooner than with the MVC Framework, which can require a relatively complex preparation process. Razor Pages are also easier for less experienced web developers to understand because the relationship between the code and content is more obvious.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How are they used?

A

Razor Pages associate a single view with the class that provides it with features and uses a file-based routing system to match URLs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Are there any pitfalls or limitations?

A

Razor Pages are less flexible than the MVC Framework, which makes them unsuitable for complex applications. Razor Pages can be used only to generate HTML responses and cannot be used to create RESTful web services.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Are there any alternatives?

A

The MVC Framework’s approach of controllers and views can be used instead of Razor Pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does the MVC Framework work?

A

The MVC Framework solves every problem in the same way: a controller defines action methods that select views to produce responses. It is a solution that works because it is so flexible: the controller can define multiple action methods that respond to different requests, the action method can decide which view will be used as the request is being processed, and the view can depend on private or shared partial views to produce its response.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the AddRazorPages method do? (in the Startup class)

A

The AddRazorPages method sets up the service that is required to use Razor Pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the MapRazorPages method do? (Startup class)

A

The MapRazorPages method creates the routing configuration that matches URLs to pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Difference between Pages and the MVC Framework

A

Razor Pages use the Razor syntax and the same CSHTML file extension. But there are some important differences.
The @page directive must be the first thing in a Razor Page, which ensures that the file is not mistaken for a view associated with a controller. But the most important difference is that the @functions directive is used to define the C# code that supports the Razor content in the same file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does the URL routing convention work?

A

URL routing for Razor Pages is based on the file name and location, relative to the Pages folder. The file named Index.cshtml, in the Pages folder, means that it will handle requests for the /index. The routing convention can be overridden, but, by default, it is the location of the Razor Page file that determines the URLs that it responds to.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How does the page model work?

A
In a Razor Page, the @model directive is used to select a page model class, rather than identifying the type of the object provided by an action method. The page model is defined within the @functions directive and is derived from the PageModel class.
When the Razor Page is selected to handle an HTTP request, a new instance of the page model class is created, and dependency injection is used to resolve any dependencies that have been declared using constructor parameters. The IndexModel class declares a dependency on the DataContext service, which allows it to access the data in the database.
After the page model object has been created, a handler method is invoked. The name of the handler method is On, followed by the HTTP method for the request so that the OnGet method is invoked when the Razor Page is selected to handle an HTTP GET request. Handler methods can be asynchronous, in which case a GET request will invoke the OnGetAsync method, which is the method implemented by the IndexModel class.
Values for the handler method parameters are obtained from the HTTP request using the model binding process. The OnGetAsync method receives the value for its id parameters from the model binder, which it uses to query the database and assign the result to its Product property.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does the Page view work?

A

Razor Pages use the same mix of HTML fragments and code expressions to generate content, which defines the view presented to the user. The page model’s methods and properties are accessible in the Razor Page through the @Model expression. The Product property defined by the IndexModel class is used to set the content of an HTML element, like this:

<div>@Model.Product.Name</div>


The @Model expression returns an IndexModel object, and this expression reads the Name property of the object returned by the Product property.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How does the Generated C# Class work?

A

Behind the scenes, Razor Pages are transformed into C# classes, just like regular Razor views. Razor Pages rely on the same features used by the MVC Framework. The HTML fragments and view expressions are transformed into calls to the WriteLiteral and Write methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does razor pages routing work?

A

Razor Pages rely on the location of the CSHTML file for routing.

Example:
http://localhost:5000/suppliers/list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you specify a routing pattern?

A

Using the folder and file structure to perform routing means there are no segment variables for the model binding process to use. Instead, values for the request handler methods are obtained from the URL query string, which you can see by using a browser to request http://localhost:5000/index?id=2. The query string provides a parameter named id, which the model binding process uses to satisfy the id parameter defined by the OnGetAsync method in the Index Razor Page.
So the query string parameter in the request URL is used to provide the id argument when the OnGetAsync method is invoked, which is used to query the database for a product.

The @page directive can be used with a routing pattern like,
@page “{id:long?}”
which allows segment variables to be defined as http://localhost:5000/index/4
The route pattern adds an optional segment variable named id, which is constrained so that it will match only those segments that can be parsed to a long value.

The @page directive can also be used to override the file-based routing convention for a Razor Page like this:
@page “/lists/suppliers”
The directive changes the route for the List page so that it matches URLs whose path is /lists/suppliers.
http://localhost:5000/lists/suppliers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What do you do if you want to define multiple routes for a Razor Page?

A

Using the @page directive replaces the default file-based route for a Razor Page. If you want to define multiple routes for a page, then configuration statements can be added to the Startup class.
The options pattern is used to add additional routes for a Razor Page using the RazorPageOptions class. The AddPageRoute extension method is called on the Conventions property to add a route for a page. The first argument is the path to the page, without the file extension and relative to the Pages folder. The second argument is the URL pattern to add to the routing configuration.

services.Configure(opts => {
opts.Conventions.AddPageRoute(“/Index”, “/extra/page/{id:long?}”);
});

17
Q

How does the page model class work?

A

Page models are derived from the PageModel class, which provides the link between the rest of ASP.NET Core and the view part of the Razor Page. The PageModel class provides methods for managing how requests are handled and properties that provide context data. The properties however are not often required in Razor Page development, which focuses more on selecting the data that is required to render the view part of the page.

18
Q

Can pages be split into view and code files? And if so, how?

A
The @function directive allows the page-behind class and the Razor content to be defined in the same file. 
Defining code and markup in the same file is convenient but can become difficult to manage for more complex applications. Razor Pages can also be split into separate view and code files, which is similar to the MVC examples in previous chapters and is reminiscent of ASP.NET Web Pages, which defined C# classes in files known as code-behind files. The first step is to remove the page model class from the CSHTML file.
The convention for naming Razor Pages code-behind files is to append the .cs file extension to the name of the view file.
When defining the separate page model class, I defined the class in the WebApp.Pages namespace. This isn’t a requirement, but it makes the C# class consistent with the rest of the application.
One drawback of using a code-behind file is that automatic recompilation applies only to CSHTML files, which means that changes to the class file are not applied until the application has been restarted.
19
Q

What is a View Imports File?

A
A view imports file can be used to avoid using the fully qualified name for the page model class in the view file.
The @namespace directive sets the namespace for the C# class that is generated by a view, and using the directive in the view imports file sets the default namespace for all the Razor Pages in the application, with the effect that the view and its page model class are in the same namespace and the @model directive does not require a fully qualified type.

Example:
View Import file contains:
@namespace WebApp.Pages
@using WebApp.Models

Therefore the @model directive can go from this:
@model WebApp.Pages.IndexModel
To this:
@model IndexModel

20
Q

How do action results work in Razor Pages?

A

Understanding Action Results in Razor Pages

Although it is not obvious, Razor Page handler methods use the same IActionResult interface to control the responses they generate. To make page model classes easier to develop, handler methods have an implied result that displays the view part of the page.

 public async Task OnGetAsync(long id = 1) {
            Product = await context.Products.FindAsync(id);
            return Page();
        }
The Page method is inherited from the PageModel class and creates a PageResult object, which tells the framework to render the view part of the page. Unlike the View method used in MVC action methods, the Razor Pages Page method doesn’t accept arguments and always renders the view part of the page that has been selected to handle the request.
21
Q

How to use an action result?

A

Sending a status code response is unhelpful in Razor Pages because they are used only when a client expects the content of the view.
For example: Instead of using the NotFound method when requested data cannot be found, a better approach is to redirect the client to another URL that can display an HTML message for the user. The redirection can be to a static HTML file, to another Razor Page, or to an action defined by a controller.

22
Q

Are pages able to handle multiple HTTP Methods?

A

Razor Pages can define handler methods that respond to different HTTP methods. The most common combination is to support the GET and POST methods that allow users to view and edit data.

The elements in the Razor Page view create a simple HTML form that presents the user with an input element containing the value of the Price property for a Product object. The form element is defined without an action attribute, which means the browser will send a POST request to the Razor Page’s URL when the user clicks the Submit button.
The page model class defines two handler methods, and the name of the method tells the Razor Pages framework which HTTP method each handles. The OnGetAsync method is used to handle GET requests, which it does by locating a Product, whose details are displayed by the view.
The OnPostAsync method is used to handle POST requests, which will be sent by the browser when the user submits the HTML form. The parameters for the OnPostAsync method are obtained from the request so that the id value is obtained from the URL route and the price value is obtained from the form.

The form:

        @Html.AntiForgeryToken()
        <div class="form-group">
            Price

        </div>
        Submit
The post function:
public async Task OnPostAsync(long id, decimal price) {
            Product p = await context.Products.FindAsync(id);
            p.Price = price;
            await context.SaveChangesAsync();
            return RedirectToPage();
}
23
Q

What are handler methods and how fo they work?

A

The page model class can define multiple handler methods, allowing the request to select a method using a handler query string parameter or routing segment variable.

Example:
public async Task OnGetAsync(long id = 1) {
Product = await context.Products.FindAsync(id);
}

public async Task OnGetRelatedAsync(long id = 1) {
Product = await context.Products
.Include(p => p.Supplier)
.Include(p => p.Category)
.FirstOrDefaultAsync(p => p.ProductId == id);
Product.Supplier.Products = null;
Product.Category.Products = null;
}

The page model class in this example defines two handler methods: OnGetAsync and OnGetRelatedAsync. The OnGetAsync method is used by default, which you can see by using a browser to request http://localhost:5000/handlerselector. The handler method queries the database and presents the result to the user.
One of the anchor elements rendered by the page targets a URL with a handler query string parameter, like this:

<a>Related</a>

The name of the handler method is specified without the On[method] prefix and without the Async suffix so that the OnGetRelatedAsync method is selected using a handler value of related. This alternative handler method includes related data in its query and presents additional data to the user.

24
Q

How do Razor Page Views work?

A

The view part of a Razor Page uses the same syntax and has the same features as the views used with controllers. Razor Pages can use the full range of expressions and features such as sessions, temp data, and layouts. Aside from the use of the @page directive and the page model classes, the only differences are a certain amount of duplication to configure features such as layouts and partial views, as described in the sections that follow.

25
Q

How do Layouts for Razor Pages work?

A

Layouts for Razor Pages are created in the same way as for controller views but in the Pages/Shared folder.
Using a view start file applies the layout to all pages that don’t override the value assigned to the Layout property.

26
Q

How do partial views work in Razor Pages?

A

Razor Pages can use partial views so that common content isn’t duplicated.
Partial views use the @model directive to receive a view model object and do not use the @page directive or have page models, both of which are specific to Razor Pages. This allows Razor Pages to share partial views with MVC controllers, as described in the sidebar.
Partial views are applied using partial element.

with the name attribute specifying the name of the view and the model attribute providing the view model.
When the Razor Page is used to handle a response, the contents of the partial view are incorporated into the response.

Caution: Partial views receive a view model through their @model directive and not a page model. It is for this reason that the value of the model attribute is Model.Product and not just Model.

27
Q

How to create Razor Pages Without Page Models?

A
If a Razor Page is simply presenting data to the user, the result can be a page model class that simply declares a constructor dependency to set a property that is consumed in the view. 
But when a page model doesn’t transform data, perform calculations, or do anything other than giving the view access to the data through dependency injection. ypu can avoid this pattern, where a page model class is used only to access a service, the @inject directive can be used to obtain the service in the view, without the need for a page model.

@inject DataContext context;

<h5>Categories</h5>

<ul>
@foreach (Category c in context.Categories) {
<li>@c.Name</li>
}
</ul>

The @inject expression specifies the service type and the name by which the service is accessed.
In this example, the service type is DataContext, and the name by which it is accessed is context. Within the view, the @foreach expression generates elements for each object returned by the DataContext.Categories properties.

Caution: The @inject directive should be used sparingly and only when the page model class adds no value other than to provide access to services. In all other situations, using a page model class is easier to manage and maintain.