Navigation

Search

Categories

On this page

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Friday, April 04, 2008
Friday, April 04, 2008 1:41:59 PM (Eastern Standard Time, UTC-05:00) (  |  )


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
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):