【问题标题】:Return an Arrray of Objects with key/value pairs using webmethod/pagemethod使用 Web 方法/页面方法返回具有键/值对的对象数组
【发布时间】:2012-08-06 07:36:37
【问题描述】:

我想获取一个对象数组并根据键获取一个值。

类似这样的javascript:

PageMethods.GetProducts(function(results) {
   var productName  = results[0].name;
});

我已经在后面的代码中尝试过这个,但我在结果中得到了一个数组数组:

VB

<WebMethod()>
    Public Shared Function GetProducts() As ArrayList

        Dim products As New ArrayList

        Dim prAdptr As New DataSet1TableAdapters.ProductsTableAdapter
        Dim prTbl As DataSet1.ProductsDataTable = prAdptr.GetData
        Dim prRow As DataSet1.ProductsRow

        For Each prRow In prTbl
            Dim product As New Collection
            product.Add(prRow.ProductID, "id")
            product.Add(prRow.ProductName, "name")

            products.Add(product)
        Next

        Return products
    End Function

c#

[WebMethod()]
public static ArrayList GetProducts()
{

    ArrayList products = new ArrayList();

    DataSet1TableAdapters.ProductsTableAdapter prAdptr = new DataSet1TableAdapters.ProductsTableAdapter();
    DataSet1.ProductsDataTable prTbl = prAdptr.GetData;
    DataSet1.ProductsRow prRow = default(DataSet1.ProductsRow);

    foreach ( prRow in prTbl) {
        Collection product = new Collection();
        product.Add(prRow.ProductID, "id");
        product.Add(prRow.ProductName, "name");

        products.Add(product);
    }

    return products;
}

因此,我无法根据键获得价值。 我知道我可以像这样引用值的位置:

results[0][0];

但这并不理想。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net .net vb.net asp.net-ajax


    【解决方案1】:

    你可以使用Anonymous Typeshttp://msdn.microsoft.com/en-us/library/bb397696.aspx

    foreach ( prRow in prTbl) {
        products.Add(new {
            id=prRow.ProductID,
            name=prRow.ProductName
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2012-02-26
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多