Friday, March 28, 2008

Programmatically Set Client-Side Events in .NET

I have run into this situation many times before and several Google searches later I know I am not alone in this problem. There are times in life when we need to set a Client side event but we need to set this event in the codebehind of where we are working.

If you are slamming out a Server Control or, as in my case, a WebPart you might run into such a situation where you need something to occur locally but you don't have the luxury of detailing the control in an aspx page.

Furthermore, there are situations where even the miracle that is AJAX will not solve your problem (getting the Excel Web Access session id is one such situation).

One of the first things you will need to do is register some type of JavaScript method on your page so that the event has something valid to call. You can do this by forming the JS Function in a StringBuilder (sb in the code below) and then use the RegisterClientScriptBlock method to push it out to the page:

Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), this.ID.ToString(), sb.ToString());

Once this is accomplished, you will want to add the event (OnChange event in my example but the same can be done for OnFocus, OnBlur, OnClick, etc). To do this you simply add an Attribute to the ASP tag in the codebehind and use the proper attribute name (see HTML reference to make sure you have the correct spelling). This is an example of doing such:

_myDDLControl.Attributes.Add("onchange", "MyJavaScriptMethod();");
_myDDLControl.AutoPostBack = true;

The meat of this is adding the Attribute to the control so that it will fire the OnChange() event on the client side and run whatever snazzy JS you might desire. You should be able to find plenty of references online on the available events for different HTML elements so then the issue falls to determining what HTML element your ASP Webcontrol will get rendered as.

Setting the AutoPostBack attribute will ensure that the control posts back to the server as well.

Edit: The wise and all knowing (alright maybe that is a bit of an exaggeration but I do have a lot of respect for him) Tim correctly pointed out that you should wrap RegisterStartupScript in a test to ensure that the method doesn't already exist.

You would do this by use of another method contained within the ClientScript object called (of all things) IsClientScriptBlockRegistered("MyJavaScriptMethod"). The specific code would look something like this (in C#):

If(Page.PreviousPage != null && !Page.ClientScript.IsClientScriptBlockRegistered("MyJavaScriptMethod"){ //use the RegisterClientScriptBlock method above }