无法将javascript变量发送到服务器端代码后面

问题描述 投票:0回答:1

我想将值(在我的 javascript 中)发送到 asp 隐藏字段值,以便我可以访问后面代码中的变量(C#)。

所以我有一个隐藏字段:

<asp:HiddenField id="SendA" value="ee" runat="server" />

在我的javascript中:

function test2() {
    
    document.getElementById("<%=SendA.ClientID%>").value = "nice";
    alert(document.getElementById("<%=SendA.ClientID%>").value);
}

但控制台显示: JavaScript.js:76 Uncaught TypeError: Cannot set properties of null (setting 'value') 在测试2。

我有正确的语法,它应该很好地提醒,我的问题是什么?

javascript c# asp.net server client-server
1个回答
0
投票

确保您的 JavaScript 代码放置在渲染的 HTML 中的 HiddenField 之后,或者在 DOM 完全加载后执行。我是说;你可能需要这样的东西:

<script>
    // if you have jQuery
    $(document).ready(function() {
        test2();
    });

    // if not
    document.addEventListener("DOMContentLoaded", function() {
        test2();
    });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.