Xperimentality

Building a Better Xperience with .NET

 Friday, May 02, 2008

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!

Thursday, May 01, 2008 11:17:23 PM (Central Standard Time, UTC-06:00)
Who Am I - Todd Miranda
Me
MVP Visual Developer - ASP/ASP.NET
Search
Links
On this page....
Calendar
<July 2008>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Archives
Aggregate Me!
RSS 2.0 | Atom 1.0 | CDF
Categories
Blogroll
Contact me
Send mail to the author(s) E-mail
Administration