0

I know this has been asked, but I have a more complicated issue than in other relevant questions.

I need to reference CSS and JS from my usercontrol.

References must be rendered inside <head> tag. For this reason I cannot use ScriptManager.RegisterClientScriptBlock

Other solution I found:

    HtmlLink link = new HtmlLink();
    link.Href = "/path/style.css";
    link.Attributes["type"] = "text/css";
    link.Attributes["rel"] = "stylesheet";
    Page.Header.Controls.Add(link);

However this ends up with "The Controls collection cannot be modified because the control contains code blocks" The problem is those code blocks are located in master page file which I don't have a control over. So workarounds suggested in this thread are not possible. (E.g.: wrap code block in <asp:placeholder ID="Placeholder1" runat="server"> or replace <%= with <%#

So considering above constraints, is it possible to place <link href='path' /> and <script src='path' /> inside <head> tag from User control?

Community
  • 1
  • 1
Sergej Popov
  • 2,933
  • 6
  • 36
  • 53

2 Answers2

1

You could add a LiteralControl to the head.

Page.Header.Controls.Add(new LiteralControl("<script src'...'></script"));
jon
  • 728
  • 5
  • 12
  • 1
    Still produces same error: ***"The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)."*** – Sergej Popov Jan 22 '13 at 09:29
0

Solution that worked for me:

Nesting Master page, and adding placeholder to nested Master page, then adding Literal Control as suggested by jon:

stylePlaceholder = ((PlaceHolder)((ContentPlaceHolder)Page.Master.Master.FindControl("HeadSection")).FindControl("phd_ControlsStyles"));

stylePlaceholder.Controls.Add(new LiteralControl(css + " href=\"http://" + cdn + "/Utils/Bundle/" + getCss() + ".css?v=" + settings["subVersion"] + "\" />"));
Sergej Popov
  • 2,933
  • 6
  • 36
  • 53