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: 1242

2 Comments

- Satyabrata Mohapatra

Nice and easy !! Great post.

- Cyrus

well done, thank you.

Recent Comments

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

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...