An old question ... but I just ran into this problem, and it was message # 1, which continued to appear on Google, so I will add my answer as others did not work in my case.
This is how I did it when the regular <asp:Content
didn't work (although with normal use, @JayC's answer is how you do it):
MasterPage has this ContentPlaceHolder
:
<asp:ContentPlaceHolder ID="ScriptsPlace" runat="server"></asp:ContentPlaceHolder>
I had to dynamically add JavaScript from User Control. Attempting to use ContentPlaceHolder
directly gives this error:
Parser error message: Content controls must be top-level items on the content page or in the nested master page that links to the master page
So, I wanted to add a script from the code. Here is the Download page for the .ascx
file:
protected void Page_Load(object sender, EventArgs e) { ContentPlaceHolder c = Page.Master.FindControl("ScriptsPlace") as ContentPlaceHolder; if (c != null) { LiteralControl l = new LiteralControl(); l.Text="<script type=\"text/javascript\">$(document).ready(function () {js stuff;});</script>"; c.Controls.Add(l); } }
UPDATE:. Turns out I had to use this in more places than I expected, and ended up using a method that was much more flexible / readable. In the user element itself, I just wrapped javascript and everything else that needed to be moved using a regular div
.
<div id="_jsDiv" runat="server"> $(document).ready(function() {
And then the code behind will find the div, and then move it to the ContentPlaceHolder
.
protected void Page_Load(object sender, EventArgs e) { ContentPlaceHolder c = Page.Master.FindControl("ScriptsPlace") as ContentPlaceHolder; HtmlGenericCOntrol jsDiv = this.FindControl("_jsDiv") as HtmlGenericControl; if (c != null && jsDiv != null) { c.Controls.Add(jsDiv); } }
I really put this code in a user control, and I have regular user controls inherited from the user control, so as soon as I finish javascript / etc with <div id="_jsDiv" runat="server">
, the user the control will take care of the rest, and I donβt need to do anything in the control code of the user control.