使用 jquery 数据表进行服务器端处理,包括分页、过滤和搜索

发布于 2024-09-08 15:19:27 字数 1539 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

作妖 2024-09-15 15:19:27

您好,此链接可能对您有帮助...

http://www.dotnetawesome.com/2015/11/jquery-datatable-server-side-pagination-sorting.html

这里有关 ASP.NET MVC 中 jQuery Datatable 服务器端分页和排序的文章,解释了步骤逐步在 asp.net mvc (C#) 作为服务器端
我将参考这篇文章[jQuery Datatable 服务器端分页和排序在 ASP.NET MVC

jQuery 代码设置 jQuery Datables

<script>
    $(document).ready(function () {
        $("#myTable").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": false, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": "/home/LoadData",
                "type": "POST",
                "datatype": "json"
            },
            "columns": [
                    { "data": "ContactName", "name": "ContactName", "autoWidth": true },
                    { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },
                    { "data": "Phone", "name": "Phone", "autoWidth": true },
                    { "data": "Country", "name": "Country", "autoWidth": true },
                    { "data": "City", "name": "City", "autoWidth": true },
                    { "data": "PostalCode", "name": "PostalCode", "autoWidth": true }
            ]
        });
    });
</script>

ASP.NET C# 代码 (MVC)

[HttpPost]
    public ActionResult LoadData()
    {

        var draw = Request.Form.GetValues("draw").FirstOrDefault();
        var start = Request.Form.GetValues("start").FirstOrDefault();
        var length = Request.Form.GetValues("length").FirstOrDefault();
        //Find Order Column
        var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
        var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();


        int pageSize = length != null? Convert.ToInt32(length) : 0;
        int skip = start != null ? Convert.ToInt32(start) : 0;
        int recordsTotal = 0;
        using (MyDatatableEntities dc = new MyDatatableEntities())
        {

            var v = (from a in dc.Customers select a);

            //SORT
            if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
            {
                v = v.OrderBy(sortColumn + " " + sortColumnDir);
            }

            recordsTotal = v.Count();
            var data = v.Skip(skip).Take(pageSize).ToList();
            return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
        }
    }

Hi this link may be helpful to you...

http://www.dotnetawesome.com/2015/11/jquery-datatable-server-side-pagination-sorting.html

Here the article about jQuery Datatable server side pagination and sorting in ASP.NET MVC , explained step by step in asp.net mvc (C#) as server dside
I will refer this article [jQuery Datatable server side pagination and sorting in ASP.NET MVC

jQuery code for setup jQuery Datables

<script>
    $(document).ready(function () {
        $("#myTable").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": false, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": "/home/LoadData",
                "type": "POST",
                "datatype": "json"
            },
            "columns": [
                    { "data": "ContactName", "name": "ContactName", "autoWidth": true },
                    { "data": "CompanyName", "name": "CompanyName", "autoWidth": true },
                    { "data": "Phone", "name": "Phone", "autoWidth": true },
                    { "data": "Country", "name": "Country", "autoWidth": true },
                    { "data": "City", "name": "City", "autoWidth": true },
                    { "data": "PostalCode", "name": "PostalCode", "autoWidth": true }
            ]
        });
    });
</script>

ASP.NET C# Code (MVC)

[HttpPost]
    public ActionResult LoadData()
    {

        var draw = Request.Form.GetValues("draw").FirstOrDefault();
        var start = Request.Form.GetValues("start").FirstOrDefault();
        var length = Request.Form.GetValues("length").FirstOrDefault();
        //Find Order Column
        var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
        var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();


        int pageSize = length != null? Convert.ToInt32(length) : 0;
        int skip = start != null ? Convert.ToInt32(start) : 0;
        int recordsTotal = 0;
        using (MyDatatableEntities dc = new MyDatatableEntities())
        {

            var v = (from a in dc.Customers select a);

            //SORT
            if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
            {
                v = v.OrderBy(sortColumn + " " + sortColumnDir);
            }

            recordsTotal = v.Count();
            var data = v.Skip(skip).Take(pageSize).ToList();
            return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
        }
    }
呆萌少年 2024-09-15 15:19:27

https://github.com/johannes-brunner/DataTables-ASP.NET-MVC

这是一个示例项目,您可以下载它并通过调试来了解 DataTables 如何与 .NET MVC 配合使用。
它帮助我在这个主题中找到了立足点。

https://github.com/johannes-brunner/DataTables-ASP.NET-MVC

This is an example project, you can download it and by debugging get a feel for how DataTables works with .NET MVC.
It helped me get find footing in the topic.

别闹i 2024-09-15 15:19:27

请遵循此代码,它非常简单

<script type="text/javascript">
$(document).ready(function () {
    $("#AllUsers").DataTable({
        "processing": true, // for show progress bar
        "serverSide": true, // for process server side
        "filter": true, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        "ajax": {
            "url": "@Url.Content("~/Users/GetAllUsers")",
            "type": "POST",
            "datatype": "json"
        },
        "columns": [
            { data: 'UserID', name: 'UserID', "autoWidth": true },
            { data: 'Name', name: 'Name', "autoWidth": true },
            { data: 'Email', name: 'Email', "autoWidth": true },
            { data: 'UserRole', name: 'UserRole', "autoWidth": true },
            { data: 'Status', name: 'Status', "autoWidth": true },
{
    data: '', name: '', "autoWidth": true, "orderable": false, mRender: function (data, colo, row) {
        return "<i class='fa fa-trash' style='cursor:pointer'></i>";
    }
}
        ]
    });
});

