javascript - 在 asp.net 代码隐藏中访问 javascript 变量

标签 javascript c# asp.net geolocation pageload

我需要在 page_load 时将地理位置(纬度,经度)存储到数据库表中。

为此我使用此脚本。

<body onload="getLocation()">

    <p>Click the button to get your coordinates.</p>

            <%--<button onclick="getLocation()">Try It</button>--%>

            <p id="demo"></p>


    <form id="form1" runat="server">
        <div>

            <p>
                <asp:HiddenField ID="hdnLocation" ClientIDMode="Static" runat="server" />
 <asp:Label ID="lblloc" runat="server"></asp:Label>
                <asp:TextBox ID="txtloc" runat="server"></asp:TextBox>
                <asp:Button ID="btnLoc" text="submit" runat="server" OnClick="btnLoc_Click" />

            </p>
        </div>
    </form>

        <script>
            var x = document.getElementById("demo");

            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                } else {
                    x.innerHTML = "Geolocation is not supported by this browser.";
                }
            }

            function showPosition(position) {
                x.innerHTML = "Latitude: " + position.coords.latitude +
                "<br>Longitude: " + position.coords.longitude;
                $("[id*=hdnLocation]").val(position.coords.latitude + ' ' + position.coords.longitude);
            //    $("[id*=btnLoc]").trigger("click");
            }
            </script>

</body>
</html>

这是我的代码 公共(public)分部类 getLocation :System.Web.UI.Page

{ protected void Page_Load(对象发送者,EventArgs e) {

    lblloc.Visible = true;

    lblloc.Text = hdnLocation.Value;
    txtloc.Text = hdnLocation.Value;

}

当我运行页面时,当我在浏览器中检查时,我会在隐藏字段中获取值。

enter image description here

但无法访问代码隐藏中的隐藏字段值。 Response.Write 为空,lblloc.text 为空。

可能是什么问题。

最佳答案

为了使当前的 jQuery 选择器正常工作,您的 HTML 元素需要将 ClientIDMode 属性设置为“静态”。

对于 .NET 中的服务器元素,服务器 ID 和客户端 ID 是两个截然不同的东西。这确保了该元素的它们是相同的。

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

关于javascript - 在 asp.net 代码隐藏中访问 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43480339/

相关文章:

javascript - React redux 组件之间共享对象

c# - Web Essentials 浏览器链接在 asp mvc 6 项目中不起作用

c# - 如何以编程方式设置附加属性,例如。 Viewport2DVisual3D.IsVisualHostMaterialProperty

c# - 从 GridView C# 中的 DataRow 获取原始对象

ASP.Net ListView 回发速度慢, ListView 中有大量数据

c# - .NET 模型绑定(bind)器

javascript - 典型的 HTTP session ,但采用 Ajax 风格

javascript - 如果值 >= 15 语句 TypeScript

javascript - Google Sheets API 在未登录的情况下将行追加到电子表格时抛出 401 错误

c# - 将零宽度空间插入数据库的 Unicode 问题