0

I am creating a custom control and was wondering if it is possible to render any JavaScript in the head tags of the page it is placed on? I am thinking I would need to use the FindControl method, but am not sure what I need to bind to. I am thinking the page object? Let me know if I am thinking in the right direction or if there is another option.

My only concern with the above mentioned idea is that how do I render all my content while placing some code in the head tags?

Thanks

2 Answers 2

2
protected override void OnPreRender(EventArgs e) {
    base.OnPreRender(e);

    string includeTemplate = "<link rel='stylesheet' type='text/css' href='{0}' />\n";
    string includeLocation = Page.ClientScript.GetWebResourceUrl(GetType(), "Path.To.Resources.css");
    LiteralControl include = new LiteralControl(String.Format(includeTemplate, includeLocation));
    Page.Header.Controls.Add(include);
}

I use this in my control-library to include css and javascript-files.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, if you do:

this.Page.Header

this gives you access to the head element, and you can dynamically add script tags to this. I think I used a LiteralControl to append the script tag statically, and I did it in the Load event, which worked for me fine. I also saw this approach: http://forums.asp.net/t/1306647.aspx

You can also add, not to the head, but in the body, scripts using the ScriptManager.RegisterClientScriptBlock or RegisterClientScriptInclude methods alternatively, if using AJAX (Page.ClientScript has the same methods available too).

HTH.

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.