coder
coder

Reputation: 13248

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

I am sorry if my tags were incorrect and I am having a simple problem from your end but it drives me crazy.

I am having the error mentioned in my question and just now I found many articles on the net stating to add some of the below workarounds to get this work. But none worked out for me. Here are some of them:

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

<%= ResolveUrl("~/js/main.js") %>

Onpage load:

Page.Header.Databind()

And instead of <%= %> I used this way <%# %>

I am having masterpage,default.aspx and main.aspx page In my main.aspx this is my code:

    <asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            $("a[rel=group1]").live("click", function () {
                $("a[rel^='group1']").colorbox({ opacity: 0.6, open: true });
                return false;
            });
        });
    </script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
                        $("img[rel^='group1']").live("click", function () {
                            $("img[rel^='group1']").colorbox({ opacity: 0.6, open: true });
                            return false;
                        });
                });
    </script>
  <script type="text/javascript">
      $(function () {
          $("#tabs").tabs();
      });
    </script>

    <script type="text/javascript">
        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Uploading!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () {

                }
            });
         }


        function showStickySuccessToast1() {
            $().toastmessage('showToast', {
                text: 'Finished Watermarking!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () {

                }
            });
        }
    </script>

   <script type="text/javascript">
       $(document).ready(function () {
           $("#<%=Nextbutton.ClientId%>").click(function (event) {
               $('#tabs').tabs('select', 1);
               return false;
           });
           $("#<%=ConfirmTextSettings.ClientId%>").click(function (event) {
               $.msgBox({
                   title: "would you like to cotinue?",
                   content: "Are you sure want to watermark with these settings?",
                   type: "confirm",
                   buttons: [{ value: "Yes" }, { value: "No" }, { value: "Cancel"}],
                   success: function (result) {
                       if (result == "Yes") {
                           $('#tabs').tabs('select', 2);
                       }
                   }
               });
               return false;
           });
           $("#<%=ConfirmImageSettings.ClientId%>").click(function (event) {
               $.msgBox({
                   title: "would you like to cotinue?",
                   content: "Are you sure want to watermark with these settings?",
                   type: "confirm",
                   buttons: [{ value: "Yes" }, { value: "No" }, { value: "Cancel"}],
                   success: function (result) {
                       if (result == "Yes") {
                           $('#tabs').tabs('select', 2);
                       }
                   }
               });
               return false;
           });
       });
    </script>
    <asp:PlaceHolder runat="server" ID="ImageScript">
    <script type="text/javascript">
        $(function () {
            document.getElementById('<%=Nextbutton.ClientId%>').style.visibility = "hidden";
            $("#<%=uploader.ClientId%>").plupload({
                runtimes: 'gears,flash,silverlight,browserplus,html5',
                url: 'Watermarker.aspx',
                max_file_size: '10mb',
                max_file_count: 26,
                chunk_size: '1mb',
                unique_names: true,
                rename: true,
                dragdrop: true,
                filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

                flash_swf_url: 'js/plupload.flash.swf',


                silverlight_xap_url: 'js/plupload.silverlight.xap'
            });



            $('form').submit(function (e) {
                var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');


                if (uploader.files.length > 0) {

                    uploader.bind('StateChanged', function () {
                        if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                            $('form')[0].submit();
                        }
                    });

                    uploader.start();
                }
                else
                //alert('You must at least upload one file.');

                    return false;
            });



            var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
            uploader.bind('FilesAdded', function (up, files) {

                var i = up.files.length,
                maxCountError = false;

                plupload.each(files, function (file) {
                    setTimeout(function () {
                        up.start();
                    }, 100);



                    if (uploader.settings.max_file_count && i >= uploader.settings.max_file_count) {
                        $.msgBox({
                            title: "Info",
                            content: "Uuh! Please don't put me any more files.<br>Maximum Upload limit is only 25 Images.<br>Rest of the Images will be removed.",
                            type: "info",
                            showButtons: true,
                            opacity: 0.1,
                            autoClose: false
                        });
                        uploader.removeFile(up.files[i - 1]);
                    } else {

                    }
                });
            });


            var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader');
            uploader.bind('FileUploaded', function (up, file, res) {

                $('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "><a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' rel='group1'><img class='clickImage' src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='75' height='50' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>");
                if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                    showStickySuccessToast();
                    document.getElementById('<%=Nextbutton.ClientId%>').style.visibility = "visible";
                }
            });
        });




        function randomString(length) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

            if (!length) {
                length = Math.floor(Math.random() * chars.length);
            }

            var str = '';
            for (var i = 0; i < length; i++) {
                str += chars[Math.floor(Math.random() * chars.length)];
            }
            return str;
        }
    </script>
    </asp:PlaceHolder>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=Panel2.ClientId%>').hide();
            $('#<%= RbtxtWatermark.ClientID %>').click(function () { $('#<%=Panel1.ClientId%>').show(); $('#<%=Panel2.ClientId%>').hide(); });
            $('#<%= RbImgWatermark.ClientID %>').click(function () { $('#<%=Panel2.ClientId%>').show(); $('#<%=Panel1.ClientId%>').hide(); });
        });
