从asmx服务返回多行

时间:2010-12-05 16:52:42

标签: c# asp.net web-services datatable asmx

我有一个Web服务方法,我想从数据表中返回多行。

我熟悉从Web服务方法返回值,但不熟悉数据表中的多行。这样做的最佳方法是什么?我是否需要返回数组或list<>

我的代码方法是这样设置的。

[WebMethod]
public void UpdateBold(int count, float lat, float lng)
{
DataTable dt = new Gallery().DisplayNearestByLatLong(count, lat, lng);

// return code here
}

2 个答案:

答案 0 :(得分:8)

您可以为数据表项创建新类型并返回此数据的数组

    public class sample
    {
        public string val1;
        public string val2;

    }
[WebMethod]
public sample[] UpdateBold(int count, float lat, float lng)

{

            DataTable dt = new Gallery().DisplayNearestByLatLong(count, lat, lng);
            var samples = new List<sample>();

            foreach(DataRow item in dt.Rows)
            {
                var s = new sample();
                s.val1 = item[0].ToString();
                s.val2 = item[1].ToString();
                samples.Add(s);
            }
            return samples.ToArray();
}

用于Ajax:

用于消费,请参阅http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ 但是你应该让你的web服务序列化JSON,为此看看 http://msdn.microsoft.com/en-us/library/bb763183.aspx

答案 1 :(得分:6)

我会返回一组轻量级DTO。

Ex,DTO:

public class Example
{
    public string Name { get; set; }
    public int Value { get; set; }
}

在您的网络服务中:

[WebMethod]
public Example[] GetExamples()
{
      return new Example[]{
          new Example { Name = "Test", Value = 100 },
          new Example { Name = "Test 2", Value = 500 }
      };      
}
相关问题