Friday, July 07, 2006

Passing values to JavaScript

Q: I have an ASP.Net application where I would like to pass the value of a variable to JavaScript code on the same page. How can I do that?

A: An article found at http://aspalliance.com/ArticleViewer.aspx?aid=851&pid=-1 explains exactly how to do that. First, place the script in a separate .js file. Then pass the required value to the script using Page.ClientScript.RegisterClientScriptBlock().

In ASP.Net 2.0 Page.ClientScript.RegisterClientScriptBlock() is used to download and store a script in a browser's cache for quicker reponse in the browser.

Another similar method is Page.ClientScript.RegisterStartupScript(). This method is best used when you have a JavaScript function that you want to initiate when the page is loaded. The code, including this method call, would be placed in the Page_Load() event handler.

For more information, go to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/JAVAwASP2.asp.

No comments: