How to get a C # Liststring and send to a JS variable?

7

I'm developing in an Asp.net C # project and I'm not sure how to get a list of strings from my class on the page.

How do I get these values?

Code that I've used.

       var pontos= rota.ObterCordenadas(this._gvConsultaCheck, txtDtInicial, txtHoraInicial, txtDtFinal, txtHoraFinal, serial);
       List<string> latitudes = new List<string>();
       List<string> longitudes = new List<string>();
       foreach (var item in pontos)
       {
           char delimiterChars = ',';
           string[] coord = item.Split(delimiterChars);
           latitudes.Add(coord[0]);
           longitudes.Add(coord[1]);
       }

      this._HdLatitudes.Value = (new JavaScriptSerializer()).Serialize(latitudes);
      this._HdLongitudes.Value = (new JavaScriptSerializer()).Serialize(longitudes);

      <html>
      <input id="_HdLatitudes" type="hidden" value="" runat="server" />
     <input id="_HdLongitudes" type="hidden" value="" runat="server" />
      </html>

    <script>
        var latitudes = $("#_HdLatitudes").val();
        var longitudes = $("#_HdLongitudes").val();
    <script>
    
asked by anonymous 29.04.2015 / 15:38

1 answer

7

You can use $.Ajax of Jquery.

Add the Jquery reference on your page, preferably to the end of the body as explained in that #

C # method access script

   $(function () {
            $.ajax({
                url: '<%=ResolveUrl("Pagina.aspx/GetCoordenadas")%>',
                 dataType: "json",
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 success: function (data) {
                     var dados = JSON.parse(data.d);
                     var latitude = dados.latitude;
                     var longitude = dados.longitude;
                     console.log(dados);
                 },
                 error: function (response) {
                     alert(response.responseText);
                 },
                 failure: function (response) {
                     alert(response.responseText);
                 }
             });
         });

Code binding.

[WebMethod]
public static string GetCoordenadas()
{
     Dictionary<string, object> coordenadas = new Dictionary<string, object>();
     coordenadas .Add("latitude","2435435736");
     coordenadas .Add("longitude", "5674865");
     return new JavaScriptSerializer().Serialize(coordenadas);        
}

For Ajax to access the method and serialize you should add:

  • namespace using System.Web.Services;
  • namespace using System.Web.Script.Serialization;
  • [WebMethod] above method.
29.04.2015 / 16:06