Reputation: 9043
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
Upvotes: 4
Views: 17901
Reputation: 2954
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.
Upvotes: 2
Reputation: 2199
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?
Upvotes: 6