395

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:

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?

Mahib
  • 3,977
  • 5
  • 53
  • 62
Daniel P
  • 4,217
  • 3
  • 21
  • 15
  • 16
    What was causing this error for me was using the <%= Resolve(); %> function inside – Daniel P May 22 '09 at 15:09
  • http://stackoverflow.com/questions/4995274/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blo Contains a longer explanation for the `@Daniel P` suggestion. – lko Nov 28 '12 at 14:08
  • Thanks Daniel P, your comment fixed it. I was trying to us ResolveUrl to fix the true URL or a font in @font-face to download that was in a Master Page - unfortunately the master page could run from different locations other than the route - which was causing part of the url to be wrong. So I needed ResolveUrl to work - but the error that you fixed resolved this. Thanks! I put my style inside of – John Foll Jan 25 '23 at 17:24

22 Answers22

516

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();    
}
Jalal El-Shaer
  • 14,502
  • 8
  • 45
  • 51
  • I don't get this error, but I'm using the = notation. However: I've seen my code fail with the above described problem. What can cause that (of why is it working OK with me)? – doekman Jun 28 '10 at 12:43
  • 3
    I seemed to start having this problem after switching to ASP.NET 4. Is it isolated to the new framework? – Corgalore Mar 09 '11 at 18:16
  • The placeholder solution from @Jonas is better... avoid unnecessary data binding. – Chris Haines Sep 13 '13 at 11:15
  • 4
    Its resolved when i copy and paste my Java Script code to the bottom of page. In the previous its placed in HEAD tag. – Miank Feb 05 '14 at 04:15
  • 1
    This is such a bizarre bug with .NET. Why `#` instead of `=`. I'll never understand this one, been doing it for years but wish I knew WHY! – Mark Pieszak - Trilon.io Jan 26 '16 at 16:08
  • Just for another information, change the `Header` on `Page.Header.DataBind();` with the id of your control if it happens on another control. – Yusril Maulidan Raji Sep 26 '16 at 12:20
  • I followed this answer for some time but realized now that the answer below with asp:PlaceHolder blocks is the best answer. I strongly suggest trying that as <%# blocks are hit and miss. They don't work in all cases! – Timothy C. Quinn Jul 07 '21 at 17:44
282

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 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.)

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jonas Stensved
  • 14,378
  • 5
  • 51
  • 80
  • 13
    Awesome. As a past user of Telerik controls, I'd often use their "RadCodeBlock" for the same purpose, but was always annoyed by the fact I didn't know of anything besides that (or as others have mentioned, moving the code into a tag made to run server-side). I never knew these placeholders could have content inside of them. Thank you! – JayC Feb 03 '12 at 03:01
  • 1
    Thank you actually to @JayC, the RadCodeBlock was the only suggestion on this page that worked with the code I inherited, for various reasons. – shiser Oct 27 '12 at 10:44
  • This also occurs with DevExpress controls registered. I have two web applications with almost identical code, configuration and master pages. Only the one with DevExpress requires a workaround like this. I think it's something to do with their HTTP handler, resource assemblies or something like that messing up the pipeline. We're moving away from 3rd party libraries now in favour of JQuery and MVC which allows you to avoid complex server-side code/handlers. – Tony Wall Jul 25 '13 at 10:16
  • 1
    In fact it is enough to wrap it with
    <%= (...) %>
    – Chris W Oct 17 '13 at 13:30
  • 7
    @Teomanshipahi It's actually pretty simple - using code blocks inside of a container means that you can no longer update `Controls` of that container. This basically exploits this behaviour by putting *the code block* in a separate container - so the error would only show up if you wanted to modify `Controls` of the `PlaceHolder`, rather than the parent control. `PlaceHolder` is a great choice for this, because it doesn't have any code of its own (unlike, say `Panel` or `
    `). Although I usually use it the other way around - put the controls I need to modify in `PlaceHolder`.
    – Luaan Jul 14 '15 at 13:38
  • @ZbigniewWiadro The idea is the same, but now you've added a `div` to your generated code. `PlaceHolder` doesn't generate anything, it only renders its contents verbatim. – Luaan Jul 14 '15 at 13:38
  • This is precisely what I'm looking for. I've had issues with the <%# code blocks as they only work in some cases and its hard to figure out why it does work. By wrapping in asp:PlaceHolder blocks, I can use <%= to my hearts extent. – Timothy C. Quinn Jul 07 '21 at 17:41
62

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

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
ITalez
  • 621
  • 5
  • 2
  • 1
    Yes, just confirmed, removing ASP tags <% %> from head fixes this error. – Corgalore Mar 09 '11 at 18:20
  • +1, confirmed as well. For me though the problematic script was outside both the head and form elements. – user420667 Feb 15 '13 at 18:25
  • 1
    Confirmed. Works like a charm for me. Just do not forget to check the scripts on your master page since this was the one who was causing me troubles and I spent like half hour before figuring out that it was not my aspx :P – Luis Hernández Jan 01 '14 at 04:00
  • Yes this worked for me too, but why? Is the tag in a Master file meant to be purely for the Master file and no sub-aspx files? I ask because I am trying to run JS code in a sub-aspx page that resides in the master file. – Fandango68 Oct 07 '15 at 02:03
  • 2
    This answer is an unsung hero. – GreySage Sep 16 '20 at 20:22
  • I was getting the same error in a weird way, I had css files in master page, It used to work for the first page but on the second page after redirecting, I was getting error. So I removed the css link from head tag and pasted it at the end of form tag. – raw_hitt Sep 30 '22 at 14:05
