CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Pass Values from CodeBehind to JavaScript and From JavaScript to CodeBehind in ASP.Net

By Satheesh Babu
Posted On Jul 10,2009
Article Rating:
Be first to rate
this article.
No of Comments: 5
Category: ASP.Net/JavaScript
Print this article.

Pass Values from CodeBehind to JavaScript and From JavaScript to CodeBehind 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

 

Also, there are numerous article posted on codedigest on making Ajax calls using jquery. Refer here.

 

Conclusion

Passing values to server and back is one of the common and frequently done tasks in asp.net applications and this article addressed it with different techniques that can be used. Please post your comments or if you have an alternate way of doing this.

 

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
RE:Article Copied
Article is now deleted from codeproject.
Thanks to Sean(CodeProject).
RE:Article Copied
Hi Clark,
Actually part of this article is copied to codeproject! I have commented on that article.
Article Copied
It's not your article, somebody else on CodeProject already wrote this one.

Check this http://www.codeproject.com/KB/scripting/JqueryCode.aspx
KAPIL
<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" />


ddsfgvd
USE [TestLINQ]
GO
/****** Object: Table [dbo].[EmployeeDependant] Script Date: 08/06/2010 16:45:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[EmployeeDependant](
[DependentID] [int] IDENTITY(1,1) NOT NULL,
[EmpID] [int] NULL,
[DependentName] [varchar](100) COLLATE Latin1_General_CI_AS NULL,
[Sex] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
[Relation] [varchar](100) COLLATE Latin1_General_CI_AS NULL,
CONSTRAINT [PK_EmployeeDependant] PRIMARY KEY CLUSTERED
(
[DependentID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
USE [TestLINQ]
GO
ALTER TABLE [dbo].[EmployeeDependant] WITH CHECK ADD CONSTRAINT [FK_TB_Emp_TB_Dependent] FOREIGN KEY([EmpID])
REFERENCES [dbo].[Employee] ([EmpID])

USE [TestLINQ]
GO
/****** Object: Table [dbo].[Department] Script Date: 08/06/2010 16:44:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Department](
[DeptID] [int] NOT NULL,
[DepartmentName] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED
(
[DeptID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


USE [TestLINQ]
GO
/****** Object: Table [dbo].[Employee] Script Date: 08/06/2010 16:43:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[EmpID] [int] IDENTITY(1,1) NOT NULL,
[EmpName] [varchar](100) COLLATE Latin1_General_CI_AS NULL,
[DeptID] [int] NULL,
[Age] [int] NULL,
[Address] [varchar](100) COLLATE Latin1_General_CI_AS NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmpID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
USE [TestLINQ]
GO
GO
ALTER TABLE [dbo].[Employee] WITH CHECK ADD CONSTRAINT [FK_TB_Emp_TB_Dept] FOREIGN KEY([DeptID])
REFERENCES [dbo].[Department] ([DeptID])



Insert queries

INSERT Department(DeptID,DepartmentName) VALUES('1','IT')
INSERT Department(DeptID,DepartmentName) VALUES('2','CSE')
INSERT Department(DeptID,DepartmentName) VALUES('3','ECE')
INSERT Department(DeptID,DepartmentName) VALUES('4','MECH')
INSERT Department(DeptID,DepartmentName) VALUES('5','CIVIL')



INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('1','1','Raj','Male','Friend')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('2','2','Mano','Male','Mama')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('3','3','Kishore','Male','ChaCha')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('4','4','Vinoth','Male','Brother')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('5','5','Vijaya','Female','Brother')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('6','1','Revathi','Female','Sister')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('7','2','Vishal','Male','Brother')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('8','4','Ranjith','Male','Cousin')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('9','5','Deepak','Male','Friend')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('10','1','Priya','Female','Sister')
INSERT EmployeeDependant(DependentID,EmpID,DependentName,Sex,Relation) VALUES('11','2','Sneha','Female','Cousin')



INSERT Employee(EmpID,EmpName,DeptID,Age,Address) VALUES('1','Satheesh babu','1','25','Bangalore')
INSERT Employee(EmpID,EmpName,DeptID,Age,Address) VALUES('2','Ramesh','1','23','Chennai')
INSERT Employee(EmpID,EmpName,DeptID,Age,Address) VALUES('3','Arun','3','25','Coimbatore')
INSERT Employee(EmpID,EmpName,DeptID,Age,Address) VALUES('4','Kumar','4','26','Coimbatore')
INSERT Employee(EmpID,EmpName,DeptID,Age,Address) VALUES('5','Dinesh',NULL,'56','Coimbatore')