【发布时间】:2013-11-26 10:31:40
【问题描述】:
我在这里得到了在c#中获取输入字段值的过程:
Get value from input html in codebehind c#
我的 aspx 页面中有一个隐藏的输入字段,如下所示:
<input type="hidden" id="lblCountry_val" runat="server" />
隐藏字段的值通过jquery放哪里:
<script type="text/javascript">
$(function () {
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry_val').value = window.strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
但是当我试图在后面的代码中获取 Page_Load 事件中的值时:
Response.Write(lblCountry_val.Value);
没有打印任何内容。怎么会?
编辑 我通过将隐藏的输入字段更改为不可见的文本框,然后将“名称”属性放入标签中来做到这一点。
<input type="text" id="lblCountry_val" name="lblCountry_val" runat="server" style="display:none" />
在后面的代码中:
var txt=Request.Form["lblCountry_val"];
虽然我不清楚它是如何完成的。
【问题讨论】:
-
您确定在
BindUserInfo()函数中填充了隐藏字段吗?写入隐藏字段后尝试发出警报并检查值是否存储在其中。 -
我将 :
alert(window.strcountry);放在脚本标签内和document.getElementById...之前,它提供了价值。 -
window.strcountry不应该有这个问题。由于您的隐藏字段是服务器端控件,因此在客户端浏览器上呈现时会修改其 ID。所以在 ID 上执行document.getElementById...是行不通的。您需要按照下面第一个答案所示的相同方式获取客户端 ID,并将值设置为window.strcountry。之后,做alert(document.getElementById('<%=lblCountry_val.ClientID%>').value),看看这个值是否已经实际存储在隐藏字段中。