Tuesday, July 9, 2013

Javascript and ASP.NET

Many ASP.NET server controls provide a property or two for specifying javascript to execute.  For example, a Button control will expose a OnClientClick property where you can specify javascript.  A CustomValidator control exposes a ClientValidationFunction where you can specify a javascript function.

The first thing you need to do is write the javascript function.  The javascript must be enclosed in <script> tags, and can be placed anywhere in the markup.  For example:

<script type="text/javascript">
     function SayHello() {
          alert('Hello');
     }
</script>

Now, you can refer to this function in those properties.  You can set these properties in either the markup or the code-behind.  For example in code-behind, you could write:

Button1.OnClientClick = "SayHello()"

Or, if your javascript is just a one or two liner, you could put the lines of code directly into the property like this:

Button1.OnClientClick = "alert('Hello')"

Sometimes, a server control will not expose a property to execute the script when you want it to.  For example, let's say you want javascript to execute when you change the value of a TextBox control.  A TextBox control will actually render as an html input tag.  The input tag has an attribute of "onchange" which is part of a group of attributes called "intrinsic events".  We can actually stick some javascript in these events with the following code:

TextBox1.Attributes.Add("onchange", "SayHello()")

Now when the TextBox's contents are changed and user tabs off, your script will execute.

One final note.  There is no way to directly call a javascript function from your code behind.  However, by using the above methods, and "injecting" the javascript at run-time, you can effectively accomplish this.


No comments:

Post a Comment