views:

320

answers:

1

From time to time I run into situation in which I could solve a given problem by dynamicly creating piece of JavaScript, spesific to that instance of the page, that I could then insert in the final markup. Usualy this is because I want some behaviour to happen on the client side, rather than on the server side and creating a static JavaScript isn't an option.
For example, when trying to submit a files original path without submitting the file itself, when trying to do it for multiple dynamicly created components.

How would you recommend me to create a script tag and populate it with, for example, JavaScript?

+7  A: 

Use your page's ClientScriptManager and it's RegisterClientScriptBlock() method.

string javascript = "javascript goes here"; 
string scriptname = "Name of this script"; // used to prevent adding the same script twice at two places in the page life cycle
if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptname)) 
{ 
    Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), scriptname, javascript, true); 
}
Joel Coehoorn
Writing javascript in code-behind is a bad practice. When you need to tweak or change the behavior of UI, you need to recompile all the project.
Philippe
Good point. Even better if you can do this using RegisterClientScriptInclude
Joel Coehoorn
I misunderstood the original question. I voted up your answer. I'll check for RegisterClientScriptInclude when needed, thanks alot!
Philippe
You could also create an HttpHandler (*.ashx) file to spit out the javascript, and just use a normal script tag in your markup that points to that handler.
Joel Coehoorn