Knowledge Management Banner

Knowledge Management Banner

Jquery Datatable in mvc.net


Required Plugins

Jquery 2.1 or above > https://jquery.com/download/
jquery.dataTables.min.js   > https://datatables.net/
jquery.dataTables.min.css   > https://datatables.net/

Hierarchy of adding Reference

<link href="/Content/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-2.1.4.js" type="text/javascript"></script>
<script src="/Scripts/jquery.dataTables.min.js" type="text/javascript"></script>


Html Code

<style type="text/css">
    th
    {
        text-align: left;
        padding-left: 10px;
    }
</style>
<div style="width: 100%; height: auto; background-color: #efefef; margin-bottom: 20px;
    padding: 10px">
    <table>
        <tr>
            <td>
                <button id="idBtnSearch" style="width: 80px;">
                    Search</button>
            </td>
            <th>@Html.Label("Id")
            </th>
            <td>@Html.TextBoxFor(m => m.Id)
            </td>
            <th>@Html.Label("Name")
            </th>
            <td>@Html.TextBoxFor(m => m.Name)
            </td>
        </tr>
        <tr>
            <td>
                <button  id="idBtnClearAll" style="width: 80px;">
                    Clear All</button>
            </td>
            <th>@Html.Label("Surname")
            </th>
            <td>@Html.TextBoxFor(m => m.Surname)
            </td>
            <th>@Html.Label("Address")
            </th>
            <td>@Html.TextBoxFor(m => m.Address)
            </td>
        </tr>
    </table>
</div>
<table id="idTableStudent" style="width: 100%;">
    <thead>
        <tr>
            <th>
                @Html.Label("Id")
            </th>
            <th>
                @Html.Label("Name")
            </th>
            <th>
                @Html.Label("Surname")
            </th>
            <th>
                @Html.Label("Address")
            </th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
@section scripts {
    @Scripts.Render("~/Views/Home/Home.js") // Your path to js file
}


Jquery

var Home = new function () {
    var self = this;
    this.StudentTableLog = null;

    this.Ready = function () {
// Load datatable on page load
        self.InitStudentDataTable();

        //Search click event
        $("#idBtnSearch").on("click", function (e) {
            e.preventDefault();
            self.StudentTableLog.ajax.reload();
        });

        //Clear All click event
        $("#idBtnClearAll").on("click", function (e) {
            e.preventDefault();
            $("input").val("");
            self.StudentTableLog.ajax.reload();
        });

        //Trigger search event on pressing enter
        $(document).on('keydown', function (e) {
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == 13) {
                $("#idBtnSearch").trigger('click');
                return false;
            }
        });

    }

    this.InitStudentDataTable = function () {
        self.StudentTableLog = $('#idTableStudent').DataTable({
            "serverSide": true,
            "processing": false,
            "ordering": false,
            "paging": true,
            "searching": false,
            "pagingType": "full_numbers",
            "ajax": {
                "url": "Home/GetStudentList",
                "type": "POST",
                "dataSrc": 'data',
                "data": function (d) {
                    d.Id = $("#Id").val();
                    d.Name = $("#Name").val();
                    d.Surname = $("#Surname").val();
                    d.Address = $("#Address").val();
                }
            },
            "columns": [
                        { data: 0 },
                        { data: 1 },
                        { data: 2 },
                        { data: 3 }
                       ]
        });
    }

}
$(document).ready(Home.Ready);


Controller Call

public ActionResult GetStudentList(DataTableRequest dtParam,Student searchParam)
{
       var episodes = HomeBl.GetStudentTableList(dtParam, searchParam);
       var result = Json(episodes, JsonRequestBehavior.AllowGet);
       return result;
 }


Bussiness Logic
  • It also includes functionality of search parameters, along with datatable list creation.
  • Entity frame work  is used for data base operation.


  public static DataTableResponse GetStudentTableList(DataTableRequest dtParam, Student objStudent)
        {
            using (var dbCntx = new SchoolDb())
            {
                IQueryable<Student> StudentTableQuery = dbCntx.Students.AsNoTracking();



                if (objStudent.Id != 0)
                {
                    StudentTableQuery = StudentTableQuery.Where(m => m.Id == objStudent.Id);
                }

                if (!String.IsNullOrEmpty(objStudent.Name))
                {
                    StudentTableQuery = StudentTableQuery.Where(m => m.Name.Contains(objStudent.Name));
                }

                if (!String.IsNullOrEmpty(objStudent.Surname))
                {
                    StudentTableQuery = StudentTableQuery.Where(m => m.Surname.Contains(objStudent.Surname));
                }

                if (!String.IsNullOrEmpty(objStudent.Address))
                {
                    StudentTableQuery = StudentTableQuery.Where(m => m.Address.Contains(objStudent.Address));
                }

                StudentTableQuery = StudentTableQuery.OrderByDescending(m => m.Id);

                var totalCount = StudentTableQuery.Count();

                var clientList = StudentTableQuery.Skip(dtParam.start)
                                                    .Take(dtParam.length).ToList();

                var List = clientList.Select(c => new[] {
                                                    c.Id.ToString(),
                                                    c.Name,
                                                    c.Surname,
                                                    c.Address});

                var dtResponse = new DataTableResponse()
                {
                    draw = dtParam.draw,
                    recordsTotal = totalCount,
                    recordsFiltered = totalCount,
                    data = List.ToList()
                };
                return dtResponse;
            }

        }


DataTable class

public class DataTableRequest
    {
        public int draw { get; set; }
        public int start { get; set; }
        public int length { get; set; }
    }

    public class DataTableResponse
    {
        public int draw { get; set; }
        public int recordsTotal { get; set; }
        public int recordsFiltered { get; set; }
        public List<string[]> data { get; set; }
    }

No comments

Powered by Blogger.