• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Access JavaScript variables on PostBack using ASP.NET Code

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
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.

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Asp.net发送邮件的两种方法发布时间:2022-07-10
下一篇:
ASP.NETMVC3数据绑定到VIEW的方式发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap