我需要在 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;
}
当我运行页面时,当我在浏览器中检查时,我会在隐藏字段中获取值。
但无法访问代码隐藏中的隐藏字段值。 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/