How to Access JavaScript Variables on Postback in ASP.NET

When you want to access some value set in the browser in JavaScript code in your server-side code, you’ll need to pass those values to the server during postback. Fortunately, there’s a simple and straightforward way to do that in ASP.NET. All you need to do is place a hidden field on your web page, and set the field’s value in your JavaScript code, as shown below:

    Pass Javascript Variables to Server    

Now you can access the value of the hidden field (inpHide) in your code-behind when the user submits the page—in this case, with a button click as shown below:

protected void btnJSValue_Click(   object sender, EventArgs e){   txtJSValue.Text = inpHide.Value;}

In this example, the tag has an onload attribute that calls the JavaScript function that sets the hidden variable (). But you don’t have to set the hidden field value in the onload function; you can set it however you like—as long as you set the hidden field’s value before you postback the page, you’ll be able to access the value from the server-side code after the postback occurs.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: