Saturday, May 20, 2017

Starting with Asp.Net Core using Visual Studio Jquery DataTables

In this post I will show you how to use Jquery DatTables in Asp.Net MVC Core 1.1, EntityFrameworkCore, LINQ Dynamic Core. Previously I had shown how to...
OutPut:















Open Index.cshtml and comment below div tag.
  

<div style="max-height:350px; overflow-y:auto">

Now comment body tag from the below table and add id as tblemp for the below tag.
  

<table class="table table-hover table-bordered">

Add datatable css and js files. The Entire Index.cshtml file looks as shown below
  

@model IEnumerable<AspDotNetCore.Models.Employees>
@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <br />
    @Html.ActionLink("ADD Employee", "ADD", null, null, new { id = "btnADD", @class = "btn btn-primary" })    
    <table id="tblemp" class="table table-bordered table-striped table-hover" width="100%">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th>Action</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>DOJ</th>
                <th></th>
            </tr>
        </tfoot>        
    </table>    
</div>
<div class="modal fade" id="MyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Employee Details</h4>
            </div>

            <div class="modal-body">
                <input type="hidden" id="hfEmpID" value="" />
                <div id="DivBody"></div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger" id="btnDelete">Delete</button>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <link href="~/datatables/css/jquery.dataTables_themeroller.css" rel="stylesheet" />
    <link href="~/datatables/css/dataTables.bootstrap.css" rel="stylesheet" />
    <script src="~/datatables/js/jquery.dataTables.js"></script>
    <script src="~/datatables/js/dataTables.bootstrap.js"></script>
    <script>
        var table;
        $('#tblemp tfoot th').each(function () {
            var title = $(this).text();
            $(this).html('<input class="FClass" style="width:inherit;" type="text" id="' + title.replace(' ', '_') + '" placeholder="Search ' + title + '" />');
        });

        table = $('#tblemp').DataTable({
            "ordering": true,
            "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            "pagingType": "full_numbers",
            "scrollY": "300px",
            "scrollX": true,
            "dom": 'Blrtip', // Hides Default Search

            "processing": true,
            "serverSide": true,
            "orderMulti": false,

            "ajax": {
                "url": "/Home/getEmployee",
                "type": "POST",
                "datatype": "json"
            },
            "aoColumns": [
                { "data": "firstName" },
                { "data": "lastName" },
                { "data": "gender", },
                { "data": "salary", },
                {
                    "data": "DOj",
                    "name": "DOj",
                    "render": function (data, type, full) {
                        return new Date(full['doj']).toLocaleDateString();
                    }
                },
                {
                    "data": null,
                    "bSearchable": false,
                    "sortable": false,
                    "autoWidth": false,
                    "sWidth": "70px",
                    "targets": -1,
                    "render": function (data, type, full) {
                        return "<a onclick='Edit(" + full['id'] + ")' id='btnEdit" + full['id'] + "' class='btn btn-success btn-xs'><i class='glyphicon glyphicon-pencil'></i></a>" +
                            " <button id=" + full['id'] + " onclick='Delete(" + full['id'] + ")' class='btn btn-danger btn-xs'><i class='glyphicon glyphicon-remove'></i></button>";
                    }
                },
                //{ "data": null, "autoWidth": true }
            ]
        });

        table.columns().every(function () {
            var that = this;
            $('input', this.footer()).on('keyup change', function () {
                if (that.search() !== this.value) {
                    that
                        .search(this.value)
                        .draw();
                }
            });
        });

        function DateFormat(data) {
            var data1 = data.replace("/Date(", "").replace(")/", "");
            var date = new Date(parseInt(data1));
            var month = date.getMonth() + 1;
            return date.getDate() + "-" + (month.toString().length > 1 ? month : "0" + month) + "-" + date.getFullYear();
        }

        function Edit(EditID) {
            var getData = "Home/Edit/" + EditID;
            window.location.href = getData;
        }

        function Delete(DelId) {
            //$('.Delete').click(function (e) {
            //var DelId = $(this).attr("id");
            var getData = "Home/Edit"; // This is used to Get Employee Details

            $.ajax({
                url: getData,
                type: "GET",
                data: { ID: DelId },
                dataType: "json",
                success: function (result) {
                    var table = $('<table>').width("100%"); // To display return data in Tabular Format.

                    var d = new Date(result.doj);
                    var dFormat = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();

                    table.append("<tr><td><b>Name</b></td><td>: " + result.firstName + " " + result.lastName + "</td></tr>");
                    table.append("<tr><td><b>Gender</b></td><td>: " + result.gender + "</td></tr>");
                    table.append("<tr><td><b>Salary</b></td><td>: " + result.salary + "</td></tr>");
                    table.append("<tr><td><b>Date of Join</b></td><td>: " + dFormat + "</td></tr>");;
                    table.append("<tr><td><b>Dept ID</b></td><td>: " + result.deptId + "</td></tr>");

                    $('#DivBody').html(table);
                    $('#hfEmpID').val(DelId);
                },
                error: function (result) {
                    $('#DivBody').html(result.statusText);
                }
            });

            // Show PopUp
            $('#MyModal').modal({
                backdrop: 'static',
                keyboard: false
            });
        }
        //});

        $('#btnDelete').click(function (e) {

            var DelId = $('#hfEmpID').val();
            var getData = "Home/DeleteConfirmed/";

            $.ajax({
                url: getData,
                type: "POST",
                data: { ID: DelId },
                dataType: "json",
                success: function (result) {
                    alert(result);
                    window.location.reload();
                },
                error: function (result) {
                    alert(result.statusText);
                }
            });

            $('#MyModal').modal('hide');
        });
    </script>
}

