Problem:

  • jQuery数据表服务器端处理使用ASP.NET网络表单.

Solution:

  • Darin Dimitrov用一个例子回答了这个问题,这个例子可以分页和排序,但不进行任何搜索.以下是我对他的作品的**基本**修改,以使搜索在他的例子中发挥作用:
public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Paging parameters:
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);

        // Sorting parameters
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Search parameters
        var sSearch = context.Request["sSearch"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = person => iSortCol == 0 ? (object) person.Id : person.Name;

        // Define the order direction based on the iSortDir parameter
        persons = "desc" == iSortDir ? persons.OrderByDescending(order) : persons.OrderBy(order);

        // prepare an anonymous object for JSON serialization
        var result = new
                         {
                             iTotalRecords = persons.Count(),
                             iTotalDisplayRecords = persons.Count(),
                             aaData = persons
                                 .Where(p => p.Name.Contains(sSearch))  // Search: Avoid Contains() in production
                                 .Where(p => p.Id.ToString().Contains(sSearch))
                                 .Select(p => new[] {p.Id.ToString(), p.Name})
                                 .Skip(iDisplayStart)   // Paging
                                 .Take(iDisplayLength)
                         };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable { get { return false; } }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person { Id = i, Name = "name " + i };
        }
    }
}

推荐答案

我写了一个简单的例子来说明这个 idea .

首先编写一个用于在服务器端处理数据的通用处理程序(Data.ashx,但这可以是网页、Web服务或任何能够返回JSON格式数据的服务器端脚本):

public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Those parameters are sent by the plugin
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = p => 
        {
            if (iSortCol == 0) 
            { 
                return p.Id; 
            }
            return p.Name;
        };

        // Define the order direction based on the iSortDir parameter
        if ("desc" == iSortDir)
        {
            persons = persons.OrderByDescending(order);
        }
        else
        {
            persons = persons.OrderBy(order);
        }

        // prepare an anonymous object for JSON serialization
        var result = new
        {
            iTotalRecords = persons.Count(),
            iTotalDisplayRecords = persons.Count(),
            aaData = persons
                .Select(p => new[] { p.Id.ToString(), p.Name })
                .Skip(iDisplayStart)
                .Take(iDisplayLength)
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person
            {
                Id = i,
                Name = "name " + i
            };
        }
    }
}

然后是一个网络表单:

<%@ Page Title="Home Page" Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="/styles/demo_table.css" /> 
    <script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="/scripts/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#example').dataTable({
                'bProcessing': true,
                'bServerSide': true,
                'sAjaxSource': '/data.ashx'
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> 
            <thead> 
            <tr> 
                <th>ID</th> 
                <th>Name</th> 
            </tr> 
            </thead> 
            <tbody> 
            <tr> 
                <td colspan="5" class="dataTables_empty">Loading data from server</td> 
            </tr> 
            </tbody> 
        </table>
    </form>
</body>
</html>

这个例子过于简单化了,但我希望它能说明如何入门的基础知识.

Asp.net相关问答推荐

IIS 中的嵌套 ASP.NET应用程序继承父配置值?

asp.net、url 重写模块和 web.config

HttpResponse 的区别:SetCookie、AppendCookie、Cookies.Add

下载功能在 asp.net 的更新面板中不起作用

ASP.NET-MVC 中的表单发布上的 FormCollection 为空

无法让嵌套在 UpdatePanel 中的 WebControl 中的 ScriptManager.RegisterStartupScript 工作

.NET 核心 IdentityUser 模型中规范化邮箱和用户名的用途是什么?

如何从 JS 访问 ViewBag

如何从 Asp.net Mvc-3 发送邮箱?

如何从 SQL Server 2008 本身获取客户端 IP 地址?

为应用程序池Classic .NET AppPool提供服务的进程与 Windows 进程激活服务发生了致命的通信错误

如何使用 WebRequest 发布数据并从网页获取响应

在 ASP.NET 中使用 MasterPages 时使用 JQuery 的正确方法?

Azure 网站 301 重定向 - 我应该把它放在哪里?

在 Application_BeginRequest 中设置会话变量

人们使用 JScript.Net 的目的是什么?

如何使用 jquery 设置单选按钮 Select 的值

x-powered by是什么意思?

try 为 Medium Trust 开发是否会失败?

.Net 上是否有 URL 验证器?