繁体   English   中英

在代码隐藏中获得控制的价值

[英]Get Value Of Control In Code-Behind

当我调用<%= this.HiddenField.Value %> ,HiddenField控件的值在这种情况下保持相同状态(5)? 但是当我用console.log(document.getElementById('<%= this.HiddenField.ClientID %>').value);调用时console.log(document.getElementById('<%= this.HiddenField.ClientID %>').value); 在这种情况下,此返回更改后的状态为“活动”,为什么? 我如何在后面的代码中获取更改的值(我希望<%= this.HiddenField.Value %>返回“活动”(更改后的值))?

码:

<script>
    $(function () {
        document.getElementById('<%= this.HiddenField.ClientID %>').value = "active";
        console.log(document.getElementById('<%= this.HiddenField.ClientID %>').value); // this return te changed value "active"
        console.log('<%= this.HiddenField.Value %>') //this again is 5 not "active"
    });
</script>
<asp:HiddenField ID="HiddenField" runat="server" Value="5" />

您会混淆服务器端和客户端代码以及它们何时运行。

服务器端代码首先运行。 这就是<%=%>块中的内容。 其中,使用this.HiddenField.Value ,它将在更改客户端之前输出控件的服务器端值。 this.HiddenField.ClientID将输出控件ID作为服务器的输出,因此您可以从客户端代码中获取它。

首次加载页面时, <%=%>部分将被服务器端值替换。

这看起来像(页面加载后在浏览器中执行-查看源代码以查看实际呈现给浏览器的内容):

<script>
    $(function () {
        document.getElementById('someId').value = "active";
        console.log(document.getElementById('someId').value); // this return te changed value "active"
        console.log('5') //this again is 5 not "active"
    });
</script>
<input type="HiddenField" ID="someId" Value="5" />

然后,直到那时,客户端代码才会运行,并显示结果。

在下一行

 console.log('<%= this.HiddenField.Value %>')

<%= this.HiddenField.Value %>是在服务器上评估的,因此在浏览器中

console.log('5')

因为那是表达的价值。

当在服务器上呈现页面时, <%= whatever %>评估whatever

如果您查看发送给客户端的HTML,就会发现类似

$(function () {
    document.getElementById('blahblah_HiddenField').value = "active";
    console.log(document.getElementById('blahblah_HiddenField').value);
    console.log('5')
});

5由服务器呈现-客户端端没有任何内容将5链接到隐藏字段中的值,因此当隐藏字段的值更改时,它不会更新。

发生这种情况是因为asp.net控件显示“服务器”值,即5。使用javascript在客户端修改dom时,直到您发布页面后,asp.net控件值才会更改。

或者您可以使用ClientIDMode

<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />

设置并获取;

在jQuery中

$('#HiddenField1').val('active');
console.log($('#HiddenField1').val());

在JavaScript中

document.getElementById('HiddenField1').value = 'active';
console.log(document.getElementById('HiddenField1').value);

暂无
暂无

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

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