Search This Blog

2009-04-27

Accessing Server side values from client Side

There are several possible ways to access server side values from client side javascript or client side values from server side.I try to describe few of them.

Method 1:-Acessing Client side values by HiddenField

In the HTML page ,write the following javascrpit function in the head section

<script type="text/javascript">
function getSharedData()
{
//Display value of hidden field.
alert("Shared data is " + document.getElementById("sharedData").value + ".");
//Change value of hidden field.
document.getElementById("sharedData").value="A new value";
}
</script>

Take a HiddenField and a button in the Body ,call the function getSharedData() from the OnCLientClick Event of the button
<asp:HiddenField ID="sharedData" runat="server" Value="Shared Data" />
<div>
<asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />

From the server side code write the following code to get the values of hidden feild which are assigned from the javascript.

protected void Page_Load(object sender, EventArgs e)
{
//Access value of hidden field from client.
String test = sharedData.Value;
}

Method 2.Dynamically create a hidden field on the client

Keep the HTML code as it is in Method 1.

Modify the server side code as follows

protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript;

//Use ClientScriptManager to dynamically create a hidden field on the client.
String hiddenName = "sharedData";
String hiddenValue = "Client data value";

//This hidden field is not a server side control, just a hidden <input> element on the client.
csm.RegisterHiddenField(hiddenName, hiddenValue);

}

Method 3:Create a HiddenField server control programmatically

Keep the HTML code as it is in Method 1.

Modify the server side code as follows

protected void Page_Load(object sender, EventArgs e)
{

//Create a HiddenField server control programmatically.
System.Web.UI.WebControls.HiddenField hiddenField = new System.Web.UI.WebControls.HiddenField();
hiddenField.ID = "sharedData";
hiddenField.Value = "New client initial value on Page 3";

//Important to add the control to the Form not the Page.
Page.Form.Controls.Add(hiddenField);
}

Method 4:Create and dynamically register an array on the server
Keep the HTML code as it is in Method 1. and modify the getSharedData() function from in the Client Side javascrpit.

function getSharedData()
{
//Display the 5th element of the array, "5".
alert("Shared data is " + sharedData[4] + ".");
}

In the server side code make the following modifications.

protected void Page_Load(object sender, EventArgs e)
{

ClientScriptManager csm = Page.ClientScript;

//Create and dynamically register an array on the server that is rendered in the JavaScript on the client.
String arrayName = "sharedData";
String arrayValues = "1,2,3,4,5";

csm.RegisterArrayDeclaration(arrayName, arrayValues);

}

No comments: