简体   繁体   中英

How do I get my hidden field values on Postback

Here is my java script

 $('#geoLocation').click(function () {
        alert("I am Here");
        if (navigator.geolocation) {
            // Get Latitude and Longitude
            navigator.geolocation.getCurrentPosition(showPosition);

        }
        else {
            // Hide Locator Panel, if Browser not supported
            document.getElementById('panel1').style.display = 'none';
        }
    });

    function showPosition(position) {
        //  x.innerHTML = "Latitude: " + position.coords.latitude +
        // "<br>Longitude: " + position.coords.longitude;
          document.getElementById('latitude').innerHTML = position.coords.latitude;
          document.getElementById('longitude').innerHTML = position.coords.longitude;


    }

I need to get at the latitude and longitude values (which are hidden on the screen), in Postback on the CodeBehind. How do I do this?

I assume 'latitude' and 'longitude' are HTML elements on the page ?

That being the case, you should be able to add a runat="server" attribute to them and then they will be available in server-side code. If you're site is ASP.NET 4/4.5 you can also add ClientIDMode="Static" and your showPosition function will work as it is; if not you could a class to them and use a jQuery class selector to get your two items.

You can use $('#HiddenFieldId').val() to assign data to HiddenField at client side.

<div id="geoLocation">Click me to retrieve Geo Location</div>
<asp:HiddenField runat="server" ID="LatitudeHiddenField" />
<asp:HiddenField runat="server" ID="LongitudeHiddenField" />

<script type="text/javascript" 
  src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $('#geoLocation').click(function () {
        if (navigator.geolocation) {
            // Get Latitude and Longitude
            navigator.geolocation.getCurrentPosition(showPosition, geoLocationErrors);
        } else {
            // Hide Locator Panel, if Browser not supported
            document.getElementById('panel1').style.display = 'none';
        }

        function showPosition(position) {
            $('#<%= LatitudeHiddenField.ClientID %>').val(position.coords.latitude);
            $('#<%= LongitudeHiddenField.ClientID %>').val(position.coords.longitude);    
        }    

        function geoLocationErrors() {
            alert("Your browser doesn't support Geo Location.");
        }
    });

</script>

Then you can retrieve those value from HiddenField at server side as -

var latitute = LatitudeHiddenField.Value;
var longitude = LongitudeHiddenField.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM