简体   繁体   中英

passing a variable to javascript function from code behind

I want to pass a string value to a javascript function from code behind. As it is a the moment I get an uncaught reference error explaining that the value is not defined.

var variable= txtVariable.Value;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Registering", "RegisterTheUser("+variable+");", true);

Advice perhaps on the correct syntax

This is the function

function RegisterTheUser(val) {
    alert(val);
}

regards

What you have posted looks fine. I've used the following without any issue:

ScriptManager.RegisterStartupScript(this, typeof(string), "Registering", String.Format("RegisterTheUser('{0}');", myVariable), true);

Can you try using the example I have posted?

The problem might be that your RegisterStartupScript is being executed before loading the function RegisterTheUser .

You need to sort out the order of the loading of the scripts or add some logic to call this function only after the document is ready.

In jQuery is done like this:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Registering", "$(document).ready(function(){ RegisterTheUser("+variable+"); });", true);

As sbhomra pointed in his answer, if the value is a string you might need to add single qoutes. Not needed if it's a number.

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