33

Place the JavaScript under a div tag.

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

It'll work!!

SharpC
  • 6,974
  • 4
  • 45
  • 40
Anup
  • 331
  • 3
  • 2
9

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>
Brandon
  • 68,708
  • 30
  • 194
  • 223
6

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

sth
  • 222,467
  • 53
  • 283
  • 367
Nick
  • 61
  • 1
  • 1
5

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.

4

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

Andrei Sfat
  • 8,440
  • 5
  • 49
  • 69
Iori-kyo
  • 349
  • 1
  • 5
  • 15
3

Keep the java script code inside the body tag

<body> 
   <script type="text/javascript">
   </script>
</body>
Bidou
  • 7,378
  • 9
  • 47
  • 70
2

The "<%#" databinding technique will not directly work inside <link> tags in the <head> tag:

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# My.Constants.CSS_VERSION %>" />

</head>

The above code will evaluate to

<head>

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=&lt;%# My.Constants.CSS_VERSION %>" />

</head>

Instead, you should do the following (note the two double quotes inside):

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# "" + My.Constants.CSS_VERSION %>" />

</head>

And you will get the desired result:

<head>

  <link rel="stylesheet" type="text/css" href="css/style.css?v=1.5" />

</head>
perryv
  • 194
  • 1
  • 4
2

I had this problem, but not via the Header. My placeholder was in the body. So I replaced all the <%= with <%# and did

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

and it worked.

bcr
  • 1,983
  • 27
  • 30
1

I had the same problem, but it didn't have anything to do with JavaScript. Consider this code:

<input id="hdnTest" type="hidden" value='<%= hdnValue %>' />
<asp:PlaceHolder ID="phWrapper" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="phContent" runat="server" Visible="false">
    <b>test content</b>
</asp:PlaceHolder>

In this situation you'll get the same error even though PlaceHolders don't have any harmful code blocks, it happens because of the non-server control hdnTest uses code blocks.

Just add runat=server to the hdnTest and the problem is solved.

desperate man
  • 905
  • 1
  • 17
  • 39
1

I also faced the same issue. I found the solutions like following.

Solution 1: I kept my script tag in the body.

<body>
   <form> . . . .  </form>
    <script type="text/javascript" src="<%= My.Working.Common.Util.GetSiteLocation()%>Scripts/Common.js"></script> </body>

Now conflicts regarding the tags will resolve.

Solution 2:

We can also solve this one of the above solutions like Replace the code block with <%# instead of <%= But the problem is it will give only relative path. If you want really absolute path it won't work.

Solution 1 works for me. Next is your choice.

Mihir
  • 8,696
  • 18
  • 56
  • 87
1

I solved an error similar to this by putting the <script> inside a contentplaceholder inside the <head> instead of putting the <script> outside the said contentplaceholder inside the <head>

Taryn
  • 242,637
  • 56
  • 362
  • 405
1

I had the same issue with different circumstances.
I had simple element inside the body tag.
The solution was:

<asp:PlaceHolder ID="container" runat="server">
    <a id="child" href="<%# variable %>">Change me</a>
</asp:PlaceHolder>
protected new void Page_Load(object sender, EventArgs e)
{    
    Page.Form.DataBind(); // I neded to Call DataBind on Form not on Header
    container.InnerHtml = "Simple text";
}
Peter
  • 1,742
  • 15
  • 26
1

I had the same issue with my system, I removed the JavaScript code from the of my page and put it at body just before closing body tag

Jesse Mwangi
  • 155
  • 2
  • 8
1

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

This is what the header of the Masterpage looks like:

<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:

<%@ 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:

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

Try writing your java script code outside the head tag it will definitely work.Its resolved when i copy and paste my Java Script code to the bottom of page. In the previous its placed in HEAD tag now just before closing the form tag.

    </div>
        <script>
                    function validate() {
                        try {

                        var username = document.getElementById("<%=txtUserName.ClientID%>").value;
                        var password = document.getElementById("<%=txtPWD.ClientID%>").value;

                            if (username == "" && password == "")
                                alert("Enter Username and Passowrd");
                            else {
                                if (username == "")
                                    alert("Enter Username");
                                else if (password == "")
                                    alert("Enter Password");
                            }

                        }

                    catch (err) {
                    }
                }
                </script>
</form>
Miank
  • 105
  • 3
  • 13
0

Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind

I removed my JavaScript from the head section of page and added it to the body of the page and got it working

victor
  • 1
0

In my case I got this error because I was wrongly setting InnerText to a div with html inside it.

Example:

SuccessMessagesContainer.InnerText = "";

   <div class="SuccessMessages ui-state-success" style="height: 25px; display: none;" id="SuccessMessagesContainer" runat="server">
      <table>
         <tr>
            <td style="width: 80px; vertical-align: middle; height: 18px; text-align: center;">
               <img src="<%=Image_success_icn %>" style="margin: 0 auto; height: 18px;
                  width: 18px;" />
            </td>
            <td id="SuccessMessage" style="vertical-align: middle;" class="SuccessMessage" runat="server" >
            </td>
         </tr>
      </table>
   </div>
live-love
  • 48,840
  • 22
  • 240
  • 204
0

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.

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.

Mohammed Hameed
  • 73
  • 1
  • 10
-1

Tags <%= %> not works into a tag with runat="server". Move your code with <%= %> into runat="server" to an other tag (body, head, ...), or remove runat="server" from container.

Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94