Now ADD the below code in the HomeController.cs file [HttpPost] public ActionResult getEmployee() { try { var Draw = Request.Form["draw"].FirstOrDefault(); var Start = Request.Form["start"].FirstOrDefault(); var Length = Request.Form["length"].FirstOrDefault(); var SortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][data]"].FirstOrDefault(); var SortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault(); var firstName = Request.Form["columns[1][search][value]"].FirstOrDefault(); var lastName = Request.Form["columns[2][search][value]"].FirstOrDefault(); var gender = Request.Form["columns[3][search][value]"].FirstOrDefault(); var sal = Request.Form["columns[4][search][value]"].FirstOrDefault(); var joinDate = Request.Form["columns[5][search][value]"].FirstOrDefault(); DateTime DJ = DateTime.MinValue; if (joinDate != "") DJ = DateTime.Now.AddYears(-1); int PageSize = Length != null ? Convert.ToInt32(Length) : 0; int Skip = Start != null ? Convert.ToInt32(Start) : 0; int TotalRecords = 0; IEnumerable emp = (from e in ent.Employees where e.FirstName.Contains(firstName) && e.LastName.Contains(lastName) && e.Gender.StartsWith(gender) && e.Salary.ToString().Contains(sal) select new Employees { Id = e.Id, FirstName = e.FirstName, LastName = e.LastName, Gender = e.Gender, Salary = e.Salary, Doj = e.Doj, }).ToList(); if (!(string.IsNullOrEmpty(SortColumn) && string.IsNullOrEmpty(SortColumnDir))) { emp = emp.AsQueryable().OrderBy(SortColumn + " " + SortColumnDir).ToList(); } TotalRecords = emp.ToList().Count(); var NewItems = emp.Skip(Skip).Take(PageSize == -1 ? TotalRecords : PageSize).ToList(); return Json(new { draw = Draw, recordsFiltered = TotalRecords, recordsTotal = TotalRecords, data = NewItems }); } catch (Exception ex) { string msg = ex.Message; return null; //return CommonModel.getError(ex); } }

No comments:

Post a Comment