Razor Pages - Understanding Handler Methods

5 (2 votes)

Handler methods is a particularly nice feature introduced with the new ASP.NET Razor Pages framework . This feature enables you to determine what the user was doing when they requested the page, and to execute logic accordingly without having to resort to a bunch of conditional code.

One of the most common tasks in web development is to determine which HTTP verb your visitor has used to request a page. Is this an initial GET request, or has the user POSTed a form? In classic ASP or PHP, you will usually query the Server Variables collection (Request.ServerVariables("REQUEST_METHOD") or $_Server['REQUEST_METHOD']) to determine which verb was used, or you might query the Request.Form collection for the presence or absence of values. The ASP.NET Web Forms and Web Pages frameworks provide convenience methods to differentiate between POST and GET requests via the Page.IsPostBack and Page.IsPost properties respectively. ASP.NET MVC offers a different solution, mapping information from the request - the URL and the HTTP verb - to controller actions using a convention-based approach.

Handler methods in Razor Pages are also based on naming conventions. The basic methods work by matching HTTP verbs used for the request to the name of the method, and they are prefixed with "On": OnGet(), OnPost(), OnPut() etc. They also have asynchronous equivalents: OnPostAsync(), OnGetAsync() etc. The following example illustrates basic usage in a single Razor pages file:

@page
@{
    @functions{
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Get used";
        }

        public void OnPost()
        {
            Message = "Post used";
        }
    }
}


<h3>@Message</h3>
<form method="post"><button class="btn btn-default">Click to post</button></form>
<p><a href="/handlerexample" class="btn btn-default">Click to Get</a></p>

When the page is first navigated to, the "Get used" message is displayed because the HTTP GET verb was used for the request, firing the OnGet() handler.

When the "Click to post" button is pressed, a form is posted and the OnPost() handler fires, resulting in the "Post used" message being displayed.

The button underneath is a hyperlink, which initiates a GET request, resulting in the "Get used" message being displayed once more.

Named Handler Methods

Imagine that you have a number of forms on the page (perfectly legal everywhere except Web Forms...) - how will you know which one was submitted? Well, I kind of take a bit if an unfair dig at Web Forms, but in fact the solution to the problem is not too disimilar to Web Forms button click event handlers. Razor Pages introduces named handler methods. The following code shows a collection of named handler methods declared in a code block at the top of a Razor page (although they can also be placed in the PageModel class if you are using one):

@page 
@{
    
    @functions{
        public string Message { get; set; } = "Initial Request";

        public void OnGet()
        {

        }

        public void OnPost()
        {
            Message = "Form Posted";
        }

        public void OnPostDelete()
        {
            Message = "Delete handler fired";
        }

        public void OnPostEdit(int id)
        {
            Message = "Edit handler fired";
        }

        public void OnPostView(int id)
        {
            Message = "View handler fired";
        }
    }
}

The convention (in Preview 1) is that the name of the method is appended to "OnPost" or "OnGet". The next step is to associate a specific form action with a named handler. This is achieved by setting the asp-page-handler attribute value for a form taghelper:

<div class="row">
    <div class="col-lg-1">
        <form asp-page-handler="edit" method="post">
            <button class="btn btn-default">Edit</button>
        </form>
    </div>
    <div class="col-lg-1">
        <form asp-page-handler="delete" method="post">
            <button class="btn btn-default">Delete</button>
        </form>
    </div>
    <div class="col-lg-1">
        <form asp-page-handler="view" method="post">
            <button class="btn btn-default">View</button>
        </form>
    </div>
</div>
<h3 class="clearfix">@Model.Message</h3>

The code above renders as three buttons, each in their own form along with the default value for the Message property:

FormTagHelpers

 

The name of the handler is added to the form's action as a querystring parameter:

Handlers

As you click each button, the code in the handler associated with the querystring value is executed, changing the message each time.

Handlers

 

If you prefer not to have querystring values in the URL, you can use routing and add an optional route value for "handler" as part of the @page directive:

@page "{handler?}"

The name of the handler is then appended to the URL:

Handler Routevalue

Parameters

Handler methods can be designed to accept parameters:

public void OnPostView(int id)
{
    Message = $"View handler fired for {id}";
}

The parameter name must match a form field name for it to be automatically bound to the value:

<div class="col-lg-1">
    <form asp-page-handler="view" method="post">
        <button class="btn btn-default">View</button>
        <input type="hidden" name="id" value="3" />
    </form>
</div>

Handler parameters

Alternatively, you can use the form tag helper's asp-route attribute to pass parameter values as part of the URL, either as a query string value or as route data:

<form asp-page-handler="delete" asp-route-id="10" method="post">
    <button class="btn btn-default">Delete</button>
</form>

You append the name of the parameter to the asp-route attribute (in this case "id") and then provide a value. This will result in the parameter being passed as a querystring value:

Parameter as Query String

Alternatively, you can extend the route defintion for the page to account for an optional parameter:

@page "{handler?}/{id?}"

This results in the parameter value being added as a separate segment in the URL:

Parameter as route segment

Summary

Razor Pages handler methods facilitate the clear separation of processing code based on user actions on the page without resorting to a confusing pile of conditional code to determine which button was clicked. They follow a clear naming convention and are easy to use. When placed in a code-behind file, they can make the page feel very much like an MVC controller. They can also be seen as analogous to event handlers in a Web Form code behind file.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 1573

2 Comments

- Satyabrata Mohapatra

Nice and easy !! Great post.

- Cyrus

well done, thank you.

Recent Comments

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...

Harris Boyce 04/07/2017 04:17
In response to Razor Pages - The Elevator Pitch
As a developer of a couple "trivial" web pages applications used by non-profits that wouldn't have I...

Cyrus 28/06/2017 20:25
In response to Razor Pages - Getting Started With The Preview
.net core 2.0 preview 2: <a...

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...