【问题标题】:Return associate array of DataSet in WebMethod?在 WebMethod 中返回 DataSet 的关联数组?
【发布时间】:2013-01-03 12:09:46
【问题描述】:

我使用<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> 自动将我的Return 格式化为json 格式输出。

但是,我认为我做的比必要的多,因为我首先将DataSet 的内容转储到Dictionary,然后我将Return Dictionary 转储。

如果我在列上使用别名并想输出所有列,有没有办法像 Dictionary 一样简单地使用 ReturnDataSet?如果没有,我怎样才能用尽可能少的行来做到这一点?

Dim conn As New SqlConnection
conn.ConnectionString = Module1.DBConn2
Dim sqlCommand = New SqlCommand("Select id, column1, column2... From table1", conn)
    conn.Open()
    Dim sqlDataset As DataSet = New DataSet()
    Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
    sqlDataAdapter.Fill(sqlDataset)
    conn.Close()

    Dim jsonDict(sqlDataset.Tables(0).Rows.Count - 1) As Dictionary(Of Object, Object)
    Dim i As Integer = 0
    For Each rs As DataRow In sqlDataset.Tables(0).Rows
        jsonDict(i) = New Dictionary(Of Object, Object)
        jsonDict(i).Add("id", rs.Field(Of Object)("id"))
        jsonDict(i).Add("column1", rs.Field(Of Object)("column1"))
        jsonDict(i).Add("column2", rs.Field(Of Object)("column2"))
        ...
    i = i + 1
Next
Return jsonDict

【问题讨论】:

  • 您可以返回数据行数组。 sqlDataset.Tables(0).Rows 或者只返回 sqlDataset.Tables(0);

标签: c# vb.net dataset associative-array webmethod


【解决方案1】:
1. pass the array of DataSets to a web service web method that
takes a DataSet as a parameter.

例如:

[webmethod]
public static void(Dataset[] a)
{
// do something
}

你也可以用xml来填充数据集:

2. Use the DataSet.GetXML method (which returns an XML string representing
the DataSet) and pass that string to a web service web method. Then that
web method would declare a new DataSet and using the ReadXML method, it
could read the XML string into itself. You will need to load the XML string
into an XMLDocument and then pass it to an XMLNodeReader so that it can be
read into the DataSet using ReadXML.

3. fill up each dataset from the array. and pick a dataset through loop operation and after picking the dataset get the table in that dataset. finally you can get the row using the process as below(if needed):

DataRow dr;
Dataset ds;
DataTable dt;

dt = ds.Tables(0);
foreach(dr in ds.tables(0).rows){
// dr("ColName") to get value;
}

【讨论】:

    【解决方案2】:

    您可以通过ID获取每行(主键): 将返回类型更改为DataTable

    return sqlDataset.Tables(0);
    

    此链接可以帮助您link

    或者这个link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多