Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: .NET
Expertise: Beginner
Jul 27, 2009



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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:

<head runat="server">
    <title>Pass Javascript Variables to Server</title>
<script type="text/javascript">
         function SetHiddenVariable()
            var jsVar = "devx.com";
            // Set the value of the hidden variable to 
            // the value of the javascript variable
            var hiddenControl = '<%= inpHide.ClientID %>';
<body onload="SetHiddenVariable()">
    <form id="form1" runat="server">
        <input id="inpHide" type="hidden" runat="server" />   
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnJSValue" 
           Text="Click to retrieve Javascript Variable" 
           runat="server" onclick="btnJSValue_Click"/>

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 <body> tag has an onload attribute that calls the JavaScript function that sets the hidden variable (<body onload="SetHiddenVariable()">). 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.

Deepak Choudhari
Thanks for your registration, follow us on our social networks to keep up-to-date