1

I declare my javascript in the design page of a usercontrol (ascx). Is there a way to register this javascript block in the Head section? I don't want to use ClientScript.RegisterClientScriptBlock as I don't want to declare my javascript in the code-behind. I also cannot move it (entirely) into a separate file, because I use business logic to create it.

5
  • What do you mean with "I don't want to declare my javascript in the code-behind"? If you are talking about registering javascript code from a user control on page header, code behind logic will be involved in one way or another. Commented Sep 20, 2010 at 13:10
  • place your control in the Head section? Commented Sep 20, 2010 at 13:13
  • I mean I don't want to create the javascript in the code-behind (string a = "myfun() { .. }"). I would like (if possible) to delcare it inside a container on the design page and register it somehow in the code-behind in the head/bottom body section Commented Sep 20, 2010 at 13:15
  • 1
    What's the point of moving it to head? It'll run fine where it is. If you need something to only happen once regardless of the number of user controls on the page, RegisterClientScriptBlock is the proper tool. Commented Sep 20, 2010 at 13:33
  • I need it to be in either in the head or in the bottom of the body. It will run everywhere, of course. However, for best page-rendering it is better to put all JS code in the bottom of the page. Commented Sep 20, 2010 at 14:21

1 Answer 1

2

I would say that ClientScript.RegisterClientScriptBlock is the way to register scripts from user/custom controls. But as you don't want to put the script in code-behind, you can write the relevant code in ascx page inside server tags. For example,

<script runat="server">

protected override OnPreRender(sender as object, e as EventArgs)
{
   base.onPreRender(sender, e);

   string script;
   // Logic to build the script goes here

   this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Key_" + this.ClientID, script, true);
}

</script>
Sign up to request clarification or add additional context in comments.

Comments

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.