Join Jess Chadwick for an in-depth discussion in this video Adding custom handlers beyond GET and POST, part of ASP.NET Core: Razor Pages.
- [Instructor] In additional to being able to handle GET and POST verbs with the OnGet and OnPost handler methods that I've already shown Razor Pages also allows you to define your own custom handlers as well. And you do so by following a simple naming convention. Just name a method OnGet or OnPost followed by the name of your handler. For example if I wanted to implement the ability to delete a recipe in addition to creating and editing it I can add another method named OnPostDelete with the same asynchronous signature as the OnPost method that I've already created.
Once I've created this method I can execute code just like I've already shown in the existing OnGet and OnPost methods. This time instead of retrieving the recipe from the database and modifying it, though, I'll simply make an asynchronous call to the recipeService.DeleteAsync method and pass it the value of the Id property as the id of the recipe to delete.
Then, once the delete has completed, I'll make a call to the page models redirect page to redirect to the homepage. That's the server side implementation of a custom handler. Now we've got to call it from the browser. The way Razor Pages exposes these custom methods is through a query string parameter named handler like this. However, you do not want to do that manually because Razor Pages provides a tag helper to do it for you. To show the tag helper in action I'll add another button to the edit recipe form to handle the delete action.
I'll simply copy and paste the existing save button and modify it. Then I'll add the asp-page-handler attribute to this button. And I'll give it the name of the custom handler that I just created. In this case delete. Note that this parameter is case sensitive so make sure that the value you provide here matches the name of your server side handler method exactly.
Finally since this page is being used for both editing existing recipes, and creating new ones, and it doesn't make much sense (chuckling) to delete a recipe that I haven't even created yet I'm going to wrap this tag in a condition to only show it when the IsNewRecipe property is false. With all this in place I can see my handler in action by trying to edit a recipe, and then clicking the delete button. And judging by the updated homepage it looks like my handler has worked since that recipe no longer exists.
- Creating a new application
- Setting up pages
- Rendering dynamic content
- Reusing markup with layouts
- Increasing the maintainability of pages
- Processing data
- Validating input
- Securing an application