问题
I've got a web app that works on my local computer and our test server but is failing in production with this error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
I've read in a couple places that this can be fixed by changing <%=...%>
to <%#...%>
, but it intrigues me that the error comes up only in production. What differences in configuration could be causing this?
Complete stack trace (note that it includes the Ajax Toolkit):
System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
at System.Web.UI.ControlCollection.Add(Control child)
at AjaxControlToolkit.ScriptObjectBuilder.RegisterCssReferences(Control control)
at AjaxControlToolkit.ExtenderControlBase.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
回答1:
I've come up with something I find a lot easier and more straightforward -- while leaving the tag in the header where it belongs.
First, start the code block with <%# instead of <%= :
<head id="head1" runat="server">
<title>My Page</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script>
</head>
This changes the code block from a Response.Write code block to a databinding expression. Since <%# ... %> databinding expressions aren't code blocks, the CLR won't complain. Then in the code for the master page, you'd add the following:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
The DataBind method evaluates all the databinding expression(s) in your header at load time.
回答2:
Try to remove <% %> and add your attributes/texts from your code behind
回答3:
wrap your head content where "<%=" used in a placeholder like so:
<asp:PlaceHolder Runat="server">
<script type="text/javascript" src="<%= ResolveUrl("~/script.js") %>">
<link rel="stylesheet" type="text/css" href="<%= ResolveUrl("~/style.css") %>"/>
</asp:PlaceHolder>
来源:https://stackoverflow.com/questions/6614481/asp-net-controls-cannot-be-modified-because-it-contains-code-blocks-error