0

我想在不使用 Linq 的情况下将 Telerik RadGrid 绑定到 Web 服务。在我能找到的所有示例中,Web 服务必须返回 List(Of MyObject); 我试过这个,效果很好。但是,我绑定到的表可能在运行时有额外的列,或者列可能有不同的数据类型,所以我不能在编译时使用静态 MyObject 类来表示表。我也不知道在编译时需要在网格中显示哪些列。出于性能原因,我想绑定到 Web 服务。

我试过让 Web 服务方法返回一个 DataView,并以很多不同的方式对其进行转换,但它不起作用。我将如何编写 Web 服务的 GetData / GetDataAndCount 方法以从 DataView 或其他非 linq 数据源返回数据?

谢谢。

4

1 回答 1

0

您可以序列化 DataTable 类似于我的博客文章。这是一个例子:

    <telerik:RadGrid ID="RadGrid1" AllowPaging="true" runat="server">
        <MasterTableView>
            <Columns>
                <telerik:GridBoundColumn DataField="CustomerID" HeaderText="ID" />
                <telerik:GridBoundColumn DataField="CompanyName" HeaderText="Name" />
                <telerik:GridBoundColumn DataField="ContactName" HeaderText="Contact" />
                <telerik:GridBoundColumn DataField="Country" HeaderText="Country" />
                <telerik:GridBoundColumn DataField="City" HeaderText="City" />
            </Columns>
        </MasterTableView>
        <PagerStyle AlwaysVisible="true" />
        <ClientSettings>
            <DataBinding Location="WebService.asmx" SelectMethod="GetDataAndCount" />
        </ClientSettings>
    </telerik:RadGrid>

    <%@ WebService Language="C#" Class="WebService" %>

using System.Data;
using System.Linq;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod(EnableSession = true)]
    public Telerik.Web.UI.GridBindingData GetDataAndCount(int startRowIndex, int maximumRows)
    {
        var table = GetDataTable("select * from customers");

        var columns = table.Columns.Cast<System.Data.DataColumn>();

        var data = table.AsEnumerable()
            .Select(r => columns.Select(c => new { Column = c.ColumnName, Value = r[c] })
            .ToDictionary(i => i.Column, i => i.Value != System.DBNull.Value ? i.Value : null))
            .Skip(startRowIndex).Take(maximumRows)
            .ToList<object>();

        return new Telerik.Web.UI.GridBindingData() { Data = data, Count = table.Rows.Count };
    }

    public System.Data.DataTable GetDataTable(string query)
    {
        var connString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        var conn = new System.Data.SqlClient.SqlConnection(connString);
        var adapter = new System.Data.SqlClient.SqlDataAdapter();
        adapter.SelectCommand = new System.Data.SqlClient.SqlCommand(query, conn);

        var table = new System.Data.DataTable();

        conn.Open();
        try
        {
            adapter.Fill(table);
        }
        finally
        {
            conn.Close();
        }

        return table;
    }
}
于 2010-09-27T08:40:05.793 回答