To implement JavaScript code dynamically there are two
functions available.
Listing 1
Page.ClientScript.RegisterStartupScript(GetType(Page), "item1", script)
and
Listing 2
ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "item1", script, True)
The last may be used if you have an AJAX enabled website and
a ScriptManager on it.
Listing 3
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
The difference between both is that the first one will put
the script code at the end of the page and the second one will put the script
code just behind the <BODY> tag.
A second difference is that the first one needs a
<script> tag to be added and in the second one these tags will be put
there for you.
Suppose my code looks like
Listing 4
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Dim script As String
If Not Page.IsPostBack Then
script = "<script type='text/javascript'><!--" & vbCrLf & _
"alert('Alert message two');" & vbCrLf & "// --></script>"
Page.ClientScript.RegisterStartupScript(GetType(Page), "focus4", _
script)
script = "alert('Alert message one');"
ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), _
"item11", script, True)
End If
End sub
Then I will have two alert boxes; the first one "alert
message one" although it is called secondly and a second one "Alert
message two".
You might even have your alert message hard coded in the
<BODY> of your page.
Listing 5
<script type="text/javascript">
<!--
alert('in between');
-->
</script>
This message will come after the first one and before the
last one. Also the alert message implemented with the following code will pop
up when the page is loaded.
Listing 6
Page.ClientScript.RegisterStartupScript
The alert message implemented with Listing 7 will pop up
before the page is loaded.
Listing 7
ScriptManager.RegisterClientScriptBlock
A third method for implementing your code dynamically is
this.
Listing 8
<head>
<title><% =titelpage%></title>
<% =MyNewStyle%>
</head>
In the code for the page you must fill the variable MyNewStyle.
Listing 9
Protected MyNewStyle As String
Protected titelpagina As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
titelpagina = "new title"
MyNewStyle = "<style type='text/css'>TD{color:orange;border:1;" & _
"border-color:black;border-style:solid;}</style>"
End Sub
And it is easy to fill this dynamically