ASP.NET 2.0: OnClientClick
I've known about this for a while, but I just helped a co-worker that did not know about this nifty new property on buttons - so here's a quick blog entry that I hope will help someone else out in the future.
In .NET 1.1 days - when you had processing that you wanted to complete in a web client prior to executing a postback, you would probably put some code in the page load of your page to add the attribute to the button manually. I've personally done this a lot for Delete operations, returning a message before the page would be posted back, asking "Are you sure you would like to delete this record?" It looked something like this:
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
With Me.btnSubmit
.Attributes.Add("onclick", _
"BLOCKED SCRIPT return confirm('are you sure?');")
End With
End Sub
There is nothing wrong with this code, except that it clutters up your code-behind. If you did this a lot, you might have encapsulated the above functionality into a shared method somewhere that probably looked like this:
Public Shared Sub AddConfirm(_
ByRef ctlButton As Button, _
ByVal message As String)
With ctlButton
.Attributes.Add("onclick", _
String.Format(_
"BLOCKED SCRIPT return confirm('{0}');", _
message))
End With
End Sub
Once again, nothing wrong with this. It displays the confirm message and everyone is happy. Your rendered HTML will look something like this:
<input type="submit"
name="btnSubmit"
value="Submit"
onclick="BLOCKED SCRIPT return confirm('Are you sure?');"
id="btnSubmit" />
In ASP.NET 2.0, though, there is a simpler (I think) way to perform this same operation. You can use the handy dandy property on the button control called "OnClientClick". This function injects the string you apply to it into the control's attributes when it is rendered in much the same way as the above. The only difference is that you can set it in the XHTML on the page. Therefore, the above code could be accomplished by doing this:
<asp:Button runat="server"
ID="btnSubmit2"
Text="Submit 2"
OnClientClick="return confirm('test');" />
This little xhtml property will accomplish the same thing as the code above and when this button is rendered to the page, the HTML will be:
<input type="submit"
name="btnSubmit2"
value="Submit 2"
onclick="return confirm('test');"
id="btnSubmit2" />
As you can see, from a straight functionality standpoint, nothing has changed - but to me, this type of property is really cool as it allows you to define something that would normally require VB or C# code in the XHTML.
Enjoy!