How to programatically add javascript to ASP.NET pages
While the ASP.NET programming model provides validation controls and the ability
to call custom functions in code-behind files, this may not be the best
solution for every programming problem. In addition to the potential
overhead additional round-trips to the server may consume, I have personally
worked on plenty of projects where a JavaScript was conditionally written to
the html output depending on the circumstances. The ability to push
JavaScript to the client during run-time provides a great deal of flexibility
when developing web applications.
In most traditional ASP pages, ASP code was intertwined with presentation layer
code. If JavaScript was going to be added conditionally, the developer would
test their condition in asp to decide whether or not to write the script to the
client. The following is a good example:
CLASSIC ASP METHOD
<HEAD>
<% Dim x
If x = 1 Then
%>
<SCRIPT LANGUAGE="JavaScript">
function myFunction()
{
alert('Hello world.');
}
</SCRIPT>
<%End If%>
</HEAD>
In ASP.NET, this can be done from the code-behind files as the page is built on
the server. In thisi example, I have an asp:button named "btnSave" on the form,
and I would like to add javascript from the server-side to pop-up a message to
the user:
ASP.NET METHOD
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim x as integer
If x=1 then
btnSave.Attributes.Add("onClick", "test();")
RegisterClientScriptBlock("dosomething", "<SCRIPT
language="JavaScript">function myFunction(){alert('Hello world.');}
")
End If
End Sub
In the Page_Load event, I first add an attribute called "onClick" to the btnSave
button , which will call the java script test() function. Next, I
register the client script function test() using the RegisterClientScriptBlock
method of the page. And that's it! This is very useful if you want to
write a different java script to the client depending on values unknown until
run-time, and I'm sure you'll find it useful in other circumstances as well.
Want to contribute a technical tip? Contact us here.
|