4

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

Benoit Blanchon
14.7k5 gold badges80 silver badges91 bronze badges
asked Sep 18, 2013 at 11:13

2 Answers 2

6

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?

answered Sep 18, 2013 at 11:19
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer should indeed work, the code in the question would write RegisterTheUser(contents of the variable); The single quotes around the text are missing.
@Peter Yeah I should have detailed that in my answer. I had automatically added the quotes in my code sample without noticing. :-)
2

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.

answered Sep 18, 2013 at 11:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.