Skip to main content

Passing Values from CodeBehind to JavaScript in ASP.Net

Passing values from server to client side for some javascript manipulation and it’s vice versa is one of most recurring tasks we will come across when developing web applications. Well, this can be done through so many ways and this article will elaborate on some of the techniques which we can use to access the javascript variable or value in server and vice versa.

How to Pass Values from CodeBehind to JavaScript?

Using HiddenField
Using a HiddenField control is one of the very common options which we can use to send some values from server to clientside. You can do this, by declaring a HTML INPUT control with type as hidden and setting runat attribute to server. Another way is to drag and drop a HiddenField control from visual studio toolbox.
ASPX
  <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {
         alert($("#hfServerValue").val());
         });
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:HiddenField ID="hfServerValue" runat="server" />

Codebehind

  protected void Page_Load(object sender, EventArgs e)
    {
        hfServerValue.Value = "From Server";
    }

Setting a Javascript Variable using <% %> blocks
We can embed the C# code using the <% %> construct in ASPX page. To do this, declare a public variable and assign it to a javascript variable through <% %> construct. Refer below,

ASPX
 <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {           
             var servervalue = '<%=FromServer %>';
             alert(servervalue);
         });
     </script>
</head>
<body>
    <form id="form1" runat="server">

Codebehind

 public string FromServer;
    protected void Page_Load(object sender, EventArgs e)
    {      
        FromServer = "From Server";
    }

Declaring JavaScript Variable from CodeBehind
This is one another way where we can declare a javascript variable by constructing the javascript from codebehind and assign a value. Refer the below code,
ASPX
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {           
             alert(JSVar);
         });
</script>

CodeBehind
public string FromServer;
    protected void Page_Load(object sender, EventArgs e)
    {        
        FromServer = "From Server";

        StringBuilder strScript = new StringBuilder();
        strScript.Append("<script type=\"text/javascript\">");
        strScript.Append("var JSVar='");
        strScript.Append(FromServer);
        strScript.Append("';");       
        strScript.Append("</script>");

        ClientScriptManager script = Page.ClientScript;

        if (!script.IsClientScriptBlockRegistered(this.GetType(), "Var"))
        {
            script.RegisterClientScriptBlock(this.GetType(), "Var", strScript.ToString());
        }

    }

Once executed, the above code will emit the javascript variable with a value to the output HTML(similar to below).

<body>
    <form name="form1" method="post" action="CBTOJS.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNTM4NjU4ODE1ZGQElWxBiEc2w9QhtjJyaVl59BWiPw==" />
</div>
<script type="text/javascript">var JSVar='From Server';</script>

Using Expando Attribute
Another way of sending some information or data from server to client side is by adding a custom attribute to a control through AttributeCollection of that control. For example,

  btnSave.Attributes.Add("flag", "From ASP.Net!");
The above custom attribute can be accessed in javascript like below,

<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">      
$(document).ready(function() {
         alert($('#btnSave').attr("flag"));
});
     </script>

The main disadvantage of the above approach is, the HTML generated by the ASP.Net for the above code is not XHTML complaint since flag is not a valid attribute of INPUT control. Below is the HTML generated when we use AttributeCollection.

<input type="submit" name="btnSave" value="Save" id="btnSave" flag="From ASP.Net!" />

To prevent this, the ClientScriptManager class has a method called RegisterExpandoAttribute() which can be used. This method can be used add a custom attribute a control which can be accessed in clientside by making it XHTML complaint.

This method has 2 overloads.
1.      RegisterExpandoAttribute(String controlID, String attribute, String value)  
Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value).
2.      RegisterExpandoAttribute(String, String, String, Boolean)
Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value) and a Boolean value indicating whether to encode the attribute value.

  To attach custom property called “LastPostBackTime” to a button control we can use,

Page.ClientScript.RegisterExpandoAttribute(btnSave.ClientID, "LastPostbackTime", DateTime.Now.ToString());

To Access the attribute in JavaScript,
  alert(document.getElementById("btnSave").LastPostbackTime);

 Or you can use the above jquery script.

When we use RegisterExpandoAttribute method, the custom attribute will be segregated in a separate javascript making the control clean and XHTML complaint. Refer the below output,
<script type="text/javascript">
<!--
var btnSave = document.all ? document.all["btnSave"] : document.getElementById("btnSave");
btnSave.LastPostbackTime = "19/03/2009 8:47:24 PM";
// -->
</script>

How to Pass Values from JavaScript to CodeBehind?

Using HiddenField Control
Again using a HiddenField control is one of the most common ways of sending client data to ASP.Net. The below code does that,
ASPX
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {            
         $("hfServerValue").val("From ClientSide!");
         });
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:HiddenField ID="hfServerValue" runat="server" />

CodeBehind
protected void Page_Load(object sender, EventArgs e)
    {      
        Response.Write(hfServerValue.Value);
    }

You can also use a HTML INPUT control by setting runat="server".

Using __doPostBack() method
One another way to pass values from javascript to ASP.Net codebehind is to use the __EventArgument in __doPostBack() method. To know more about this method and to use it you can refer Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net

If you have a control that emits __doPostBack() method (or you will have to emit it through code, refer above article) you can use __EventArgument to pass values from a javascript to codebehind. Refer the below code,
ASPX
 <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {
             $("#btnSave").click(function() {
                 __doPostBack("lbSave","From Javascript!");

             });

         });
        
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input id="btnSave" type="button" value="Save" />
    <asp:LinkButton ID="lbSave" runat="server" onclick="Save_Click">lbSave</asp:LinkButton>

CodeBehind
protected void Save_Click(object sender, EventArgs e)
    {
        Response.Write(Request["__EVENTARGUMENT"]);
    }
   
Using Ajax Methods
This is another way where we can make an Ajax call to server whenever we need the server value in javascript/jquery. When you use ASP.Net AJAX then you can use PageMethods for this. Read the below code snippet which demonstrates it with an example.
Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods

Comments

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.