how to pass javascript variable to server side asp.net

↘锁芯ラ 提交于 2021-01-28 04:10:06

问题


I am trying to write javascript variable(hdnField) to server side. In javascript code I have assigned the value of "HiddenField" Control and then I want to write this value to server side. 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 :

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

回答1:


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: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. 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.



来源:https://stackoverflow.com/questions/31576047/how-to-pass-javascript-variable-to-server-side-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!