</script>
<script type="text/javascript">
    function StartUpload() {
        $("imgDisplay").hide();
    }
    function UploadComplete(sender, args) {
        $("#imgDisplay").show();
        $("#imgDisplay").attr('src', 'ajax-loader.gif');
        var img = new Image();
        img.src = args.get_fileName();

        img.onload = function () {
            $("#imgDisplay").attr('src', img.src);
        };
    }
    </script>
    <div id="tabs" style="position:relative;margin-left:0px;margin-top:30px;margin-bottom:30px;width:946px; height:432px;">
    <ul>
        <li><a href="#tabs-1">Preview</a></li>
        <li><a href="#tabs-2">Settings</a></li>
        <li><a href="#tabs-3">Watermark</a></li>
    </ul>
    <div id="tabs-1">
    <div id="uploader" class="container" runat="server">
        <p>
            You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
    </div>
    <div id="thumbs" class="imgContain" runat="server">
    <asp:Button ID="Nextbutton" runat="server" Text="Go to Next Step" style="position:absolute;left:332px;top:345px;"/>
    <script type="text/javascript">
        $('#<%=Nextbutton.ClientId%>').button();
    </script>
    </div>
    </div> 
    <div id="tabs-2">
    <table>
    <tr>
    <td>
        <asp:RadioButton ID="RbtxtWatermark" runat="server" Text="Text Watermark" ForeColor="White" GroupName="selection" Checked="True" />
       </td>
    <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
    <td>
     <asp:RadioButton ID="RbImgWatermark" runat="server" Text="Image Watermark" ForeColor="White" GroupName="selection"/>
    </td>
    </tr>
    </table>
        <asp:Panel ID="Panel1" runat="server">
        <script type="text/javascript">
            function colorChanged(sender) {
                sender.get_element().style.color = "#" + sender.get_selectedColor();
            }
        </script>
        <table>
        <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="Enter Watermark Text :"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="txtSample" runat="server" Text="(C)Copyright" Height="20px"></asp:TextBox>
        </td>
        </tr>
        <tr>
         <td>
                                    <asp:Label ID="Label2" runat="server" Text="Font Name:"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropFont" runat="server">
                                    </asp:DropDownList>
                                </td>
        </tr>
         <tr>
                                <td>
                                    <asp:Label ID="Label3" runat="server" Text="Font Size:"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropFontSize" runat="server">
                                        <asp:ListItem Value="6">6</asp:ListItem>
                                        <asp:ListItem Value="8">8</asp:ListItem>
                                        <asp:ListItem Value="10">10</asp:ListItem>
                                        <asp:ListItem Value="12">12</asp:ListItem>
                                        <asp:ListItem Value="14">14</asp:ListItem>
                                        <asp:ListItem Value="18">18</asp:ListItem>
                                        <asp:ListItem Value="24">24</asp:ListItem>
                                        <asp:ListItem Value="32">32</asp:ListItem>
                                        <asp:ListItem Value="36">36</asp:ListItem>
                                        <asp:ListItem Value="40">40</asp:ListItem>
                                        <asp:ListItem Value="48">48</asp:ListItem>
                                        <asp:ListItem Value="52">52</asp:ListItem>
                                        <asp:ListItem Value="56">56</asp:ListItem>
                                        <asp:ListItem Value="62">62</asp:ListItem>
                                        <asp:ListItem Value="68">68</asp:ListItem>
                                        <asp:ListItem Value="72">72</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                            </tr>
                             <tr>
                                <td>
                                    <asp:Label ID="Label4" runat="server" Text="Text Color:"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox runat="server" ID="txtColor1" AutoCompleteType="None" MaxLength="6"
                                        Width="80" Height="20" /><br />
                                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/icon_colorpicker.gif"
                                        Style="position: absolute; margin-top: -20px; left: 245px;"/>
                                    <cc1:ColorPickerExtender ID="buttonCPE" runat="server" TargetControlID="txtColor1"
                                        SampleControlID="ImageButton1" PopupButtonID="ImageButton1" PopupPosition="TopLeft"/>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label5" runat="server" Text="Text Opacity:"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropTransparency" runat="server">
                                        <asp:ListItem Value="0%">0%</asp:ListItem>
                                        <asp:ListItem Value="25%">25%</asp:ListItem>
                                        <asp:ListItem Value="50%">50%</asp:ListItem>
                                        <asp:ListItem Value="75%">75%</asp:ListItem>
                                        <asp:ListItem Value="100%">100%</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label6" runat="server" Text="Text Effects:"></asp:Label>
                                </td>
                                <td>
                                    <asp:CheckBox ID="CheckBoxSolid" runat="server" Text="Solid" ForeColor="White" />
                                    <asp:CheckBox ID="CheckBoxOutline" runat="server" Text="Outline" ForeColor="White" />
                                </td>
                            </tr>
                            <tr>
                             <td>
                                    <asp:Label ID="Label7" runat="server" Text="Text Decoration:"></asp:Label>
                                </td>
                                <td>
                                    <asp:CheckBox ID="CheckBold" runat="server" Text="Bold" ForeColor="White" />
                                    <asp:CheckBox ID="CheckItalic" runat="server" Text="Italic" ForeColor="White" />
                                    <asp:CheckBox ID="CheckUnderline" runat="server" Text="Underline" ForeColor="White" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label8" runat="server" Text="Text Shadow:"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropShadow" runat="server">
                                        <asp:ListItem Value="Yes">Yes</asp:ListItem>
                                        <asp:ListItem Value="No">No</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label9" runat="server" Text="Text Shadow Color:"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtShadowColor" runat="server" Width="80px" Height="20px"></asp:TextBox>
                                </td>
                                <td>
                                    <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/Images/icon_colorpicker.gif"
                                        Style="position: absolute; margin-top: -10px; left: 245px;" />
                                    <cc1:ColorPickerExtender ID="ColorPickerExtender2" runat="server" TargetControlID="txtShadowColor"
                                        SampleControlID="ImageButton2" PopupButtonID="ImageButton2" PopupPosition="TopLeft"/>
                                </td>
                            </tr>
                             <tr>
                                <td>
                                    <asp:Label ID="Label10" runat="server" Text="Position of Text:"></asp:Label>
                                </td>
                                <td>
                                    <asp:Label ID="Label11" runat="server" Text="Margin-Left:"></asp:Label>
                                    <asp:TextBox ID="txtmarginleft" runat="server" Text="10" Width="50"></asp:TextBox>
                                    <asp:Label ID="Label12" runat="server" Text="Margin-Top:"></asp:Label>
                                    <asp:TextBox ID="txtmargintop" runat="server" Width="50" Text="10"></asp:TextBox>
                                </td>
                            </tr>
                             <tr>
                                <td>
                                    <asp:Label ID="Label13" runat="server" Text="Rotation of Text:"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtrotate" runat="server" Text="0" Width="50"></asp:TextBox>&nbsp;<asp:Label
                                        ID="Label14" runat="server" Text="Degrees"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                            <td>
                            <asp:Button ID="ConfirmTextSettings" runat="server" Text="Go to Next Step" style="position:absolute;left:812px;top:395px;"/>
                            <script type="text/javascript">
                                $('#<%=ConfirmTextSettings.ClientId%>').button();
                            </script>
                            </td>
                            </tr>
        </table>
        </asp:Panel>
        <asp:Panel ID="Panel2" runat="server">
        <table>
        <tr>
        <td>
            <asp:Label ID="Label15" runat="server" Text="Add Image"></asp:Label>
        </td>
        <td>
                                    <cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadComplete="UploadComplete"
                                        OnClientUploadStarted="StartUpload" ThrobberID="imgLoader" Width="230px" OnUploadedComplete="AsyncFileUpload1_UploadedComplete"
                                        Style="float: left;"  ClientIDMode="AutoID"/>
                                    <asp:Image ID="imgLoader" runat="server" ImageUrl="~/images/ajax-loader.gif" Style="position: absolute;
                                        left: 370px; top: 75px;" />
                                </td>
        </tr>
        <tr>
                                <td>
                                    <img id="imgDisplay" alt="" src="" style="display: none;" height="80"/>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="Label16" runat="server" Text="Image Opacity in %:"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="DropDownImgOpacity" runat="server">
                                        <asp:ListItem Value="0%">0</asp:ListItem>
                                        <asp:ListItem Value="25%">25</asp:ListItem>
                                        <asp:ListItem Value="50%">50</asp:ListItem>
                                        <asp:ListItem Value="75%">75</asp:ListItem>
                                        <asp:ListItem Value="100%">100</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                            </tr>
                            <tr>
                            <td>
                            <asp:Button ID="ConfirmImageSettings" runat="server" Text="Go to Next Step" style="position:absolute;left:812px;top:395px;"/>
                            <script type="text/javascript">
                                $('#<%=ConfirmImageSettings.ClientId%>').button();
                            </script>
                            </td>
                            </tr>
        </table>
        </asp:Panel>
    </div>
    <div id="tabs-3">
      Are you sure want to process your images?<br />If so click on the watermark images button below<br />
                <br />
                    <asp:Button ID="btnWatermark" runat="server" Text="Watermark Images" style="position:absolute;left:20px;top:105px;" OnClick="btnWatermark_Click"/>
                    <script type="text/javascript">
                    $('#<%=btnWatermark.ClientId%>').button();
                    </script>
             <%--   <asp:Button ID="btnWatermark" runat="server" Text="Watermark Your Images" OnClick="btnWatermark_Click"
                                            Font-Size="12" Font-Bold="True" Style="position: absolute; top: 105px; left: 5px;
                                            height: 40px;" CssClass="ui-button ui-widget ui-state-default ui-corner-all" />--%>

                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                        <ContentTemplate>
                            <table style="width: 100%;">
                                <tr>
                                    <td>

                                        <asp:HyperLink ID="DownloadLink" runat="server" ForeColor="#0066FF" style="position:absolute;left:670px;top:404px;">Download Images</asp:HyperLink>
                                            <script type="text/javascript">
                                                $('#<%=DownloadLink.ClientId%>').button();
                                            </script>
                                    </td>
                                </tr>
                                <tr>
                                   <%-- <asp:Image ID="Preview" runat="server" Height="150" Width="200" Style="position: absolute;
                                        top: 170px; left: 100px;" BorderStyle="None" />--%>
                                        <div id="FinalPreview" class="imgContainPreview" runat="server">
                                        </div>
                                </tr>
                            </table>
                             <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="0">
                                <ProgressTemplate>
                                    <div style="position: absolute; top: 140px; left: 650px;">
                                        <img src="images/Loader.gif" alt="loading" /><br />
                                        <span style="font-weight: bold; font-size: large; color: #000000;">Please wait...</span>
                                    </div>
                                </ProgressTemplate>
                            </asp:UpdateProgress>
                       </ContentTemplate>
                            <Triggers>
                            <asp:AsyncPostBackTrigger ControlID="btnWatermark" EventName="Click" />
                            </Triggers>

                    </asp:UpdatePanel>

    </div>
    </div> 

    <input type="hidden" id="currentDirectory" runat="server" />
    <asp:TextBox ID="CopySession" runat="server" Visible="True"></asp:TextBox>
