Apr 05
2010

Registering a javascript for an aspx page is possible in many ways.
Here is an example to add an eventhandler for an asp.net control using ASP.NET AJAX client life-cycle events.

  • First on the bottom of our javascript code in aspx we have to add handler functions for the load and unload event. The event handlers itself contains the needed js functions:

    Sys.Application.add_load(jsFunction_pageLoad);
    Sys.Application.add_unload(jsFunction_pageUnload);

  • The next step is to add a click handler to our asp.net control, in this case to a radiobutton. Javascript finds the control by getting the controls ClientID. To complete this way the handler will removed when page will be unloaded:

    function jsFunction_pageLoad(source, args)
    {
        if (!args.get_isPartialLoad())
        {
            $addHandler($get('<%= rbtnTest.ClientID %>'),
'click', rbtnTest_click);
         }
    }

    function jsFunction_pageUnload(source, args)
    {
        $removeHandler($get('<%= rbtnTest.ClientID %>'),
'click', rbtnTest_click);
    }

  •  Now we can write the real js function which will execute something when the radiobutton is clicked:

    function rbtnTest_click(evt)
    {
        alert('hello world');
    }

 

Here the complete code:

<script type="text/javascript">
//<![CDATA[

    function jsFunction_pageLoad(source, args)
    {
        if (!args.get_isPartialLoad())
        {
            $addHandler($get('<%= rbtnTest.ClientID %>'), 'click', rbtnTest_click);
         }
    }

    function jsFunction_pageUnload(source, args)
    {
        $removeHandler($get('<%= rbtnTest.ClientID %>'), 'click', rbtnTest_click);
    }

    //event when rbtnTest is clicked
    function rbtnTest_click(evt)
    {
        alert('hello world');
    }


 Sys.Application.add_load(jsFunction_pageLoad);
 Sys.Application.add_unload(jsFunction_pageUnload);

//]]>
</script>

More informations about AJAX client events you can get here.

Tags: Tags:

Related posts

Comments are closed