views:

98

answers:

2

OK, I know how to call a simple old fashion asmx webservice webthod that returns a single value as a function return result. But what if I want to return multiple output params? My current approach is to separate the params by a dividing character and parse them on teh client. Is there a better way.

Here's how I return a single function result. How do I return multiple output values?

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="WebService.asmx" />
    </Services>

    function CallHelloWebMethod() {
        WebService.Hello(txtMyName.value, OnComplete1, OnTimeOut, OnError);
    }

    function OnComplete1(arg) {

        alert(arg);

    }

    function OnTimeOut(arg) {
    }

    function OnError(arg) {
    }

<WebMethod()> Public Function Hello(ByVal MyName As String) As String
    Return "Hello " & MyName
End Function
+3  A: 

The normal way to return multiple values is for the AJAX call to return a serialized JSON object.

For example:

{"firstName":"Santa","lastName":"Claus"}

Using the return value is simple, as the client code just has to eval (or JSON.parse) the results to produce a JavaScript object.

jhurshman
Up to this point, I was returning multiple values by separating them with a "|" char and using the Java split function to parse them out. You seem to be suggesting a uppity parsing method that I am unfamiliar with. Can you point me to an example?
Velika
It's called JSON, and it is very widely used (and not considered "uppity" at all). I would guess it's more widely used than XML (which is the "X" in AJAX), because it's easier for humans to read and client code to parse.Basically, it's using JavaScript object literal notation as a serialization. For that reason, it fits beautifully into client-side JavaScript.High-level overview with examples: http://en.wikipedia.org/wiki/JSON
jhurshman
+3  A: 

Try this.

First establish a class you want to return...

Public Class Person
  Public Name As String
  Public Greeting As String
End Class

Then make the webmethod return the class...

<WebMethod()> _
Public Function Hello(ByVal MyName As String) As Person
    Dim myPerson As New Person
    myPerson.FirstName = MyName 
    myPerson.Greeting = "Hello " & MyName
    Return myPerson
End Function

And update the javascript...

function OnComplete1(arg) {
  alert(arg.Greeting);
}

Note you could also return lists....

<WebMethod()> _
Public Function GetPeople() As Person()
    Dim myPersonList As New Generic.List(Of Person)
    Dim myPerson1 As New Person
    myPerson1.FirstName = "Fred"
    myPerson1.Greeting = "Hello " & MyName
    Dim myPerson2 As New Person
    myPerson2.FirstName = "Bill"
    myPerson2.Greeting = "Hi " & MyName
    myPersonList.Add(myPerson1)
    myPersonList.Add(myPerson2)
    Return myPersonList.ToArray()
End Function
digiguru