Hi guys, today I would like to present two easy ways in which to present a confirm dialog to the user (such as “Are you sure you wish to delete this item?”) from a button or link click before performing a particular action on your ASP.NET MVC website. If you are already somewhat familiar with the standard JavaScript function, confirm(), parts of the process below should not be too foreign.
In both examples I will use the ASP.NET MVC ActionLink control? (for lack of a better words) but it could easily be applied to a RouteLink or any HTML control which supports onClick really!
OPTION 1
Being a fairly standard JavaScript onClick implementation of which the confirmation dialog handler code is appended to the htmlAttributes property of your ActionLink.
[sourcecode language='html']
<%=Html.ActionLink(c => c.Delete(model.ID), “delete”, new { onclick = “return confirm(‘Are you sure you wish to delete this module?’);” })%>
Please Note: I am using the ASP.NET MVC Futures Release which is why you may not be familiar with the strongly typed ActionLink (where the model is specified as a type parameter). But never fear, if yours is slightly different, the important part is making sure the part of the "new" is placed in your htmlAttributes property of your ActionLink.
OPTION 2
My preferred method actually, as it utilises an unobtrusive JavaScript approach (an emerging good practice), does not tie the JavaScript code down with individual links (which is great if you repeat the delete link many times, eg. in a grid) and it uses jQuery.
Just place the script at the top of your page or with other jQuery logic and all you need to tie the reference of the confirm dialog to the button is ensuring the class attributes match. Using a class attribute I feel is good as you can then repeat this many times using the one class and your JavaScript confirm logic is also not repeated, cutting down code size.
[sourcecode language='html']
$( function() {
$('.button-delete').click(function() {
return confirm('Are you sure you wish to delete this item?');
});
});
{...}
<%=Html.ActionLink(c => c.Delete(model.ID), "delete", new { @class = "button-delete" })%>
Be sure to rename the obvious named parts and away you go!
4 Comments
[...] Two Easy Methods for Confirm Dialog with ActionLink [...]
Thanks for this!
Thanks ! It works for me.
Thanks Graham, this is super useful.
One Trackback/Pingback
[...] Two Easy Methods for Confirm Dialog with ActionLink [...]
Post a Comment