Javascript 使用 ASP.NET WebForms 的 jQuery DataTables 服务器端处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3531438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:02:58  来源:igfitidea点击:

jQuery DataTables server-side processing using ASP.NET WebForms

javascriptasp.netjqueryajaxdatatables

提问by rebelliard

Problem:

问题:

  • jQuery DataTables server-side processing using ASP.NET WebForms.
  • 使用 ASP.NET WebForms 的 jQuery DataTables 服务器端处理。

Solution:

解决方案:

  • Darin Dimitrov answered the question using an example which pages and sorts, but doesn't do any searching. Here's my **basic** modification of his work to make searching work on his example:
  • 达林·迪米特洛夫 (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 };
        }
    }
}

回答by Darin Dimitrov

I wrote a simple example that should illustrate the idea.

我写了一个简单的例子来说明这个想法。

Start by writing a generic handler for handling data on the server side (Data.ashxbut this could be a web page, web service, anything server side script capable of returning JSON formated data):

首先编写一个通用处理程序来处理服务器端的数据(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
            };
        }
    }
}

And then a WebForm:

然后是一个 WebForm:

<%@ 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>

The example is oversimplified but I hope it will illustrate the basics on how to get stared.

这个例子过于简单,但我希望它能说明如何开始的基础知识。

回答by Holystream

The example pages you listed actually sort, paginate, filter on initialization. Basically, you pass those data via query string.

您列出的示例页面实际上对初始化进行了排序、分页和过滤。基本上,您通过查询字符串传递这些数据。

Something like:

就像是:

sAjaxSource": "../examples_support/server_processing.ashx?SortBy=FirstName&FilterBy=StackOverFlow"

Having said that, if you want to override some behavior or want to extend dataTable's functionaly, you have a few options: Extending dataTable functionalityCustomizing Scrolling

话虽如此,如果您想覆盖某些行为或想扩展 dataTable 的功能,您有几个选择:扩展 dataTable 功能自定义滚动

You can follow the above examples and customize them for Filtering, Sorting, and Pagination

您可以按照上面的示例进行自定义以进行过滤、排序和分页

回答by Incognito

http://naspinski.net/post/REAL-AJAX-with-AspNet-(not-AspNet-AJAX).aspx

http://naspinski.net/post/REAL-AJAX-with-AspNet-(not-AspNet-AJAX).aspx

This guy has made ajax work with asp.net and datatables.

这家伙使 ajax 与 asp.net 和数据表一起工作。

回答by Fabio

I'm asp.Net developer... Please take in mind that .net developers are used to build web pages using .net controls, not javascript controls.

我是 asp.Net 开发人员...请记住,.net 开发人员习惯于使用 .net 控件来构建网页,而不是 javascript 控件。

The difference is: an asp.net control is a server-side control, you manage it without writing javascript your self, but programming in C#/VB.net. The asp.net control automatically generates the client-side javascript control when the website runs.

区别在于:asp.net 控件是服务器端控件,您无需自己编写 javascript 即可对其进行管理,而是使用 C#/VB.net 进行编程。网站运行时,asp.net 控件会自动生成客户端javascript 控件。

It approach is more "modern" and really powerful.

它的方法更“现代”并且非常强大。

So if you are a .net developer I suggest you to use this approach. If you are a javascript developer and you are building only the client-side interface of your application, probably you need a webService that provides the server-side data in XML format that you can call and read over HTTP. But, to "search", provide "pagination" and "sorting" via AJAX you need to develop server-side...

因此,如果您是 .net 开发人员,我建议您使用这种方法。如果您是一名 javascript 开发人员并且您只构建应用程序的客户端接口,那么您可能需要一个 webService 来提供 XML 格式的服务器端数据,您可以通过 HTTP 调用和读取这些数据。但是,要“搜索”,通过 AJAX 提供“分页”和“排序”,您需要开发服务器端...