Pass Javascript data to C#method

Asked

Viewed 2,181 times

3

I need to get a user’s location, go to C, get his 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 take 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 it is not passing the javascript data pro C# and I cannot see error in the code :/

Could you help me?

  • 1

    The server-side control ID is not necessarily the same on the client-side. See if you don’t need to manually set the property ClientID each to have the same value as the property ID.

  • remember that to use the same id set in your web page, just put the Property Clientidmode="true" in your control.

2 answers

7

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

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

var latitude = "<%= lblLatitude.ClientID %>";
document.getElementById(latitude)(...)
  • 2

    Exact. The ID is the result of concatenating the Namingcontainer Ids into which the controller is inserted.

  • 1

    Or change the ClientID to have the same value as ID if you want to make the code shorter ;) but this works, +1.

1


You can do this without calling any method in C#.

An example:

http://jsfiddle.net/moykn/N6x3q/

As stated earlier the element id on the side of usually is not the same on the client side, often being formed by concatenation of kin ids.

An option would be instead of using Document.getElementById to use jquery or querySelector

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

or with Jquery

$("[id$=lblLatitude]");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.