How to access JavaScript variables on postback in ASP.NET ?

Dec 12, 2009 Posted by Lara Kannan
When you want to access some value set in the browser in JavaScript code in your server-side code, you'll need to pass those values to the server during postback.

There's a simple and straightforward way to do that in ASP.NET. All you need to do is, place a Hidden field on your web page, and set the field's value in your JavaScript code.

See the sample code :
<html>
<head runat="server">
<title>Pass Javascript Variables to Server</title>
<script type="text/javascript">
function SetHiddenVariable()
{
var jsVar = "devx.com";
// Set the value of the hidden variable to
// the value of the javascript variable
var hiddenControl = '<%= inpHide.ClientID %>';
document.getElementById(hiddenControl).value=jsVar;
}
</script>
<body onload="SetHiddenVariable()">
<form id="form1" runat="server">
<div>
<input id="inpHide" type="hidden" runat="server" />
<asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
<asp:Button ID="btnJSValue"
Text="Click to retrieve Javascript Variable"
runat="server" onclick="btnJSValue_Click"/>
</div>
</form>
</body>
</html>


Now you can access the value of the hidden field (Ex: inpHide) in your code-behind when the user submits / postback the page—in this case, with a button click as shown below:


protected void btnJSValue_Click(object sender, EventArgs e)
{
txtJSValue.Text = inpHide.Value;
}

In this example, the &lr;body> tag has an onload attribute that calls the JavaScript function that sets the hidden variable (&lr;body onload="SetHiddenVariable()">). But you don't have to set the hidden field value in the onload function; you can set it however you like—as long as you set the hidden field's value before you postback the page, you'll be able to access the value from the server-side code after the postback occurs.

I hope this will help you. A 'Thank You' would be nice!

Share
Labels: , ,

Post a Comment