Access JavaScript variables on PostBack using ASP.NET Code

Posted by: Suprotim Agarwal , on 9/19/2008, in Category ASP.NET
Views: 288907
Abstract: In this article, we will see how to pass javascript values on postback and then access these values in your server side code. This article will primarily showcase two techniques of doing so. One using Hidden variables and the other using the __doPostBack() javascript method.
Access JavaScript variables on PostBack using ASP.NET Code
 
In this article, we will see how to pass javascript values on postback and then access these values in your server side code. This article will primarily showcase two techniques of doing so.  One using Hidden variables and the other using the __doPostBack() javascript method.
Using Hidden Variables – This method is pretty straightforward. All you have to do is declare a hidden field (inpHide) in your web page and then set the value of the hidden field in your JavaScript function as shown below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">
         function SetHiddenVariable()
         {
            var jsVar = "dotnetcurry.com";
            // Set the value of the hidden variable to
            // the value of the javascript variable
            var hiddenControl = '<%= inpHide.ClientID %>';
            document.getElementById(hiddenControl).value=jsVar;
         }
    </script>
</head>
 
<body onload="SetHiddenVariable()">
    <form id="form1" runat="server">
    <div>  
        <input id="inpHide" type="hidden" runat="server" />  
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable" runat="server" onclick="btnJSValue_Click"/>
    </div>
    </form>
</body>
</html>
Then access the value of this field in the code behind on a Button click as shown below:
C#
    protected void btnJSValue_Click(object sender, EventArgs e)
    {
        txtJSValue.Text = inpHide.Value;
    }
VB.NET
      Protected Sub btnJSValue_Click(ByVal sender As Object, ByVal e As EventArgs)
            txtJSValue.Text = inpHide.Value
      End Sub
Note: Observe that the <body> tag has an onload attribute using which the javascript function is being called.
<body onload="SetHiddenVariable()">
 
Using __doPostBack() – All but two ASP.NET web controls (Button & ImageButton) use the __doPostBack javascript function to cause a postback. Are you interested in knowing how the __doPostBack function looks like? Here’s a small test you can try. Just create a sample page and drop a textbox server control with AutoPostBack = true. Run the page and observe the source code.
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMjgzMDgzOTgzZGSkxIAX/
qPBYbY7JLBDh+UeGWrOCg==" />
</div>
 
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
If you observe in the code above, ASP.NET automatically adds two hidden fields (“__EVENTTARGET” and “__EVENTARGUMENT”) and a client-side script method (“__doPostBack”) to the page.  The EVENTTARGET is the ID of the control that caused the postback and the EVENTARGUMENT contains any arguments passed that can be accessed on the server. The __doPostBack method sets the values of the hidden fields and causes the form to be submitted to the server.
I hope this gives you a clear idea of how we can use the __doPostBack function to submit the value of a JavaScript variable to the server. All we have to do is call this JavaScript method explicitly and pass in the JavaScript variable value using the EVENTARGUMENT. Here’s an example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">
         function SetHiddenVariable()
         {
            var jsVar = "dotnetcurry.com";
            __doPostBack('callPostBack', jsVar);
         }
    </script>
</head>
 
<body>
    <form id="form1" runat="server">
    <div>   
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable"
            runat="server"/>
    </div>
    </form>
</body>
</html>
 
