Search

ASP.Net - confirmation before delete

February 5th, 2008 by mike

I realise this is a bit of a departure from my usual posts (i.e. I’m not ranting), but I’d thought I’d share a rather useful bit of ASP.Net code I’ve been using.

When a user is presented with a GridView of data they can delete, it’s usually a good idea to give them a “Are you sure?” confirmation dialog using Javascript, like so:

<asp:Button ID="uxDelete" runat="server" Text="Delete" OnClientClick="javascript: return confirm('Are you sure you want to delete this record?');" />

(The above is an ASP button, to be placed in a TemplateField in a GridView)

Now that will give a plain “Are you sure?” message, but it’s a bit vague - what if the GridView has twenty-five, fifty or one hundred records displayed? Will the user be sure they clicked the right delete button for the right product / entry / whatever?

By some clever use of the Eval statement, the dataitem you want to delete and some character escapes, it’s possible to put an identifiable piece of data in the Javascript confirm call:

<asp:Button ID="uxDelete" runat="server" Text="Delete" OnClientClick='<%# Eval("ProductCode", "javascript: return confirm(\"Are you sure you want to delete {0}?\");") %>' />

Now, when the user clicks delete on an item, the name of the item will appear in the confirm dialog, reinforcing their decision to delete.

Another reason I’ve blogged this is to have it somewhere where I can always get hold of it - I don’t remember stuff as well as I used to ;)

Posted in ASP.Net, Development | No Comments »