I often come across the need to share data between javascript client-side code and my asp.net server controls. Many functions just perform better on the client-side and the need to pass data from my server controls to javascript comes up often. One of the easier ways of doing this is to create a asp:hiddenfield. Doing this gives your javascript code access to the data it contains. In this example, we programatically create a asp:Hiddenfield with a ID="sharedData" and assign a value of "New client initial value." When we click the server-side button, btnGetData which calls the javascript function getSharedData(), it passes the hiddenfield value from sharedData to getSharedData().
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Default" %>
<!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 runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function getSharedData()
{
alert("Shared data is " + document.getElementById("sharedData").value + ".");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />
</form>
</body>
</html>Code behind - Default.aspx.vb:
Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
Dim hiddenField As System.Web.UI.WebControls.HiddenField = New System.Web.UI.WebControls.HiddenField
hiddenField.ID = "sharedData"
hiddenField.Value = "New client initial value"
Page.Form.Controls.Add(hiddenField)
End Sub
End Class