I am trying to create dynamic meta tags in C# but it gives the following error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
This is the code I added:
HtmlMeta meta = new HtmlMeta();
meta.Name = "keywords";
meta.Content = "book,paper";
Page.Header.Controls.Add(meta);
Thank you very much.
It's hard to tell for sure because you haven't included many details, but I think what is going on is that there are <% ... %>
code blocks inside your Page.Header
(which is referring to <head runat="server">
- possibly in a master page). Therefore, when you try to add an item to the Controls collection of that control, you get the error message in the title of this question.
If I'm right, then the workaround is to wrap a <asp:placeholder runat="server">
tag around the <% ... %>
code block. This makes the code block a child of the Placeholder control, instead of being a direct child of the Page.Header
control, but it doesn't change the rendered output at all. Now that the code block is not a direct child of Page.Header
you can add things to the header's controls collection without error.
Again, there is a code block somewhere or you wouldn't be seeing this error. If it's not in your aspx page, then the first place I would look is the file referenced by the MasterPageFile
attribute at the top of your aspx.
Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Regards Örvar
Check out the solutions at "The Controls collection cannot be modified because the control contains code blocks"
The accepted solution on the other question worked for me -- change instances of <%=
to <%#
, which converts the code block from Response.Write
to an evaluation block, which isn't restricted by the same limitations.
In this case though, like the accepted solution here suggests, you should add the controls to something other than a masterpage ContentPlaceHolder element, namely the asp:Placeholder
control suggested.
I have had the same issue that I solved this way:
Instead of adding the meta to the current page header that caused the same error as you had:
Page.Header.Controls.Add(meta);
I used this instead:
Master.FindControl("YourHeadContentPlaceHolder").Controls.Add(meta);
and it works like a charm.
For those using Telerik as mentioned by Ovar, make sure you wrap your javascript in
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Since Telerik doesn't recognize <%# %> when looking for an element and <%= %> will give you an error if your javascript code isn't wrapped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With