How to get a List<string> C# and send to a JS variable?

Asked

Viewed 1,432 times

7

I am developing in an Asp.net C# project and I don’t know how to get on the page a list of strings of my class.

How do I get these values?

Code I’ve been using.

       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>
  • 1

    You’ve heard of Ajax?

  • as it would be in ajax?

  • This is possible with Ajax and Json.

1 answer

7


You can use the $.Ajax jquery.

Add the Jquery reference on your page, preferably at the end of the body as explained in this question.

Access script to the C method#

   $(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 must add:

  • namespace using System.Web.Services;
  • namespace using System.Web.Script.Serialization;
  • [Webmethod] above the method.

Browser other questions tagged

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