Client and Serverside Button Click in ASP.Net

While I was going through the comments in this post here, someone asked a question around how button click function worked, so I thought I would write a post around this topic.

There are two types of click that can be associated with a button, one is a server side click function, i.e in a function in VB code that gets called, and there is a javascript click function, a function that gets called in javascript when a button is clicked on.
Javascript onclick function gets executed before the server side on click function.
Here are the methods of specifying both.

Javascript click function

1. in asp, specify the javascript to be called using the onclientclick attribute, what ever is specified in this attribute will be executed on the client side.

2. In the code behind, specify the javascritp to be called using the onclick attribute.

3. Using a library like JQuery, the onclick function can be specified like so
$(document).ready(function(){$(’#button’).click(function() {alert(’me’);});});
If you are doing some validation in the javascript and only want the server side click function to execute if the javascript validation is successful then you can return false in the javascript function called. If false is returned in the javascript function, the server side event is not executed.

Serverside Click Function

1. In the design view of the ASP, double click on a button, and a function similar to this should be generated

Private Sub
button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button.Click
End Sub

notice that the Handles part, this tells that code that this function is used to handle the click event of the button

2. In the source view, there are 2 drop down lists at the top, the left one allows selecting of the different form elements on the page, the right hand side allows viewing of the the functions available for each element. In the left, select the button, and then on the right, select Click, a sub similar to above should be created.

3. You can also specify the click function in the ASP and not have the Handles part in the code.

Private Sub
button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
End Sub

This would only work if the parameters specified matches the ones required for the button click event.