2017-04-18 97 views
1

我需要将page_load上的地理位置(lat,long)存储到db表中。在asp.net代码隐藏中访问javascript变量

我使用这个脚本。

<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> 

这里是背后 公共部分类的getLocation我的代码:System.Web.UI.Page

{ 保护无效的Page_Load(对象发件人,EventArgs的){

lblloc.Visible = true; 

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

} 

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

enter image description here

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

可能是什么问题。

回答

0

您需要在代码后面使用此代码。

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


CODE BEHIND  
var value = this.hdnLocation.Value; 

例子是Here

+0

这并不工作 –

0

为了你当前的jQuery选择工作,你的HTML元素需要有ClientIDMode属性设置为“静态”。

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

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

这并没有帮助。我已经更新了这个问题。 –

0

这应该工作:

HTML

<script type="text/javascript"> 
function abc() 
{ 
    var str="value"; 
    document.getElementById("Hidden1").value=str; 
} 


</script> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <input id="Hidden1" type="hidden" runat="server" /> 
     <asp:Button ID="Button1" runat="server" OnClientClick="abc()" Text="Button" 
      onclick="Button1_Click" /> 
    </div> 
    </form> 
</body> 

代码背后

Response.Write(Hidden1.Value); 
+0

document.getElementById(“Hidden1”)。value = str; 。价值未被识别 即使它不显示在intellisense中。相反,.nodevalue和.valueof来了。 –

相关问题