Pages

Search

Tuesday, October 7, 2008

How to call java script functions in code behind pages?

When web server receives request, it constructs the response string that has to be rendered on to client browser.
This response string is build not just based upon aspx page but also aspx.cs. So developer can call java script functions not only from aspx page but also from aspx.cs provided the syntax or the approach is different.

Example :-
If I want to show a message using alert box (javascript) upon button click , I can call the alert box javascript function just on button click of appropriate button.

This button might be a Html (input type=”button”) type button or asp button (asp:Button). What ever the case it is at the moment they are rendered to browser they seems to be Html (input type=”button”) type button.
So I can do in the following way to display alert box.
<input type=”button ” id=”btnTest ” value=”Test ” onclick=”alert(‘Hi’);”/>
in aspx page


Else I can do in aspx.cs page as
btnTest.Attributes.Add("OnClick", "alert('Hi');"); in page load event.


The above 2 give the same response to the browser but the way web server constructs the response is different.

In first case web server need not bother exclusively to add onclick event where as in other case form the page load event it finds that an onclick (client event) is required to be considered for “btnTest” button.

Finally the response string gets builded in simmilar manner to handle client on click event once rendered on to client browser.

This is a sample, there are many functionalities or instants that we cannot add client events like click,mouse down,mouse over etc.. directly on aspx page but can handle from aspx.cs page.

No comments:

Post a Comment