Friday, May 10, 2013

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

Introduction: 

Here I will explain how to solve the problem “The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).” when running web application using asp.net. 

Description: 

I created one web application and added some of script files in header section of page like this

<head id="head2" runat="server">
<title>Lightbox Page</title>
<link href="aspdotnetsuresh.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= ResolveUrl("~/js/LightBox.js") %>"></script>
</head>
After add script file to header section i tried to run the application during that time I got error like 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.

To solve this problem we have different methods
First Method
Remove JavaScript from the header section of page and add it to body of the page and run your application it will work for you.
Second Method
Replace the code block with <%# instead of <%=
<head id="head2" runat="server">
<title>Lightbox Page</title>
<link href="aspdotnetsuresh.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/js/LightBox.js") %>"></script>
</head>
After replace code block with <%# instead of <%= add following code in page load

protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();    
}
After add code run your application it will work for you.

Happy Coding………

No comments:

Post a Comment