简体   繁体   中英

Pass value from code-behind to JavaScript

Trying to pass value (abc) from code-behind to JavaScript but the page fails and doesn't load. Is there something wrong with the syntax? I've noticed that normally the <%...%> is highlighted yellow but this is not the case in my code.

<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $().ready(function() {    });

    $("a").click(function() {
    if (this.id == "optionalFeatures_Online") {
        var abc = "<%=Variable_codebehind %>";
    }
        });
</script>

Code Behind On_Load event:

    protected override void OnLoad(EventArgs e)
    {
        Variable_codebehind = "hello world"; 
    }

Error from logfile:

Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (ie <% ... %>).

first bind the value to a hidden control

then get the value from the hidden control

<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {    
        $("a").click(function() {
            if (this.id == "optionalFeatures_Online") {
                var abc = <%=Variable_codebehind %>;
            }
        });
    });
</script>

Code Behind On_Load event:

    protected override void OnLoad(EventArgs e)
    {
        Variable_codebehind = HttpUtility.JavaScriptStringEncode("hello world", true); 
    }

You can use Page.RegisterStartupScript and pass some variables from Code-Behind. Place the script in a .js file and call it on OnLoad method from the code-behind:

OnLoad CodeBehind:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", String.Format("MyScript({0});", codeBehindVar));

MyScript.js

function MyScript(myVar)
{
   var self = this;
   $("a").click(function() {
   if (this.id == "optionalFeatures_Online") {
      var abc = self.myVar;
   }
}

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