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

Server Error in 'ASP.Net' 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. <% ... %>).
____________________________________________________________________________

Recently I have faced this type of error on browse my application after add JavaScript method. This is the first time I have faced this issue. Newly written method is double checked by me but nothing found. Then try to find in asp.net forum now this time got the solution :).

Very silly mistake......now I have share with you.


Problem

if we are adding some server side controls to the head section of aspx page, we used the following JavaScript which had the <% %> tags to get the ClientID of a server side control.

<head runat="server">
<title>Untitled Page</title>
<script type = "text/javascript">
function GetAgentName()
{
var lblAgentName = document.getElementById("<%=lblAgent.ClientID%>");
alert(lblAgentName.value);
}
</script>
</head>

Therefore we have used ASP.Net Server tags to get the ClientID we need to use <% %> tags but unfortunately you cannot add controls dynamically at head section of a page.
It causes the same error.


Solution

1.Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind. You can add this javascript code to the html body it will solve your problem.

2. You can use <%# instead of <%=

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. If you use Master page then you'd add the following:

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

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript