Adding a confirmation dialog to an ASP.NET Core 2.0 form page handler

The solution to this particular problem was not as difficult as I at first thought. Our web app contains dynamic toolbars that are in fact Razor form page handlers. Inside each form page handler is a button that invokes the Razor page handler and thus services the request.

For example, a toolbar may contain buttons for adding, deleting, updating a particular entity.

Hide Copy Code

<form asp-page-handler=@toolbar.PageHandler method=@toolbar.Method>
<button class="btn btn-default">@toolbar.DisplayText</button>

As can be seen from the example code, the toolbar is built entirely from dynamic data. This is because each toolbar menu item is tied to a permission, and the ASP.NET Web API service that returns the toolbar items contains all the business logic for deciding which toolbar items to return based on the user’s permissions.

This all works perfectly. However, I ran into a problem when I needed to add a confirmation dialog to the Delete toolbar menu item. Adding a confirmation dialog using JQuery was simple enough, the problem was that all toolbar items are linked to a Razor page handler. For example, the toolbar menu item for Edit was linked to the OnPostEdit page handler. This would then implement any code as necessary to service the user’s request to Edit the entity. None of the these toolbar items required a confirmation dialog. The toolbars are defined entirely by the service and all are linked to a single Razor page handler.

The Delete toolbar item needed a confirmation (“Are you sure you want to delete this item?”), and the most obvious solution was to implement this using JQuery, but this would break the pattern I was using for the other toolbar items.

I eventually came across a simple solution that solved the problem. I could add an onclick to the toolbar items that needed a confirmation dialog.

Hide Copy Code

<form asp-page-handler=@toolbar.PageHandler method=@toolbar.Method onclick="return confirm('Are you sure you want to delete this?')">
<button class="btn btn-default">@toolbar.DisplayText</button>

Clicking on the toolbar item now brings up a confirmation dialog. If the user selects the Yes option the Razor page handler is still invoked — which is exactly what I wanted. If the user selects No, then nothing happens.

This very simple addition to the Razor form page handler gives you a confirmation before the page handler code is invoked. No need for JQuery. Just a very simple solution that I have now implemented and which works perfectly.

A father, cyclist, vegetarian, atheist, geek and multiple award winning technical author. Loves real ale, fine wine and good music. All round decent chap.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store