3

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?

3
  • Do you want your script tag inside the <head> block or anywhere in the <form runat=server> block? Commented Mar 24, 2009 at 13:02
  • Providing a simple example of "a given problem" would help? Commented Mar 24, 2009 at 13:02
  • @Philippe: I do belive anywhere inside the <form> tag would do fine. Of course, someone else might appriciate a solution for the <head> tag as well. Commented Mar 24, 2009 at 13:12

1 Answer 1

8

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); 
} 
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Good point. Even better if you can do this using RegisterClientScriptInclude
I misunderstood the original question. I voted up your answer. I'll check for RegisterClientScriptInclude when needed, thanks alot!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.