shanish
shanish

Reputation: 1984

return two values from webservice

Is is possible to return two values from a WebService to jQuery.

I tried like

[WebMethod(EnableSession = true)]
public string testing(string testId)
{
    string data = string.Empty;
    string data1 = string.Empty;
    List<test1> datalist1 = new List<test1>();
    List<test> datalist = new List<test>();

    //coding
    data = jsonSerialize.Serialize(datalist1);
    data1 = jsonSerialize.Serialize(datalist);
    return [data,data1];
}

but its showing error....how can we return two values from webservice here.....

Upvotes: 5

Views: 11171

Answers (5)

shanish
shanish

Reputation: 1984

I tried like

 return jsonSerialize.Serialize(new { list1 = datalist1, list = datalist });

and I can receive these from my jQuery file easily. Thanks everyone for ur support

Upvotes: 0

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Another way is to create a custom data type that has the two return values you want:

[Serializable]
public sealed class MyData
{
    public string Data { get; set; }
    public string Data1 { get; set; }
}

...

[WebMethod(EnableSession = true)]
public MyData testing(string testId)
{
    string data = string.Empty;
    string data1 = string.Empty;
    List<test1> datalist1 = new List<test1>();
    List<test> datalist = new List<test>();

    //coding
    data = jsonSerialize.Serialize(datalist1);
    data1 = jsonSerialize.Serialize(datalist);
    return new MyData { Data = data, Data1 = data1 };
}

OR

[Serializable]
public sealed class MyData
{
    public List<test> Data { get; set; }
    public List<test1> Data1 { get; set; }
}

...

[WebMethod(EnableSession = true)]
public string testing(string testId)
{
    MyData data = new MyData();
    string alldata = string.Empty;
    List<test1> datalist1 = new List<test1>();
    List<test> datalist = new List<test>();

    //coding
    data.Data = datalist1;
    data.Data1 = datalist;
    alldata = jsonSerialize.Serialize(data);
    return alldata;
}

Upvotes: 9

Mithir
Mithir

Reputation: 2431

a webmethod is like a regular method, it can only return one value.

if its the same type you can use a list or array.

if its different types you can make a class holding the data

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

return [data, data1] is not valid C# syntax. If you want to return a JSON array to the caller, use the JsonSerializer to serialize the array and return the resulting string.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503260

Well you could return an array of strings:

public string[] Testing(...)
{
    return new string[] { data, data1 };
}

You'd then need to perform each bit of JSON deserialization separately on the client, which isn't likely to be terribly pleasant :(

Upvotes: 7

Related Questions