Anyone that builds or has built web applications, is familiar with the idea of writing some JavaScript code that will pop up a confirmation message to the user prior to performing a postback.
While I love JavaScript, I always thought the way this had to be done was a little messy. An ASP.NET Button has an OnClick attribute, but this attribute's value is the server-side event that will be invoked upon a postback. In order to invoke a client-side click handler in JavaScript, the attribute that must be set on the rendered HTML Input control is also OnClick. Therefore, in order to accommodate both a client-side click event and a server-side click event, the client-side click handler must be added at runtime before the button is rendered.
In the code-behind, the following code would be used to add the client-side click handler:
btnDelete.Attributes.Add("onclick","javascript:if(
!confirm('Are you sure you want to delete this item?'))
return false;");
In the markup, the button would then look like this:
<html>
<head>
</head>
...
<asp:Button id="btnDelete" onclick="btnDelete_Click"
runat="server" Text="Delete" />
...
</html>
Starting with .NET 2.0, there is an easier way to do this. .NET 2.0 introduced the OnClientClick attribute. Instead of having to add the "onclick" attribute to the button in the code-behind, you can use the OnClientClick attribute at design-time in markup. The new button code would like this:
<html>
<head>
</head>
...
<asp:Button id="btnDelete" onclick="btnDelete_Click"
runat="server" Text="Delete" OnClientClick="return
confirm('Are you sure you want to delete this item?');" />
...
</html>
Much cleaner to me. And I like that it can be done at design-time!