|
Write a comment |
Articles |
DHTML Gallery |
.NET |
MyBlog |
About Me |
FAQ
|
|
Adding multiple client-side event handlers to ASP.NET controls
In this article, I will show how to do this with 'jQuery'. As many of you might be knowing, there is talk of Visual Studio supporting jQuery in future. This makes 'jQuery' the ideal candidate. All one needs to do is download a javascript file from their site and reference it in the *.aspx page. I have written two javascript functions which I will demonstrate attaching to client-side 'click' event of ASP.NET textbox.
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Handler1(p1){alert('Handler1 called.['+p1+']');}
function Handler2(p1,p2){alert('Handler2 called.['+p1+' '+p2+']');}
</script>
Now, in the code-behind of the *.aspx file, code looks like this:
protected override void OnPreRender(EventArgs e)
{
StringBuilder sb = new StringBuilder();
string functionCall = "$('#{0}').bind('{1}', function(){{ {2} }});\n";
sb.Append(" $(window).bind('load',function(){\n");
sb.Append(string.Format(functionCall,TextBox1.ClientID,"click","Handler1('param1')"));
sb.Append(string.Format(functionCall, TextBox1.ClientID, "click", "Handler2('param1','param2')"));
sb.Append(string.Format(functionCall, TextBox2.ClientID, "click", "Handler1('param1')"));
sb.Append(string.Format(functionCall, TextBox2.ClientID, "click", "Handler2('param1','param2')"));
sb.Append ("});");
ClientScript.RegisterClientScriptBlock(this.GetType(),"ClickHandlers",sb.ToString(),true);
base.OnPreRender(e);
}
The above code does two things:
<script type="text/javascript">
//<![CDATA[
$(window).bind('load',function(){
$('#TextBox1').bind('click', function(){ Handler1('param1') });
$('#TextBox1').bind('click', function(){ Handler2('param1','param2') });
$('#TextBox2').bind('click', function(){ Handler1('param1') });
$('#TextBox2').bind('click', function(){ Handler2('param1','param2') });
});//]]>
</script>
The '$()' is the famous dollar function. The notation $('#TextBox1') is roughly eqvivalent to saying document.getElementById('TextBox1'). To further understand the code check out tutorials for jQuery. As always, let me know your suggestions and comments. |
| Copyright (c) 2007-2009 Ashish Patil . Please read FAQ for more details. |