The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>)

谁都会走 提交于 2019-12-21 05:24:04

问题


I am stuck with this error and found a work around and the solutions works for me, but i i would like to know is it the best way to fix the issue and i want to make sure that it wont affect any other pages badly. Hope the experts will help. If this was the best solution then many of you can save your heads.

This error occurs when a code block is placed in the MasterPage. Place the code block in a placeholder to resolve the issue.When adding AJAX extenders to your Web page, it will attempt to register scripts in the head. If code blocks are present in the MasterPage, an error might occur.

To resolve this issue, simply move the code block into a placeholder in the head of your MasterPage, like so:

<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="myPlaceholder" runat="server">
    <script language="javascript" type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/global.js")%>"></script>
    </asp:ContentPlaceHolder>
    <asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>

回答1:


The error is logical you can not confuse the rendered controls after they rendered by using the <%= %>

One way to solve this issue is to use a literal control, and render the script line on code behind.

<asp:ContentPlaceHolder ID="myPlaceholder" runat="server">
    <asp:Literal runat="server" ID="txtIncludeScript" EnableViewState="false"></asp:Literal>
</asp:ContentPlaceHolder>

and on code behind. Check for null because if you change the placeholder the literal is null. Also set EnableViewState=false because you set it on every Page_Load and you do not wish to save it to viewstate.

  if(txtIncludeScript != null)
  {
    txtIncludeScript.Text = 
string.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>",   
Page.ResolveClientUrl("~/javascript/global.js"));
  }



回答2:


ContentPlaceHolder requires a master page, so you can replace that tag with some other element that can be ran at the server in case your page does not have a master page and you cannot get rid of the

<head id="Head1" runat="server">
 <title>Untitled Page</title>
 <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
 <div runat="server">
  <script language="javascript" type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/global.js")%>"></script>
 </div>
 <asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>


来源:https://stackoverflow.com/questions/6774590/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blo

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