</asp:Content>

In my page_load:

For Each str As String In Directory.GetFiles(Server.MapPath("~/WatermarkedImages/") & Session("tempDir").ToString())
            Dim filename As String = Path.GetFileName(str)
            Dim urls As New List(Of String)
            urls.Add("~/WatermarkedImages/" & Session("tempDir").ToString & "/" & filename)
            For Each imageURL As String In urls
                Dim img = New System.Web.UI.WebControls.Image()
                img.ImageUrl = imageURL
                img.Attributes.Add("href", "WatermarkedImages/" & Session("tempDir").ToString & "/" & filename)
                img.Attributes.Add("rel", "group1")
                img.Width = 75
                img.Height = 50
                img.CssClass = "clickImage"
                img.ImageAlign = HorizontalAlign.Left
                Me.FinalPreview.Controls.Add(img)
        Next
    Next
    For Each str As String In Directory.GetFiles(Server.MapPath("~/Uploads/") & Session("tempDir").ToString())
        Dim filename As String = Path.GetFileName(str)
        Dim urls As New List(Of String)
        urls.Add("~/Uploads/" & Session("tempDir").ToString & "/" & filename)
        For Each imageURL As String In urls
            Dim img = New System.Web.UI.WebControls.Image()
            img.ImageUrl = imageURL
            img.Attributes.Add("href", "Uploads/" & Session("tempDir").ToString & "/" & filename)
            img.Attributes.Add("rel", "group1")
            img.Width = 75
            img.Height = 50
            img.CssClass = "clickImage"
            img.ImageAlign = HorizontalAlign.Left
            Me.thumbs.Controls.Add(img)
        Next
    Next