这是控制器方法

public JsonResult GetAllUsers()
    {
        JsonResult result = new JsonResult();
        try
        {
            // Initialization.   
            string search = Request.Form.GetValues("search[value]")[0];
            string draw = Request.Form.GetValues("draw")[0];
            string order = Request.Form.GetValues("order[0][column]")[0];
            string orderDir = Request.Form.GetValues("order[0][dir]")[0];
            int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
            int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
            // Loading.   
            List<User> data = _userReps.AllUsers().ToList();
            // Total record count.   
            int totalRecords = data.Count;
            // Verification.   
            if (!string.IsNullOrEmpty(search) &&
                !string.IsNullOrWhiteSpace(search))
            {
                // Apply search   
                data = data.Where(p => p.FirstName.ToString().ToLower().Contains(search.ToLower()) ||
                    p.LastName.ToLower().Contains(search.ToLower()) ||
                    p.EmailID.ToString().ToLower().Contains(search.ToLower()) ||
                    p.UserRole.UserRoleName.ToLower().Contains(search.ToLower()) ||
                    p.UserStatus.Name.ToLower().Contains(search.ToLower())
                 ).ToList();
            }
            // Sorting.   
            if (!(string.IsNullOrEmpty(order) && string.IsNullOrEmpty(orderDir)))
            {
                data = data.OrderBy(order + " " + orderDir).ToList();
            }
            int recFilter = data.Count;
            data = data.Skip(startRec).Take(pageSize).ToList();
            var modifiedData = data.Select(d =>
                new {
                UserID= d.UserID,
                Name= d.FirstName + " "+ d.LastName,
                Email= d.EmailID, 
                Status= d.UserStatus.Name,
                UserRole= d.UserRole.UserRoleName
                }
                );
            // Loading drop down lists.   
            result = this.Json(new
            {
                draw = Convert.ToInt32(draw),
                recordsTotal = totalRecords,
                recordsFiltered = recFilter,
                data = modifiedData 
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            // Info   
            Console.Write(ex);
        }
        // Return info.   
        return result;  
    }

Please follow this Code Its very Simple

<script type="text/javascript">
$(document).ready(function () {
    $("#AllUsers").DataTable({
        "processing": true, // for show progress bar
        "serverSide": true, // for process server side
        "filter": true, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        "ajax": {
            "url": "@Url.Content("~/Users/GetAllUsers")",
            "type": "POST",
            "datatype": "json"
        },
        "columns": [
            { data: 'UserID', name: 'UserID', "autoWidth": true },
            { data: 'Name', name: 'Name', "autoWidth": true },
            { data: 'Email', name: 'Email', "autoWidth": true },
            { data: 'UserRole', name: 'UserRole', "autoWidth": true },
            { data: 'Status', name: 'Status', "autoWidth": true },
{
    data: '', name: '', "autoWidth": true, "orderable": false, mRender: function (data, colo, row) {
        return "<i class='fa fa-trash' style='cursor:pointer'></i>";
    }
}
        ]
    });
});

And This is Controller method

public JsonResult GetAllUsers()
    {
        JsonResult result = new JsonResult();
        try
        {
            // Initialization.   
            string search = Request.Form.GetValues("search[value]")[0];
            string draw = Request.Form.GetValues("draw")[0];
            string order = Request.Form.GetValues("order[0][column]")[0];
            string orderDir = Request.Form.GetValues("order[0][dir]")[0];
            int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
            int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
            // Loading.   
            List<User> data = _userReps.AllUsers().ToList();
            // Total record count.   
            int totalRecords = data.Count;
            // Verification.   
            if (!string.IsNullOrEmpty(search) &&
                !string.IsNullOrWhiteSpace(search))
            {
                // Apply search   
                data = data.Where(p => p.FirstName.ToString().ToLower().Contains(search.ToLower()) ||
                    p.LastName.ToLower().Contains(search.ToLower()) ||
                    p.EmailID.ToString().ToLower().Contains(search.ToLower()) ||
                    p.UserRole.UserRoleName.ToLower().Contains(search.ToLower()) ||
                    p.UserStatus.Name.ToLower().Contains(search.ToLower())
                 ).ToList();
            }
            // Sorting.   
            if (!(string.IsNullOrEmpty(order) && string.IsNullOrEmpty(orderDir)))
            {
                data = data.OrderBy(order + " " + orderDir).ToList();
            }
            int recFilter = data.Count;
            data = data.Skip(startRec).Take(pageSize).ToList();
            var modifiedData = data.Select(d =>
                new {
                UserID= d.UserID,
                Name= d.FirstName + " "+ d.LastName,
                Email= d.EmailID, 
                Status= d.UserStatus.Name,
                UserRole= d.UserRole.UserRoleName
                }
                );
            // Loading drop down lists.   
            result = this.Json(new
            {
                draw = Convert.ToInt32(draw),
                recordsTotal = totalRecords,
                recordsFiltered = recFilter,
                data = modifiedData 
            }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            // Info   
            Console.Write(ex);
        }
        // Return info.   
        return result;  
    }
场罚期间 2024-09-15 15:19:27

在您提到的官方网站中,有完整的参考此处

我希望它能有所帮助。

In the official website that you referred, there is a complete reference Here.

I hope that it can help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文