passing a variable to javascript function from code behind

17,411

Solution 1

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?

Solution 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.

Share:
17,411

Related videos on Youtube

Arianule
Author by

Arianule

Updated on June 04, 2022

Comments

  • Arianule
    Arianule almost 2 years

    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