In the first for each loop it adds the images fine and for the next forloop for uploads ie..for the thumbs div I get this error.

Upvotes: 1

Views: 7999

Answers (1)

Aristos
Aristos

Reputation: 66649

I see that you use in too many points the <% … %> but you also use it inside the UpdatePanel.

When you include the <% … %> then this processing are made during the page render and not on code behind, on the events of the page. Now if the updatepanel for example try to update from code behind and send data, this part of the page is fails because is never renders again. Or if for any reason this part of the page done before the code behind then we also have some issue. This can be done if you call the <% … %> and inside him you make a call to a code behind functions that try to change some other control on page before this call.

All this sound complicate* ? no its not, you just need to have in your mine how the processing on the web page done and follow it with your mine, and see if you make calls that can not be affect the output because what they affect they all ready have been render.

To solve this issues you need to remove the on page render <% … %> inside the update panels Instidead of <% … %> use a Literal control, and render inside the literal control your output on code behind, so there is no issues when the updatepanel for example needs to render his part.

So change this

<%=cMyInput.CliendID%>

to

 <asp:literal run="server" id="txtRenderOnMe" EnableViewState="false" />

and on code behind

protected void Page_Load(object sender, EventArgs e)
{
   txtRenderOnMe.Text = cMyInput.CliendID;
}

From your code that you use a lot the <%= ...%> do not go to change all points, only the points that have this issue, probably the one on the UpdatePanel.

*(or I do not describe them good)

Upvotes: 4

Related Questions