简体   繁体   English

如何将javascript变量传递到服务器端asp.net

[英]how to pass javascript variable to server side asp.net

I am trying to write javascript variable(hdnField) to server side. 我正在尝试将javascript变量(hdnField)写入服务器端。 In javascript code I have assigned the value of "HiddenField" Control and then I want to write this value to server side. 在javascript代码中,我分配了“ HiddenField”控件的值,然后我想将此值写入服务器端。 Here's my Client side script: 这是我的客户端脚本:

<script type="text/javascript">
  var hdnField = document.getElementById('<%= hdnField.ClientID%>');                        
  hdnField.value = 100; 
</script>

Server side: 服务器端:

<form action="#" runat="server">
  <div class="left"><%Response.Write(hdnField.Value);%></div>
  <asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
</form>

I viewed the Page src and was able to retrieve the "hdnField" which is : 我查看了Page src,并能够检索到“ hdnField”:

<input id="hdnField" type="hidden" name="hdnField" value="100 ">

I don't know where 我不知道在哪

  <div class="left"><%Response.Write(hdnField.Value);%></div>

Comes into play because that looks more ASP than ASP.NET web forms, but if you have: 之所以起作用,是因为与ASP.NET Web表单相比,ASP看起来更多,但是如果您有:

<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>

You can read and write to this on the client via: 您可以通过以下方式在客户端上进行读写:

document.getElementById('<%= hdnField.ClientID %>').value = 'XYZ';

alert(document.getElementById('<%= hdnField.ClientID %>').value);

On the server, you can read and write to this via: 在服务器上,您可以通过以下方式对此进行读写:

hdnField.Text = "XYZ";

var text = hdnField.Text;

As long as hdnField is not in a template or list control, you can refer to it directly on the server, with the <asp:HiddenField> control you can do both. 只要hdnField不在模板或列表控件中,就可以直接在服务器上引用它,使用<asp:HiddenField>控件,您可以同时执行这两个操作。 This bridges the gap so that you can change the value on the client, then retrieve the value on postback. 这样可以弥合差距,以便您可以更改客户端上的值,然后在回发时检索该值。 AJAX is only necessary if you need to send the value to the server before the next postback occurs, or out of the normal flow of the ASP.NET postback lifecycle. 仅当您需要在下一次回发发生之前或在ASP.NET回发生命周期的正常流程之外将值发送到服务器时,才需要AJAX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM