Ajax receive String list from a WebMethod

2

I need to pass a string list from a server method to ajax, but it does not work. If you pass only one string works fine.

Follow the code:

    [System.Web.Services.WebMethod]
    public List<string> MontarGrafico()
    {
          var l = new List<string>();
          l.Add("teste1");
          l.Add("teste2");
          return l;
    }

And in ajax:

    $.ajax({
        type: "POST",
        url: "Grafico.aspx/MontarGrafico",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (produtos) {
            var prods = produtos.d;
            $.each(prods, function (index, prod) {
                alert(prod);
            });                
        }
    });

But it does not display anything.

    
asked by anonymous 04.06.2014 / 16:43

1 answer

2

You should be giving this error:

Thatis,failuretoauthenticate,toworkaroundthisproblem,itwillgointotheApp_Startfolder,openthefileRouteConfig.csandleftitthus,public static class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { var settings = new FriendlyUrlSettings(); settings.AutoRedirectMode = RedirectMode.Off; routes.EnableFriendlyUrls(settings); } }

Ready will work right away.

Atip:MakeaRedirectMode.Off:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebApplication2 { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class WebServiceDados : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod()] public List<string> MontarGrafico() { var l = new List<string>(); l.Add("teste1"); l.Add("teste2"); return l; } } }

Ajax Javascript:

$.ajax({
        type: "POST",
        url: "WebServiceDados.asmx/MontarGrafico",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (produtos) {
            var prods = produtos.d;
            $.each(prods, function (index, prod) {
                alert(prod);
            });                
        }
});

In this mode you do not have to tinker with that setting WebService.asmx

Another point to note is that of sending and receiving, set your RouteConfig.cs in your WebConfig, to receive / send data with large sizes

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 

Note: To check for errors, I install Firebug Lite , a much-used plugin that gets jsonSerialization errors from the browser.

    
04.06.2014 / 17:51