c# - passing a variable to javascript function from code behind - Stack Overflow

admin2025-04-04  0

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

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

Share Improve this question edited Sep 18, 2013 at 11:28 Benoit Blanchon 14.6k5 gold badges79 silver badges91 bronze badges asked Sep 18, 2013 at 11:13 ArianuleArianule 9,06345 gold badges122 silver badges179 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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?

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743709701a216069.html

最新回复(0)