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

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:EAjaxTk-AjaxControlToolkitReleaseAjaxControlToolkitExtenderBaseScriptObjectBuilder.cs:293 AjaxControlToolkit.ExtenderControlBase.OnLoad(EventArgs e) in d:EAjaxTk-AjaxControlToolkitReleaseAjaxControlToolkitExtenderBaseExtenderControlBase.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%">
                <asp:Label ID="lblMaxValue" runat="server" Text="Maximum" CssClass="float_right" />
                <asp:Label ID="lblMinValue" runat="server" Text="Minimum" />
            <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 style="text-align:right;width:40%;">                

                    <asp:TextBox ID="txtSlider" runat="server" Text="50" style="display:none;" />
                    <ajaxToolkit:SliderExtender ID="seSlider" runat="server" 
                        Steps="1" />


What is the problem?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

First, start the code block with <%# instead of <%= :

<head id="head1" runat="server">
  <title>My Page</title>
  <link href="css/common.css" rel="nofollow noreferrer noopener" rel="stylesheet" type="text/css" />
  <script type="text/javascript" src="<%# ResolveUrl("~/javascript/leesUtils.js") %>"></script>

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)

Method 2

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"] %>" />

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

Method 3

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


Method 4

Place the javascript under a div tag.

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

It’ll work!!

Method 5

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">  
      <asp:ScriptReference Path="~/Styles/javascript/jquery.min.js" />

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

Method 7

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.

Method 8

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

Method 9

Keep the java script code inside the body tag

   <script type="text/javascript">

Method 10

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 %>" rel="nofollow noreferrer noopener" />


The above code will evaluate to


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


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=<%# " rel="nofollow noreferrer noopener"" + My.Constants.CSS_VERSION %>" />


And you will get the desired result:


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


Method 11

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)

and it worked.

Method 12

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">
    <link href="CSS/AccordionStyles.aspx" rel="nofollow noreferrer noopener" rel="stylesheet" type="text/css" />

The referenced .aspx form contains your content:

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

    cursor: pointer;
    background-image: url(<%=ResolveUrl("~/Images/Backgrounds/AccordionPaneHeaderOpen.png") %>);
    background-repeat: no-repeat;
    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";

Method 13

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

Solution 1:
I kept my script tag in the 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.

Method 14

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>

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.

Method 15

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>

Method 16

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 %>" rel="nofollow noreferrer noopener">Change me</a>
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";

Method 17

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

Method 18

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.

Method 19

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.

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

Method 20

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

Method 21

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


SuccessMessagesContainer.InnerText = "";

   <div class="SuccessMessages ui-state-success" style="height: 25px; display: none;" id="SuccessMessagesContainer" runat="server">
            <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 id="SuccessMessage" style="vertical-align: middle;" class="SuccessMessage" runat="server" >

Method 22

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.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x