我需要从单击事件在数据库中插入纬度和经度,但是当我单击时,我在数据库中得到了零值,而不是实际值

i need to insert latitude and longitude in database from click event but when i click i got zero values in database not an actual values

本文关键字:数据库 单击 插入 事件 纬度 经度      更新时间:2023-09-26

使用 ASP.net 和WebForms,我试图将用户的位置(纬度,经度)存储到数据库中。这带来了问题:

我想通过单击B按钮来获取谷歌地图的Laqngitude和latude的值,我在数据库中得到了0个值。我的数据库哈两个文件的朗格和纬度,具有双重数据类型。

这是我第一次尝试的示例代码:

<html xmlns="http://www.w3.org/1999/xhtml"> 
   <head id="Head1" runat="server">
   <title></title>
</head>
<body>
   <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
   <script type="text/javascript">
       var long = 0;
       var lat = 0;
       window.onload = function () {
           var mapOptions = {
               center: new google.maps.LatLng(18.9300, 72.8200),
               zoom: 14,
               mapTypeId: google.maps.MapTypeId.ROADMAP
           };
           var infoWindow = new google.maps.InfoWindow();
           var latlngbounds = new google.maps.LatLngBounds();
           var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
           google.maps.event.addListener(map, 'click', function (e) {
               long = e.latLng.lng();
               lat = e.latLng.lat();
               document.getElementById("lat").value = lat;
               document.getElementById("lng").value = long;
               alert("Latitude: " + lat + "'r'nLongitude: " + long);
           });
       }
   </script>
<form id="myForm" runat="server">
   <div id="dvMap" style="width: 300px; height: 300px">
   </div>
   <asp:HiddenField ID="lat" runat="server" />
   <asp:HiddenField ID="lng" runat="server" />
   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>

下面是.aspx代码隐藏文件。我们在按钮的 Click 事件期间将经度和纬度保存到数据库中:

protected void Button1_Click(object sender, EventArgs e)
    {
        //TODO: Ask Stackoverflow how to get these values from browser-land javascript
        Double latitude = Convert.ToDouble(lat.Value);
        Double longitude = Convert.ToDouble(lng.Value);
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "@Data Source=(LocalDB)'v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
        string query1 = "insert into Courses(longi,lati) values (@lati, @longi)";
        SqlCommand cmd1 = new SqlCommand(query1, con);
        cmd1.Parameters.AddWithValue("@lati", latitude);
        cmd1.Parameters.AddWithValue("@longi", longitude);
        con.Open();
        cmd1.ExecuteNonQuery();
        con.Close();
    }

您需要访问服务器端代码中发布的表单。更准确地说,是 Request.Form 对象。

窗体上有一个 NameValueCollection 属性,您可以在其中使用字符串键查找来查找已发布的表单值

NameValueCollection nvc = Request.Form;
string lat,lng; 
if (!string.IsNullOrEmpty(nvc["lat"])) { 
    lat = nvc["lat"];
 } 
if (!string.IsNullOrEmpty(nvc["lng"])) { 
    lng = nvc["lng"]; 
}