Learner
Learner

Reputation: 353

Pass a value to javascript from code behind

I need to pass a value to javascript from code behind.

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "<script type='text/javascript'>OpenPopUp();</script>", false);

JS:

function OpenPopUp(parameterValue) {           
        paramframe = parameterValue;            
        openmodal(paramframe);
    }

So parameterValue will have ID.Text value which is passed from code behind.

I need to pass a value from code behind in this function OpenPopUp to javascript.

I tried below code and the javascript doesn't fire. Am I passing the value correct to JS.

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "<script type='text/javascript'>OpenPopUp(" + ID.Text + ");</script>", false);

ID.Text is a ItemTemplate value of a LinkButton in a gridview.

Upvotes: 0

Views: 1416

Answers (2)

Hoshani
Hoshani

Reputation: 836

generally I would use a hidden parameter and access it from javascript and C# like this

ASP.NET

<asp:HiddenField runat="server" ID="HiddenFieldID" />

javascript

var FieldName= document.getElementById('<%=HiddenFieldID.ClientID%>').value;

and C#

var x = HiddenFieldID.Value

note that hidden fields have string as their value,. I prefer this way so that code is easier to maintain in the future.

Upvotes: 0

user6656728
user6656728

Reputation:

try this, this should work

ScriptManager.RegisterStartupScript(this, typeof(string), "script1", "SampleJSFunction('" + vls_variable.Text+ "');", true);

Upvotes: 2

Related Questions