ASP.NET “Controls cannot be modified [because it contains code blocks]…” error on one server but not another

一曲冷凌霜 提交于 2020-01-14 04:23:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!