将 MSSQL 表值传递给 javascript

Pass MSSQL table values to javascript

本文关键字:javascript 值传 MSSQL      更新时间:2023-09-26

我正在尝试创建一个包含 asp.net mvc 4和EF6的网站,我想在其中将值从MSSQL表传递到javascript。到目前为止,一切正常,除非我为google-map-api函数传递LatitudeLongitude值,地图不会显示在我的视图中。我使用Html.HiddenFor助手从<span>传递值。这是我的代码,

控制器

public ActionResult BranchDetails(int BrId)
    {
        Branch branchDetails = abdb.Branches.Find(BrId);
        return View(branchDetails);
    }

视图

<script>
    function initialize() {
        var marker;
        var LatTag = document.getElementById("Lat");
        var Lat = LatTag.getElementsByTagName("span");
        var LngTag = document.getElementById("Lng");
        var Lng = LngTag.getElementsByTagName("span");
        var mapProp = {
            center: new google.maps.LatLng(LatTag, LngTag),
            zoom: 18,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(Lat, Lng),
            animation: google.maps.Animation.BOUNCE
        });
        marker.setMap(map);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
    <div class="container well" style="min-width: 100%; padding-right: 5px;">        
        <div id="googleMap"></div>
        <span id="Lat">@Html.HiddenFor(model => model.Latitude)</span>
        <span id="Lng">@Html.HiddenFor(model => model.Longitude)</span>
        <h4><b>@Html.DisplayFor(model => model.Title)</b></h4>
        <p><strong>Address:</strong> @Html.DisplayFor(model => model.Address)</p>
        <p><strong>Contact No. :</strong> @Html.DisplayFor(model => model.ContactNo)</p>
        <p><strong>Contact Person(s):</strong> @Html.DisplayFor(model => model.ContactPerson)</p>
    </div>
</body>

需要注意的是,我在MSSQL中的LongitudeLatitude字段是在varchar模式下设置的。我不确定它是否导致了问题,但只是觉得需要通知。如何解决这个问题?非常需要这种帮助。咔嚓。

关系,找到了我自己的解决方案。这对我有用,我没有给span id,而是给了Html.HiddenFor助手id。出于某种原因,javascript 没有选择我猜的跨度的 id。这是我的代码,

<script>
    function initialize() {
        var marker;
        var Lat = parseFloat(document.getElementById("Lat").value);
        var Lng = parseFloat(document.getElementById("Lng").value);
        var mapProp = {
            center: new google.maps.LatLng(Lat, Lng),
            zoom: 18,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(Lat, Lng),
            animation: google.maps.Animation.BOUNCE
        });
        marker.setMap(map);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
    <div id="googleMap"></div>
    @Html.HiddenFor(model => model.Latitude, new { id = "Lat" })
    @Html.HiddenFor(model => model.Longitude, new { id = "Lng" })
</body>