Access JavaScript variables on PostBack using ASP.NET Code
In this article, we will see how to pass javascript values on postback and then access these values in your server side code. This article will primarily showcase two techniques of doing so. One using Hidden variables and the other using the __doPostBack() javascript method.
Using Hidden Variables – This method is pretty straightforward. All you have to do is declare a hidden field (inpHide) in your web page and then set the value of the hidden field in your JavaScript function as shown below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Pass Javascript Variables to Server</title>
<script type="text/javascript">
function SetHiddenVariable()
{
var jsVar = "dotnetcurry.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>
</head>
<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 retreive Javascript Variable" runat="server" onclick="btnJSValue_Click"/>
</div>
</form>
</body>
</html>
Then access the value of this field in the code behind on a Button click as shown below:
C#
protected void btnJSValue_Click(object sender, EventArgs e)
{
txtJSValue.Text = inpHide.Value;
}
VB.NET
Protected Sub btnJSValue_Click(ByVal sender As Object, ByVal e As EventArgs)
txtJSValue.Text = inpHide.Value
End Sub
Note: Observe that the <body> tag has an onload attribute using which the javascript function is being called.
<body onload="SetHiddenVariable()">
Using __doPostBack() – All but two ASP.NET web controls (Button & ImageButton) use the __doPostBack javascript function to cause a postback. Are you interested in knowing how the __doPostBack function looks like? Here’s a small test you can try. Just create a sample page and drop a textbox server control with AutoPostBack = true. Run the page and observe the source code.
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMjgzMDgzOTgzZGSkxIAX/
qPBYbY7JLBDh+UeGWrOCg==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
If you observe in the code above, ASP.NET automatically adds two hidden fields (“__EVENTTARGET” and “__EVENTARGUMENT”) and a client-side script method (“__doPostBack”) to the page. The EVENTTARGET is the ID of the control that caused the postback and the EVENTARGUMENT contains any arguments passed that can be accessed on the server. The __doPostBack method sets the values of the hidden fields and causes the form to be submitted to the server.
I hope this gives you a clear idea of how we can use the __doPostBack function to submit the value of a JavaScript variable to the server. All we have to do is call this JavaScript method explicitly and pass in the JavaScript variable value using the EVENTARGUMENT. Here’s an example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Pass Javascript Variables to Server</title>
<script type="text/javascript">
function SetHiddenVariable()
{
var jsVar = "dotnetcurry.com";
__doPostBack('callPostBack', jsVar);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
<asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable"
runat="server"/>
</div>
</form>
</body>
</html>
The code behind will look similar to the following:
C#
protected void Page_Load(object sender, EventArgs e)
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (IsPostBack)
{
string eventTarget = this.Request["__EVENTTARGET"];
string eventArgument = this.Request["__EVENTARGUMENT"];
if (eventTarget != String.Empty && eventTarget == "callPostBack")
{
if (eventArgument != String.Empty)
txtJSValue.Text = eventArgument;
}
}
else
{
btnJSValue.Attributes.Add("onClick", "SetHiddenVariable();");
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.ClientScript.GetPostBackEventReference(Me, "arg")
If IsPostBack Then
Dim eventTarget As String = Me.Request("__EVENTTARGET")
Dim eventArgument As String = Me.Request("__EVENTARGUMENT")
If eventTarget <> String.Empty AndAlso eventTarget = "callPostBack" Then
If eventArgument <> String.Empty Then
txtJSValue.Text = eventArgument
End If
End If
Else
btnJSValue.Attributes.Add("onClick", "SetHiddenVariable();")
End If
End Sub
The GetPostBackEventReference() emits __doPostBack() and also provides a reference to the control that initiated the postback event. The first time the page is loaded, IsPostBack is false, so we enter the ‘Else’ loop where we register the JavaScript on the button click event, using the Attribute collection of the Button control. When the user clicks the button, the JavaScript method is now called which in turn explicitly calls the __doPostBack thereby passing the JavaScript variable (jsVar) as an EVENTARGUMENT. We then access this hidden variable EVENTARGUMENT using our server side code and set the value of the textbox.
Run the application and try it out!! There are a few more ways including AJAX calls using which you can pass JavaScript variables during postback and access them using server-side code. I will leave that technique to be explored in future articles. I hope this article was useful and I thank you for viewing it.
Known 是基于 Blazor 轻量级、跨平台、低代码、易扩展的插件开发框架。
源码:https://gitee.com/known/Known
源码:https://github.com/known/Known
如果对您有帮助,点击⭐Star⭐关注 ,感谢支持开源!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!