Access JavaScript Variables in Code-Behind Class

After writing the article on how to “Access Code-Behind variables in ASPX and JavaScript”, my focus continued on this particular counteract concept. At times we got to transfer some data from client side JavaScript to code-behind on some particular requirements. For example when the screen resolution of the client’s web browser is needed to be known in code-behind, then the simple way to accomplish is to access JavaScript variable in Code-Behind.

Step By Step Procedure:

The basic requirement can be achieved using Hidden Field control in ASP.NET (can also use basic HTML input (hidden) also). The following code illustrates how to access JavaScript variables in code-behind.

ASPX code:

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

<!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 JavaScriptFunction()
         {
            var JavaScriptVar = "JavaScript Variable";
            document.getElementById('<%= Hidden1.ClientID %>').value = JavaScriptVar; 
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>  
        <asp:HiddenField ID="Hidden1" runat="server" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="JavaScriptFunction()" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Code-Behind code:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;                                 
using System.Xml.Linq;

public partial class Default1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Display JavaScript Variable in Textbox Control...
        TextBox1.Text = Hidden1.Value;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // Do something here....
        Response.Write("Hello!!");
    }
}

Place a hidden field control, a Textbox control and a Button control on the asp.net page and write the above shown JavaScript code in the head tag of the page. The concept of accessing JavaScript variables in code-behind is to access the hidden field control in the JavaScript function and then assign a particular value to the hidden field control, and then retrieve the value stored in hidden field in code-behind as shown in above code.

The above code also demonstrates the click events of the Button control. Normal server side logic can be implemented in the function assigned to onclick attribute of the Button control. The client side JavaScript function can be assigned to the Button control using OnClientClick attribute. In the above code the function JavaScriptFunction() is used to bind JavaScriptVar to the hidden field and the same is retrieved from the hidden field in the Page_Load event in the code-behind.

ALSO SEE “Access Code-Behind Variables in JavaScript”

Conclusion:

JavaScript variables are accessed in the code-behind class using hidden field controls of ASP.NET. Although there might be some performance issues with the increase of hidden fields in the page, this approach is considered as the simplest method to access JavaScript variables in the code-behind model.

You may also like...

  • Ali

    Nice Article

  • vishal

    very Nice Article

  • Santosh gupta

    Love it. its a nice good. god bless u. its hot.

  • keith

    This does not work. The value of the hidden field always comes back empty. I have the following client side code:

    function showkeyval()
    {
    flgKeyPress.value = “1”;
    alert(document.getElementById(“flgKeyPress”).value);
    return true;
    }

    and the following Server-Side Code which is executed on a button click event:

    string tstflg = flgKeyPress.Value;

    Even though the value is displayed when the alert code is executed it always comes back empty when accessed in the code behind. I haven’t found the fix yet but I see this everywhere through out the web saying that this is the easiest way to do it. It doesn’t work.

  • !@#!@#

    Testing With Mesting

    Select * from article;

  • sidheswar

    Untitled Page

    var Stamp = new Date();
    document.write(” + (Stamp.getMonth() + 1) +”/”+Stamp.getDate()+ “/”+Stamp.getYear() + ”);
    var Hours;
    var Mins;
    var Time;
    Hours = Stamp.getHours();
    if (Hours >= 12) {
    Time = ” P.M.”;
    }
    else {
    Time = ” A.M.”;
    }
    if (Hours > 12)
    {
    Hours -= 12;
    }
    if (Hours == 0) {
    Hours = 12;
    }
    Mins = Stamp.getMinutes();
    if (Mins < 10) {
    Mins = "0" + Mins;
    }
    //document.write('‘ + Hours + “:” + Mins + Time + ‘‘);

    //document.getElementById(”).value =” + Hours + “:” + Mins + Time + ”;

    ———————————-
    dear sir plz guide me..

    when ever i i debug this program it shows an error

    “Microsoft JScript runtime error: ‘document.getElementById(…)’ is null or not an object”

    what should i do to overcome this error..plz help me sir!!

  • Danny

    Regards your article, I need to access the variable from code without post back, this is to get the url of the page using js variable so that it can grab also the hash values e.g http://micro.com/ring.aspx#operations

  • nattelip

    as danny says when posted back the control to get the variables from doesnt exist at that stage of the lifeyle off the page and when it exists it is a new control.

  • RamiVemula

    @Danny – Please make a JQuery POST/GET to Server and post all your data to Server, in that way you can send all your javascript variables to WebMethod.

  • RamiVemula

    @nattelip – Please see my comments to Danny’s Question.

  • shashi

    Very helpfull content
    thanks.

  • ethm

    very very grrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeetttttttttt.