Passing Javascript data to C #

3

I need to get a user's location, pass it to C #, get their street data and show it on a label.

I have the following code:

Labels

<asp:Label ID="lblMsg" runat="server" Visible="true"></asp:Label>
<asp:Label ID="lblLatitude" runat="server" Visible="false"></asp:Label>
<asp:Label ID="lblLongitude" runat="server" Visible="false"></asp:Label>   

Javascript to get latitude and longitude

<script>
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
}
else { alert("O seu navegador não suporta Geolocalização."); }
function showPosition(position) {
    document.getElementById('lblLatitude').textContent = position.coords.latitude;
    document.getElementById('lblLongitude').textContent = position.coords.longitude;
}
</script>

Button Code

protected void btnLocalizei_Click(object sender, EventArgs e)
    {
        String latitude = lblLatitude.Text;
        String longitude = lblLongitude.Text;

        string url = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", latitude, longitude);

        XElement xml = XElement.Load(url);

        if (xml.Element("status").Value == "OK")
        {
            lblMsg.Text = string.Format("<strong>Origem</strong>: {0}",
                xml.Element("result").Element("formatted_address").Value);
        }
        else
        {
            lblMsg.Text = "Ocorreu um erro";
        }
    }

Unfortunately, I'm not passing the javascript data to C # and I can not see error in the code: /

Could you help me?

    
asked by anonymous 26.02.2014 / 21:09

2 answers

1

You can do this without having to call any method in C #.

An example:

link

As previously stated, the element id on the side of the client side is often not the same as the client side, often being concatenated by the ids of the relatives.

One option would be to use the document.getElementById to use jquery or the querySelector

document.querySelector("[id$=lblLatitude]");

or with Jquery

$("[id$=lblLatitude]");
    
26.02.2014 / 21:43
7

The ID for ASP.NET elements generated on the server ( runat=server ) is updated at run time.

Use <%= lblLatitude.ClientID %> to reference correct ID :

var latitude = "<%= lblLatitude.ClientID %>";
document.getElementById(latitude)(...)
    
26.02.2014 / 21:15