Sunday, October 22, 2006

Client scripts on a page

Ever need to put an alert onto a webpage from the codebehind? It wasn't logical doing it within ASP.NET1.x but now it seems better.

eg. on the page load

String script = "alert('testing this functionality');";
Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "MyKey", script, True);

The RegisterClientScriptBlock() method has changed namespaces between 1.x and 2.0. It is now under the ClientScriptManager class (you can get access to this using Page.ClientScript)

The last parameter of this method is the "AddScript" parameter. It indicates whether the script should be enclosed within a <script> block. If this is set to false it will effectively be written to the page and not executed (it will appear as text on the rendered page)

The "key" parameter in 1.0 was allowed to be epty(but not null) now in 2.0 if it is empty it will generate a runtime error.


If you have a javascript include with your script (without the script tags) then use the Page.ClientScript.RegisterClientScriptInclude method it will generate code as follows:

<script src="./includedfile.js" type="text/javascript" ></script>

No comments: