Create new account I forgot my password    

Access JavaScript variables on PostBack using ASP.NET Code
Rating: 428 user(s) have rated this article Average rating: 4.9
Posted by: Suprotim Agarwal, on 9/19/2008, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 124946 times
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. 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

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 05, 2008 7:25 PM
Good article.. Informative. Keep it up.
Comment posted by lidy on Wednesday, November 05, 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 05, 2008 10:14 PM
中文可以显示吗!我试试下!
Comment posted by finix on Wednesday, November 05, 2008 11:24 PM
wonderful
rich me!!!
Comment posted by Ashraf on Thursday, November 06, 2008 3:31 AM
You catch a good thing.
very important for web developers.
Comment posted by Ashok on Thursday, November 06, 2008 4:34 AM
good one.... :)
Comment posted by Ratndeep on Thursday, November 06, 2008 4:43 AM
Its realyyy great explanation.
Comment posted by Thanigainathan.S on Thursday, November 06, 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 07, 2008 2:56 AM
commmmmm
Comment posted by Matt on Friday, November 07, 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 09, 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 02, 2009 4:30 AM
asdf
Comment posted by monir on Tuesday, February 03, 2009 4:04 AM
I am pleased to all
Comment posted by naim on Thursday, April 09, 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 07, 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

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

NEWSLETTER