The code behind will look similar to the following:
C#
protected void Page_Load(object sender, EventArgs e)
{
    this.ClientScript.GetPostBackEventReference(this, "arg");
    if (IsPostBack)
    {
        string eventTarget = this.Request["__EVENTTARGET"];
        string eventArgument = this.Request["__EVENTARGUMENT"];
 
        if (eventTarget != String.Empty && eventTarget == "callPostBack")
        {
            if (eventArgument != String.Empty)
                txtJSValue.Text = eventArgument;
        }
    }
    else
    {
        btnJSValue.Attributes.Add("onClick", "SetHiddenVariable();");
    }
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Me.ClientScript.GetPostBackEventReference(Me, "arg")
      If IsPostBack Then
            Dim eventTarget As String = Me.Request("__EVENTTARGET")
            Dim eventArgument As String = Me.Request("__EVENTARGUMENT")
 
            If eventTarget <> String.Empty AndAlso eventTarget = "callPostBack" Then
                  If eventArgument <> String.Empty Then
                        txtJSValue.Text = eventArgument
                  End If
            End If
      Else
            btnJSValue.Attributes.Add("onClick", "SetHiddenVariable();")
      End If
End Sub
The GetPostBackEventReference() emits __doPostBack() and also provides a reference to the control that initiated the postback event. The first time the page is loaded, IsPostBack is false, so we enter the ‘Else’ loop where we register the JavaScript on the button click event, using the Attribute collection of the Button control. When the user clicks the button, the JavaScript method is now called which in turn explicitly calls the __doPostBack thereby passing the JavaScript variable (jsVar) as an EVENTARGUMENT. We then access this hidden variable EVENTARGUMENT using our server side code and set the value of the textbox.
Run the application and try it out!! There are a few more ways including AJAX calls using which you can pass JavaScript variables during postback and access them using server-side code. I will leave that technique to be explored in future articles. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Rick Strahl on Monday, September 29, 2008 1:25 AM
Suprotim, this is something I don't see discussed much, but that I do a lot of as well.

For what it's worth I posted a component some time ago that can manage accessing and passing back of variables between code behind and client side code call ScriptVariables. Similar concept but it goes two ways and is a bit more generic - you can just set the variable on the client and if the component is set to update any client side vars are automatically pushed back with their updated values when a postback occurs.

The original post and a follow-up (which includes the post back support) can be found here:
http://www.west-wind.com/WebLog/posts/252178.aspx
http://www.west-wind.com/WebLog/posts/259442.aspx
Comment posted by Suprotim Agarwal on Monday, September 29, 2008 3:03 AM
Rick: That's a lot more generic and a cleaner approach you have adopted. I also liked the way you have approached the ClientID generation. Lots to learn from your article!! I would strongly recommend my readers to take a look at those links.

Comment posted by Jayesh on Wednesday, November 5, 2008 7:25 PM
Good article.. Informative. Keep it up.
Comment posted by lidy on Wednesday, November 5, 2008 10:12 PM
It`s very goog.I mark it.develop .net about one and half year.I will more something to study!
Comment posted by HI on Wednesday, November 5, 2008 10:14 PM
中文可以显示吗!我试试下!
Comment posted by finix on Wednesday, November 5, 2008 11:24 PM
wonderful
rich me!!!
Comment posted by Ashraf on Thursday, November 6, 2008 3:31 AM
You catch a good thing.
very important for web developers.
Comment posted by Ashok on Thursday, November 6, 2008 4:34 AM
good one.... :)
Comment posted by Ratndeep on Thursday, November 6, 2008 4:43 AM
Its realyyy great explanation.
Comment posted by Thanigainathan.S on Thursday, November 6, 2008 12:58 PM
Hei,
This is really cool thing to know . will help in lot of practical situations. Thanks for Rick also for givin the links.

Thanks
Comment posted by test on Friday, November 7, 2008 2:56 AM
commmmmm
Comment posted by Matt on Friday, November 7, 2008 9:09 AM
Great Job!  I tried your example and using an Asp.net control it appears to postback twice to the server while using a standard HTML control I only get 1 postback.  Is it because the asp.net control is still posting back?  If so any way to stop the second postback?

Thanks
Comment posted by Thyagaraju Govardhan on Sunday, November 9, 2008 8:24 AM
Neat Article...Great Job
Comment posted by HY Lee on Wednesday, November 12, 2008 11:35 PM
In caes of your "Using Hidden Variables" in a DropdownList,
it does't work on at once, but two Click. Check out this source .  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="WebService_Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">
         function SetHiddenVariable()
         {
            var jsVar = document.getElementById('ddlclass');
            // Set the value of the hidden variable to
            // the value of the javascript variable
            var hiddenControl = '<%= inpHide.ClientID %>';
            document.getElementById(hiddenControl).value=jsVar.value;
         }
    </script>
</head>

<body onload="SetHiddenVariable()">
    <form id="form1" runat="server">
    <div>  
        <input id="inpHide" type="hidden" runat="server" />  
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable" runat="server" onclick="btnJSValue_Click"/>
         <asp:DropDownList ID="ddlclass" runat="server" Width ="100px">
                    <asp:ListItem>C#</asp:ListItem>
                    <asp:ListItem>AJAX</asp:ListItem>
                    <asp:ListItem>SQL</asp:ListItem>
                    <asp:ListItem>VB</asp:ListItem>
                                    </asp:DropDownList>
    </div>
    </form>
</body>
</html>


Comment posted by bill on Friday, November 14, 2008 8:50 AM
great article, i always use Request.Form("...") to get the valve which has been changed in javascript during the postback to keep sync the value between client and server side.

but ur solution is quite cool, i still look for a solution to directly update the viewstate, u know, asp.net page will recover the data from the viewstate, if we can update the viewstate when use js to change the value.
Comment posted by asdf on Monday, February 2, 2009 4:30 AM
asdf
Comment posted by monir on Tuesday, February 3, 2009 4:04 AM
I am pleased to all
Comment posted by naim on Thursday, April 9, 2009 2:00 AM
Excellent article
Comment posted by Patrick on Friday, July 24, 2009 10:48 AM
I hope you can help me too, since I've tried so many ways available on the net and I still can't get it right.

My problem is I can't pass the value of a Label control to the javascript variable.  The Label control dynamically gets value from DB, and i managed to display the value in this label called "lblmap".  

I would like to pass the value of "lblmap" to a javascript variable called "address".  I've tried the code in <script> as below:

1. var address = document.getElementById('<%=lblmap%>').value;
2. var address = document.getElementById('<%=lblmap%>').innerHTML;
3. var address = document.getElementById('lblmap').value;
4. var address = document.getElementById('lblmap').innerHTML;
5. var mapaddress = '<%=lblmap%>';
   var address = document.getElementById(mapaddress).value;

none of the above works, when i run the project, IE complaint the "object doesn't support this property or method".  I'll need to assign an address (e.g. 123 Main Street, Sydney NSW 2000, Australia) to the address variable, the google map i'm working on will automatically point and mark based on this address variable.

Currently if i assign a static (hard coded) value to this address variable, the map will display correctly (e.g. var address = "123 main street, sydney NSW 2000, Australia).  

I hope you can understand my question and wish you could help.
Comment posted by Suprotim Agarwal on Tuesday, July 28, 2009 2:06 AM
Patrick: Can you use the Contact page and mail me the code. I will look into it
Comment posted by mithun on Friday, July 31, 2009 10:21 AM
kuch nahi aata
Comment posted by Sasi on Thursday, November 19, 2009 2:52 PM
Great Idea. Excellent
Comment posted by Diego AC on Thursday, January 7, 2010 6:25 PM
Hey man, thanks! This saved my day! Seriously!!
Comment posted by rupesh on Wednesday, January 20, 2010 7:20 AM
without using hidden control i want access any one help me pls..
Comment posted by komal mhatre. on Saturday, March 27, 2010 3:16 AM
how to detect sereen resolution using ASp.net +C# within one page only
Comment posted by Abu on Tuesday, August 10, 2010 4:45 AM
Nice article.  How to pass multiple javascript values on postback?
When I tried to pass two multiple values, the first one disappeared.
Here is the javascript code.
function SetHiddenVariable()
         {
            var jsVar = "dotnetcurry.com";
            var tb = "www.noor-studio.com";
            __doPostBack('callPostBack', jsVar);
            __doPostBack('callPostBack2', tb);
         }
I also tried to pass multiple values like so: __doPostBack('callPostBack', jsVar, tb);

Thanks
Comment posted by ali sami on Sunday, June 26, 2011 2:33 PM
j'ai besoin de compend comment on peut changer le lieu d'une button
dans une page de asp.net(c#).
Comment posted by kanat on Wednesday, November 9, 2011 3:13 PM
Really quality post thanks much
Comment posted by tess on Tuesday, January 31, 2012 7:10 AM
1)I call this code from a button.

function ValidateRejMem() {
            __doPostBack('__Page', 'MyCustomArgument2');            
            if (document.getElementById("<%=HResult.ClientID %>").value == "1") {
                var result = confirm(document.getElementById("<%=HResult.ClientID %>").value + " - You are about to reject this request, Press OK to continue");
            }
            else {
                var result = confirm(document.getElementById("<%=HResult.ClientID %>").value + " - Work Orders has been generated for this request.  Rejecting this request will result in all associated Work Orders being cancelled, the NA will have to manually communicate the cancellation of the Work Orders with the System Administrators. Do you wish to continue?");
            }
            if (result == true) {
                document.getElementById('<%=HOnclickEvent.ClientID%>').value = "Ok";
                document.getElementById('<%=btnRejMem.ClientID%>').disabled = true;
                if (document.getElementById('<%=btnSave.ClientID%>') != null) {
                    document.getElementById('<%=btnSave.ClientID%>').disabled = true;
                    document.getElementById('<%=btnComplete.ClientID%>').disabled = true;
                }
                if (document.getElementById('<%=btnComplete.ClientID%>') != null) {
                    document.getElementById('<%=btnSave.ClientID%>').disabled = true;
                    document.getElementById('<%=btnComplete.ClientID%>').disabled = true;
                }
                document.getElementById('<%=btnRejMem.ClientID%>').value = 'Processing please wait...';
                document.body.style.cursor = "wait";
                __doPostBack('<%=btnRejMem.ClientID%>', 'OnClick');
                return true;
            }
            else {
                document.getElementById('<%=HOnclickEvent.ClientID%>').value = "Cancel";
                return false;
            }
        }
2) It then executes the Page_load code
if (eventTypeTarget == "MyCustomArgument2")
        {
            ValidateWO("R");
        }

3) Nr 2 executes the following that I can see returns a value of "1"
private void ValidateWO(string i_type)
    {
        int rst_code = 0;
        try
        {
            RequestObj.PK_REQUEST_NUMBER = txtRequestNo.Text;
            OrloDBObj.Check_WO_Exist(RequestObj, i_type, ref rst_code);

            if (rst_code == 1) // NO WO's RETURNED.
            {
                HResult.Value = "1";
            }
            else
            {
                HResult.Value = "0";
            }
        }
        catch (Exception err)
        {
            pMessage.Attributes.Add("class", "error");
            pMessage.InnerText = "System Error : " + err.Message;
        }
    }

4. When the message displays (on the first click of the button) then the hidden field is empty. When I click on the button again, then the value is populated.  Can someone please indicate what the problem is.
Comment posted by ravi sankar on Sunday, February 26, 2012 8:30 AM
Thanks for this idea
Comment posted by Piyu on Friday, March 23, 2012 7:25 AM
Thanks.After spending a whole day i get this code.i try and solve my problem.Thanks......
Comment posted by Hesha on Saturday, March 31, 2012 11:20 PM
@ tess  "When the message displays (on the first click of the button) then the hidden field is empty. When I click on the button again, then the value is populated.  Can someone please indicate what the problem is. "

to avoid this problem dnt use dopostback method in ur JavaScript.instead of that call the JS variable value from HiddenFeild value chnge event.This will solve the problem








E:g
In  Aspx use this codes :

<head>

function ServerReg()
    {
        var serverName = prompt("Enter Server Name?", 'Testserver');

        if (serverName) document.getElementById('<%= getServer.ClientID %>').value = serverName;

        else alert('You pressed Cancel or no value was entered!');
      
    }  
    </script>

<head>





in the body:

<form runat="server">

<div>
    <asp:HiddenField ID="hid1" runat="server"
     onvaluechanged="hid1_ValueChanged" />
    
    </div>

</form>

In .Cs page add following codes:


protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack )
            {
                
                        ClientScript.RegisterStartupScript(GetType(), "load", "ServerReg();", true);

                    
                      

                    }

                     //in hiddenfeild control.cs ..call the JS Sript value(hiddenfeildvalue)


protected void hid1_ValueChanged(object sender, EventArgs e)
        {
            if (hid1.Value != "")
            {
                Server_Config.getserver(hid1.Value);
            }
        }





            }


// Hope this will solve your matter

hppy coding
Hesha...

Comment posted by punyavathi on Monday, July 9, 2012 2:14 AM
if (mySplitResult[0] != 'Exit') {
                            window.document.getElementById("txtGeography").value = mySplitResult[0];
                            window.document.forms[0].elements['txtGeographyValue'].value = mySplitResult[1];
                            var i = 0;
                            var sGeoId = 'GetGeoBasedCustomer(' + mySplitResult[1].toString() + ')';
                            function CallServer()
                            {
                              __doPostBack("", sGeoId);
                              
                            }
i will try this code but it not working
Comment posted by bindu on Wednesday, August 22, 2012 5:38 AM
Hi,
Liked your article, its really cool, is there any way to get the value of the hidden control on page load instead of button click?
I am using vb.net as code-behind.
Someone please help
Thanks in advance
Comment posted by mohamed on Wednesday, March 20, 2013 3:23 PM
please,
i deal with google maps using java script
and i want to access the values of lat and lang in my page using asp.net server controls
any help ?
Comment posted by jhgj on Wednesday, April 16, 2014 2:40 AM
jhg
Comment posted by Mexican Codder on Thursday, June 19, 2014 12:08 PM
Thanks Mr. Agarwal.!
Very targeted info.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel