“the j stands for Jaghir”
about me | blog | facebook profile | linkedin profile | twitter profile | stuff i've done | stuff i like | wordpress plugins

20 April, 2009

Returning Key/Value pairs from a .NET Web Service

Filed under: ASP.NET,Web Development — Tags: , , , , , , , , — John @ 6:51 pm

As soon as I started using Web Services I came against this problem, and loads of other people have asked it before but I didn’t really find a satisfactory answer. The easiest method is to create your own custom class (or a struct, as I did) and use that:

The struct

public struct KeyValueStruct
{
private int _key;
private string _val;

public int Key
{
get { return _key; }
set { _key = value; }
}
public string Value
{
get { return _val; }
set { _val = value; }
}

public KeyValueStruct(int key, string value)
{
_key = key;
_val = value;
}
}

The web method

[WebMethod]
[XmlInclude(typeof(KeyValueStruct))]
public List<KeyValueStruct>  GetEnergySources()
{
List<KeyValueStruct>  sources = new List<KeyValueStruct>();
sources.Add(new KeyValueStruct(1, "Solar"));
sources.Add(new KeyValueStruct(2, "Wind"));
return sources;
}

Simple!

No Comments »

:(

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress