معرفی
اجازه دهید نحوه پیادهسازی jQuery DataTables را با جستجوی فیلتر سفارشی سمت سرور و مرتبسازی و صفحهبندی IQueryable در برنامه ASP.NET MVC 5 ببینیم. همیشه بهتر است از یک شبکه با پردازش سمت سرور برای بارگذاری سریع لیست شبکه در برنامه حتی با میلیون ها داده در جدول پایگاه داده استفاده کنید.
زمینه
jQuery DataTables یک افزونه برای کتابخانه جاوا اسکریپت است که توسط Allan Jardine توسعه یافته است. این ابزار بسیار انعطافپذیر و آسان است که به شما کنترلهای تعاملی پیشرفته برای هر جدول HTML را میدهد.
jQuery dataTables را تنظیم کنید
jQuery.DataTables را از مدیریت بسته NuGet اضافه کنید و به query.dataTables.min.js، dataTables.bootstrap.js و dataTables.bootstrap.css به Layout خود مراجعه کنید.
ایجاد مدل
ابتدا، اجازه دهید مدلی را برای برگرداندن داده ها و نمایش مقادیر برای شبکه ایجاد کنیم.
- using System.ComponentModel.DataAnnotations;
- namespace MVCApplication.Models
- {
- public class EmployeeDetails
- {
- public long Id { get; set; }
- public string EmpCode { get; set; }
- public string EmpName { get; set; }
- public string Gender { get; set; }
- }
- }
ایجاد کنترلر و مشاهده
حال، اجازه دهید یک کنترلر و نمای cshtml برای رندر کردن دادههای جی کوئری ایجاد کنیم.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MVCApplication.Controllers
- {
- public class EmployeeDataController : Controller
- {
- [HttpGet]
- public ActionResult EmployeeDataList()
- {
- try
- {
- return View();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
من متد ActionResult EmployeeDataList را در داخل کنترلر با ویژگی get HTTP ایجاد کرده ام. حال اجازه دهید نمای EmployeeDataList.cstml را برای نتیجه عمل ایجاد کنیم.
- @{
- ViewBag.Title = "Employee data";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- @section Styles{
- <style type="text/css">
- div.dataTables_filter {
- display: none !important;
- }
- table.dataTable tbody td {
- vertical-align: middle !important;
- padding: 5px !important;
- }
- </style>
- }
- <div class="row">
- <div class="col-md-12 col-sm-12 col-xs-12">
- <div class="table-responsive" style="background-color:#fff;font-size:13px;padding-top:5px;">
- <table id="Employeegrid" class="display dataTable cell-border table-bordered" style="width: 100%;" cellspacing="0">
- <thead>
- <tr>
- <th data-sortable="false">Id</th>
- <th>Emp Code</th>
- <th>Emp Name</th>
- <th>Gender</th>
- </tr>
- </thead>
- <thead class="filters" style="text-transform:uppercase;">
- <tr>
- <td style="padding:5px;">Emp Code</td>
- <td style="padding:5px;">Emp Name</td>
- <td style="padding:5px;">Gender</td>
- </tr>
- </thead>
- <tbody style="text-transform:uppercase;"></tbody>
- </table>
- </div>
- </div>
- </div>
اولین <thead></thead> برای سر ستون و دومی برای فیلتر سفارشی در سطح ستون است. مرحله بعدی پر کردن داده ها در شبکه با استفاده از فراخوانی Ajax به سمت سرور است. قطعه کد زیر این کار را انجام می دهد.
- @section Scripts
- {
- <script type="text/javascript">
- $(document).ready(function () {
- $('#Employeegrid).dataTable({
- "paging": true,
- "ordering": true,
- "filter": true,
- "destroy": true,
- "orderMulti": false,
- "serverSide": true,
- "Processing": true,
- "columnDefs": [
- { "width": "5%", "targets": [0] }
- ],
- "ajax":
- {
- "url": "/EmployeeData/GetEmployeeDataList",
- "type": "POST",
- "dataType": "JSON"
- },
- "aoColumns": [
- {
- "mDataProp": "Id",
- "visible": false
- },
- {"mDataProp": "EmpCode"},
- {"mDataProp": "EmpName"},
- {"mDataProp": "Gender"}
- ]
- });
- // Setup - add a text input to each filter column
- $('#Employeegrid.filters td').each(function () {
- var title = $('# Employeegrid thead td').eq($(this).index()).text();
- if (title) {
- $(this).html('<input type="text" class="form-control" />');
- }
- });
- // DataTable
- var table = $('#Employeegrid').DataTable(
- {
- "bFilter": true,
- "order": []
- });
- // function to clear the previous timer and set new timer for filter column keyup event to execute.
- var delay = (function () {
- var timer = 0;
- return function (callback, ms) {
- clearTimeout(timer);
- timer = setTimeout(callback, ms);
- };
- })();
- // script for column filter Keyup event and here I have created half second(500) delay using the timer. You can increase depends on your requirement.
- table.columns().eq(0).each(function (colIdx) {
- $('input', $('.filters td')[colIdx]).bind('keyup', function () {
- var coltext = this.value; // typed value in the search column
- var colindex = colIdx; // column index
- delay(function () {
- table
- .column(colindex)
- .search(coltext)
- .draw();
- }, 500);
- });
- });
- });
- </script>
- }
بعد، اجازه دهید یک متد post ActionResult ایجاد کنید تا داده ها را از پایگاه داده دریافت کنید و در dataTable jQuery پر کنید.
- public ActionResult GetEmployeeDataList()
- {
- try
- {
- 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]);
- //Custom column search fields
- string EmpCode = Request.Form.GetValues("columns[0][search][value]").FirstOrDefault();
- string EmpName = Request.Form.GetValues("columns[1][search][value]").FirstOrDefault();
- string Gender = Request.Form.GetValues("columns[2][search][value]").FirstOrDefault();
- IQueryable<Employee> employee = DbContext.Employee;
- //Getting the total count of Employee to display on the grid pagination.
- long TotalRecordsCount = employee.count();
- /* Here I have done the filter on And condition (You can change to OR condition if required). Validating the search value is not null or empty and not containing only space. */
- #region filters
- if (!string.IsNullOrEmpty(EmpCode) && !string.IsNullOrWhiteSpace(EmpCode))
- {
- employee = employee.Where(x => x.Code != null && x. Code.ToLower().Contains(EmpCode.ToLower()));
- }
- if (!string.IsNullOrEmpty(EmpName) && !string.IsNullOrWhiteSpace(EmpName))
- {
- employee = employee.Where(x => x.Name != null && x.Name.ToLower().Contains(EmpName.ToLower()));
- }
- if (!string.IsNullOrEmpty(Gender) && !string.IsNullOrWhiteSpace(Gender))
- {
- employee = employee.Where(x => x.Gender != null && x.Gender.ToLower().Contains(Gender.ToLower()));
- }
- #endregion
- //count of record after filter
- long FilteredRecordCount = employee.Count();
- /*Here we are allowing only one sorting at time. orderDir will hold asc or desc for sorting the column. */
- #region Sorting
- // Sorting
- switch (order)
- {
- case "1":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Code) : employee.OrderBy(p => p.Code);
- break;
- case "2":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Name) : employee.OrderBy(p => p.Name);
- break;
- case "3":
- employee = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? employee.OrderByDescending(p => p.Gender) : employee.OrderBy(p => p.Gender);
- break;
- default:
- employee = employee.OrderByDescending(p => p.Id);
- break;
- #endregion
- /* Apply pagination to employee iqueryable, startRec will hold the record number from which we need to display and pageSize will hold the number of records to display. Then assign the values to EmployeeDetails model. */
- var listemployee = employee.Skip(startRec).Take(pageSize).ToList()
- .Select(d => new EmployeeDetails()
- {
- Id = d.Id,
- EmpCode = d.Code,
- EmpName = d.Name,
- Gender = d.Gender
- }).ToList();
- // To avoid object reference error incase of listemployee being null.
- if (listemployee == null)
- listemployee = new List<EmployeeDetails>();
- return this.Json(new
- {
- draw = Convert.ToInt32(draw),
- recordsTotal = TotalRecordsCount,
- recordsFiltered = FilteredRecordCount,
- data = listemployee
- }, JsonRequestBehavior.AllowGet);
- }
- catch (Exception ex)
- {
- throw;
- }
- }
بنابراین، ما باید تمام مراحل ساخت پردازش سمت سرور را با jquery DataTables در برنامه MVC به پایان برسانیم. امیدوارم این به شما کمک کند.