C# “控件集合无法修改,因为控件包含代码块”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:48:32  来源:igfitidea点击:

"The Controls collection cannot be modified because the control contains code blocks"

c#asp.netuser-controls

提问by Daniel P

I am trying to create a simple user control that is a slider. When I add a AjaxToolkit SliderExtender to the user control I get this (*&$#()@# error:

我正在尝试创建一个简单的用户控件,它是一个滑块。当我将 AjaxToolkit SliderExtender 添加到用户控件时,我得到了这个 (*&$#()@# 错误:

Server Error in '/' Application. The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`). Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): The Controls collection cannot be modified because the control contains code blocks (i.e. `<% ... %>`).]    System.Web.UI.ControlCollection.Add(Control child) +8677431    AjaxControlToolkit.ScriptObjectBuilder.RegisterCssReferences(Control control) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ScriptObjectBuilder.cs:293 AjaxControlToolkit.ExtenderControlBase.OnLoad(EventArgs e) in d:\E\AjaxTk-AjaxControlToolkit\Release\AjaxControlToolkit\ExtenderBase\ExtenderControlBase.cs:306 System.Web.UI.Control.LoadRecursive()
+50    System.Web.UI.Control.LoadRecursive()
+141    System.Web.UI.Control.LoadRecursive()
+141    System.Web.UI.Control.LoadRecursive()
+141    System.Web.UI.Control.LoadRecursive()             
+141    System.Web.UI.Control.LoadRecursive()
+141    System.Web.UI.Control.LoadRecursive()
+141    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627


Version Information: Microsoft .NET Framework Version:2.0.50727.3074; ASP.NET Version:2.0.50727.3074

I have tried putting a placeholder in the user control and adding the textbox and slider extender to the placeholder programmatically and I still get the error.

我尝试在用户控件中放置一个占位符,并以编程方式将文本框和滑块扩展器添加到占位符,但仍然出现错误。

Here is the simple code:

这是简单的代码:

<table cellpadding="0" cellspacing="0" style="width:100%">
    <tbody>
        <tr>
            <td></td>
            <td>
                <asp:Label ID="lblMaxValue" runat="server" Text="Maximum" CssClass="float_right" />
                <asp:Label ID="lblMinValue" runat="server" Text="Minimum" />
            </td>
        </tr>
        <tr>
            <td style="width:60%;">
                <asp:CheckBox ID="chkOn" runat="server" />
                <asp:Label ID="lblPrefix" runat="server" />:&nbsp;
                <asp:Label ID="lblSliderValue" runat="server" />&nbsp;
                <asp:Label ID="lblSuffix" runat="server" />
            </td>
            <td style="text-align:right;width:40%;">                

                    <asp:TextBox ID="txtSlider" runat="server" Text="50" style="display:none;" />
                    <ajaxToolkit:SliderExtender ID="seSlider" runat="server" 
                        BehaviorID="seSlider" 
                        TargetControlID="txtSlider" 
                        BoundControlID="lblSliderValue" 
                        Orientation="Horizontal" 
                        EnableHandleAnimation="true" 
                        Length="200" 
                        Minimum="0" 
                        Maximum="100" 
                        Steps="1" />

            </td>
        </tr>
    </tbody>
</table>

What is the problem?

问题是什么?

采纳答案by Jalal El-Shaer

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:

这会将代码块从 Response.Write 代码块更改为数据绑定表达式。
由于<%# ... %>数据绑定表达式不是代码块,CLR 不会抱怨。然后在母版页的代码中,添加以下内容:

protected void Page_Load(object sender, EventArgs e)
{
  Page.Header.DataBind();    
}

回答by Daniel P

I had same issue in the user control. My page that was hosting the control had comments in the head tag, I removed those comments, everything worked afterwards. Some posts also suggest removing scripts from head and placing them in the body.

我在用户控件中遇到了同样的问题。我托管控件的页面在 head 标签中有评论,我删除了这些评论,之后一切正常。一些帖子还建议从 head 中删除脚本并将它们放在 body 中。

回答by Nick

I tried using <%# %>with no success. Then I changed Page.Header.DataBind();in my code behind to this.Header.DataBind();and it worked fine.

我尝试使用但<%# %>没有成功。然后我Page.Header.DataBind();在后面的代码中更改为this.Header.DataBind();,它工作正常。

回答by ITalez

I can confirm that moving the javascript with <% %>tags from the head to the form tag fixes this error

我可以确认将带有<% %>标签的 javascript从头部移动到表单标签修复了这个错误

http://italez.wordpress.com/2010/06/22/ajaxcontroltoolkit-calendarextender-e-strana-eccezione/

http://italez.wordpress.com/2010/06/22/ajaxcontroltoolkit-calendarextender-e-strana-eccezione/

回答by Mohan Prajapati

you can do the same functionality if you are using script manager in your page. you have to just register the script like this

如果您在页面中使用脚本管理器,则可以执行相同的功能。你只需要像这样注册脚本

<asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"   EnablePageMethods="true">  
<Scripts>
      <asp:ScriptReference Path="~/Styles/javascript/jquery.min.js" />
</Scripts>
</asp:ScriptManager>

回答by Anup

Place the javascript under a div tag.

将 javascript 放在 div 标签下。

<div runat="server"> //div tag must have runat server
  //Your Jave script code goes here....
</div>

It'll work!!

它会工作!!

回答by Jonas Stensved

I just ran into this problem as well but found another solution.

我也遇到了这个问题,但找到了另一个解决方案。

I found that wrapping the code blocks with a asp:PlaceHolder-tag solves the problem.

我发现用 asp:PlaceHolder-tag 包装代码块可以解决这个问题。

<asp:PlaceHolder runat="server">
  <meta name="ROBOTS" content="<%= this.ViewData["RobotsMeta"] %>" />
</asp:PlaceHolder>

(The CMS I'm using is inserting into the head-section from some code behind which restricted me from adding custom control blocks with various information like meta-tags etc so this is the only way it works for me.)

(我使用的 CMS 是从后面的一些代码插入头部部分,这些代码限制了我添加带有各种信息(如元标记等)的自定义控制块,因此这是它对我有用的唯一方法。)

回答by Iori-kyo

In my case, I have replaced <%= %>with <%# %>, and it worked!

就我而言,我已替换<%= %><%# %>,并且有效!

回答by Hugo

An alternative way is to have another .aspx page act as the page you want to link to.

另一种方法是让另一个 .aspx 页面充当您要链接到的页面。

This is what the header of the Masterpage looks like:

这是 Masterpage 的标题的样子:

<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
    <link href="CSS/AccordionStyles.aspx" rel="stylesheet" type="text/css" />
</head>

The referenced .aspx form contains your content:

引用的 .aspx 表单包含您的内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AccordionStyles.aspx.cs" Inherits="IntranetConnectCMS.CSS.AccordionStyles" %>
.AccordionHeader
{
    cursor: pointer;
    background-image: url(<%=ResolveUrl("~/Images/Backgrounds/AccordionPaneHeaderClosed.png") %>);
    background-repeat: no-repeat;
}

.AccordionHeaderSelected
{
    cursor: pointer;
    background-image: url(<%=ResolveUrl("~/Images/Backgrounds/AccordionPaneHeaderOpen.png") %>);
    background-repeat: no-repeat;
}
.AccordionContent
{
    background-image: url(<%=ResolveUrl("~/Images/Backgrounds/AccordionPaneContent.png") %>);
    background-repeat: no-repeat;
}

Finally, you need the .aspx page to tell the browser you're sending CSS content:

最后,您需要 .aspx 页面来告诉浏览器您正在发送 CSS 内容:

protected void Page_Load(object sender, EventArgs e)
{
    Response.ContentType = "text/css";
}

回答by mdhameed

For some cases ResolveUrl and ResolveClientUrl works but not all times especially in case of js script files. What happens is it works for some pages but when you navigate to some other pages it might not work due to relative path of that particular page.

在某些情况下, ResolveUrl 和 ResolveClientUrl 有效,但并非总是如此,尤其是在 js 脚本文件的情况下。发生的情况是它适用于某些页面,但是当您导航到其他一些页面时,由于该特定页面的相对路径,它可能无法工作。

So finally my suggestion is always do a complete recheck of your site pages for whether all your javascript references are fine or not. Open your site in Google Chrome -> right click on the page -> click view source page -> HTML appears -> now click your JS hyperlinks; if its working fine it should open the js file in another browser window, otherwise it will not open.

所以最后我的建议是始终对您的网站页面进行全面的重新检查,以确定您的所有 javascript 引用是否正常。在谷歌浏览器中打开您的网站 -> 右键单击​​该页面 -> 单击查看源页面 -> 出现 HTML -> 现在单击您的 JS 超链接;如果它工作正常,它应该在另一个浏览器窗口中打开 js 文件,否则它不会打开。