简体   繁体   中英

Why I get error when I try to use variable of form class from designer?

In code behind I have property called ReportFeatures and Page_Load event:

    public partial class FeatureList : System.Web.UI.Page
    {
        protected string ReportFeatures;

        protected void Page_Load(object sender, EventArgs e)
        {
            IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();

            ReportFeatures = featureProps.ToJson();
        }
    }

In designer I tried to access ReportFeatures variable:

<head runat="server">
    <title></title>
    <script type="text/javascript">
        window.reportFeatures = <%= ReportFeatures%>;
    </script>
</head>

When page loaded I get this error:

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

Any idea why I get that error, and how to fix it?

Instead of using <%= ... %> block, try using data binding expression syntax ( <%# ... %> ), because <%= ... %> implicitly calls Response.Write() method in Page.Header which counts as code block while data binding expression doesn't count:

<head runat="server">
    <title></title>
    <script type="text/javascript">
        window.reportFeatures = <%# ReportFeatures %>;
    </script>
</head>

Then add Page.Header.DataBind() method in Page_Load event, because you want to bind ReportFeatures inside <head> tag which contains runat="server" attribute:

protected void Page_Load(object sender, EventArgs e)
{
    IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();

    ReportFeatures = featureProps.ToJson();

    // add this line
    Page.Header.DataBind();
}

More details about this issue can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM