如何将javascript变量传递到服务器端asp.net [英] how to pass javascript variable to server side asp.net

查看:74
本文介绍了如何将javascript变量传递到服务器端asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将javascript变量(hdnField)写入服务器端.在javascript代码中,我分配了"HiddenField"控件的值,然后我想将此值写入服务器端.这是我的客户端脚本:

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>

服务器端:

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

我查看了Page src并能够检索到"hdnField":

I viewed the Page src and was able to retrieve the "hdnField" which is :

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

推荐答案

我不知道在哪里

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

之所以起作用,是因为它看起来比ASP.NET Web表单看起来更多的ASP,但是如果有的话:

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;

只要hdnField不在模板或列表控件中,则可以直接在服务器上引用它,使用< asp:HiddenField>控件,您可以同时执行这两个操作.这样可以弥合差距,以便您可以更改客户端上的值,然后在回发时检索该值.仅当您需要在下一次回发发生之前或在ASP.NET回发生命周期的正常流程之外将值发送到服务器时,才需要AJAX.

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.

这篇关于如何将javascript变量传递到服务器端asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