1

I need to return an array of string from MyMethod at codebehind. But do I parse it on aspx page using javascript?

[WebMethod]
public static string[] MyMethod(){
   return new[] {"fdsf", "gfdgdfgf"};
}

..........
function myFunction() {
            $.ajax({ ......
                    success: function (msg) {
                                //how do I parse msg?
                                }
            });
        };

3 Answers3

3

First, make sure you've tagged your class with [ScriptService] to allow it to be called through AJAX. Something like:

[ScriptService] //<-- Important
public class WebService : System.Web.Services.WebService
{
   [ScriptMethod] //<-- WebMethod is fine here too
   public string[] MyMethod()
   {
      return new[] {"fdsf", "gfdgdfgf"};
   }
}

You can then read the result with jQuery directly, as there's no need to parse anything:

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "WebService.asmx/MyMethod",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      // msg.d will be your array with 2 strings
    }
  });
});

Another approach is to just include a reference to:

<script src="WebService.asmx/js" type="text/javascript"></script>

This will generate proxy classes to allow you to call web methods directly. For example:

WebService.MyMethod(onComplete, onError);

The onComplete function will receive a single parameter with the results of the web service call, in your case a Javascript array with 2 strings. In my opinion, this is an easier solution than using jQuery and worrying about the URL and HTTP payload.

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0

Use the jQuery iterator to iterate over the strings in the msg result like so.

function myFunction() {
    $.ajax({ ......
        success: function (msg) {
            $.each(msg, function(index, value) {
                alert(value);
            });
        }
    });
};
Wulfram
  • 3,292
  • 2
  • 15
  • 11
0

The response object will contain an object called d which wraps the values returned from your WebMethod. Just access it like so:

function myFunction() {
    $.ajax({ ......
        success: function (msg) {
            //how do I parse msg?
            alert(msg.d); //alerts "fdsf", "gfdgdfgf"
        }
    });
};

See this question for an explanation.

Community
  • 1
  • 1
gowansg
  • 795
  • 1
  • 8
  • 15