Tuesday 30 January 2018

example of check boxes in angular-datatable



Press Me

MVC Code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult Gets()
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                return Json(obj.EMPs.ToList(), JsonRequestBehavior.AllowGet);
            }
        }
        [HttpPost]
        public JsonResult DeleteAll(List<int> lst)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                obj.EMPs.RemoveRange(obj.EMPs.Where(m => lst.Contains(m.EID)));
                obj.SaveChanges();
                return Json("Data Deleted", JsonRequestBehavior.AllowGet);
            }
        }
    }
}


Angular js code :

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<style>
    .TBL {
        border: solid 1px #000000;
        height: auto;
        width: auto;
    }
</style>

<link rel="stylesheet" href="~/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/jquery.dataTables.min.css" />
<script type="text/javascript" src="~/scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/scripts/jquery.dataTables.js"></script>
<script type="text/javascript" src="~/scripts/angular.js"></script>
<script type="text/javascript" src="~/scripts/angular-datatables.js"></script>

<div class="container" ng-app="app" ng-controller="Ctrl" style="margin-top:20px">
    <div class="TBL">
        <table id="dt" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-bordered table-hover table-condensed table-responsive table-striped"></table>
    </div>
    <br /><br />
    <p>   
    <input type="button" value="Delete All" class="btn btn-primary" ng-click="display()" />
    </p>

</div>

<script type="text/javascript">
    var app = angular.module('app', ['datatables']);
    app.controller('Ctrl', function ($scope, $http, $compile, $window, DTOptionsBuilder, DTColumnBuilder) {
       
        $scope.arr = [];
        $scope.selected = {};
        $scope.selectAll = false;
        $scope.toggleAll = toggleAll;
        $scope.toggleOne = toggleOne;
        var titleHtml = '<input type="checkbox" ng-model="selectAll" ng-click="toggleAll(selectAll, selected)">';
       
     
            $scope.dtColumns = [
             DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable()
        .renderWith(function (data, type, full, meta) {
            $scope.selected[full.EID] = false;
            return '<input type="checkbox" ng-model="selected[' + data.EID + ']" ng-click="toggleOne(selected)">';
        }).withClass("text-center"),
        DTColumnBuilder.newColumn('EID').withTitle('Eid'),
        DTColumnBuilder.newColumn("firstName", "First Name"),
        DTColumnBuilder.newColumn("lastName", "Last Name")
        ]
            $scope.dtOptions = DTOptionsBuilder.newOptions()
                .withOption('stateSave', true)
                .withOption('responsive', true)
                .withOption("bProcessing", true)
                .withOption('bFilter', true)
                .withOption('ajax', {
                    url: "/Home/Gets",
                    type: "Get",
                    catch: false
                })
            .withOption('aLengthMenu', [2, 10, 20, 30, 50])
            .withPaginationType('full_numbers')
            .withDisplayLength(2)
                .withOption('headerCallback', function (header) {
                    if (!$scope.headerCompiled) {
                        $scope.headerCompiled = true;
                        $compile(angular.element(header).contents())($scope);
                    }
                })
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);

            });
           


       
       
        function toggleAll(selectAll, selectedItems) {
            for (var id in selectedItems) {
               
                if (selectedItems.hasOwnProperty(id)) {
                    selectedItems[id] = selectAll;
                   
                }
            }
        }
        function toggleOne(selectedItems) {
            for (var id in selectedItems) {
                if (selectedItems.hasOwnProperty(id)) {
                    if (!selectedItems[id]) {
                        $scope.selectAll = false;
                        return;
                    }
                   
                     
                }
            }
            $scope.selectAll = true;
        }
     
        $scope.display = function ()
        {
            angular.forEach($scope.selected, function (i, j) {
                if (i==true)
                {
                    $scope.arr.push(j);
                }
            });
            var confic = {
                 type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false
            };
            if (confirm('Do you want to delete selected items from the list ?'))
            {
                $http.post("/Home/DeleteAll", $scope.arr, confic).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
        }
        });
</script>

Sunday 28 January 2018

DML operation with multiple delete using angular-datatables,angularjs,MVC


MVC CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
       
        public JsonResult Save(EMP emp)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                obj.Entry(emp).State = System.Data.Entity.EntityState.Added;
                obj.SaveChanges();
                return Json("Data Saved", JsonRequestBehavior.AllowGet);
            }
        }
     
        public JsonResult Update(EMP emp)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                obj.Entry(emp).State = System.Data.Entity.EntityState.Modified;
                obj.SaveChanges();
                return Json("Data Updated", JsonRequestBehavior.AllowGet);
            }
        }
   
        public JsonResult Delete(int EID)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                EMP emp = obj.EMPs.Find(EID);
                obj.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
                obj.SaveChanges();
                return Json("Data Deleted", JsonRequestBehavior.AllowGet);
            }
        }
        [HttpPost]
        public JsonResult DeleteAll(List<int> lst)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {

                obj.EMPs.RemoveRange(obj.EMPs.Where(m => lst.Contains(m.EID)));
                obj.SaveChanges();
                return Json("Data Deleted", JsonRequestBehavior.AllowGet);
            }
        }

        [OutputCache(Duration =0)]
        public JsonResult Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.EMPs.ToList(), JsonRequestBehavior.AllowGet);
            }
               
        }
     
        public JsonResult Get(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.EMPs.SingleOrDefault(m=>m.EID==EID), JsonRequestBehavior.AllowGet);
            }

        }

    }
}

VIEW CODE :



@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2></h2>
<style>
    .TBL {
        border: solid 1px #000000;
        height: auto;
        width: auto;
    }
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables_themeroller.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/angular-datatables.js"></script>
<div class="container" ng-app="app" ng-controller="Ctrl" style="margin-top:20px">
    <form class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-lg-4">EID</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.EID"  class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4">NAME</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.NAME" class="form-control" />
             
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4">DID</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.DID" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <input type="button"  class="btn btn-primary" value="Save" ng-click="save()" style="width:80px" />
                <input type="button" class="btn btn-primary" value="Update" ng-click="update()" style="width:80px" />
                <input type="button" class="btn btn-primary" value="Reset" ng-click="reset()" style="width:80px" />
                <input type="button" class="btn btn-primary" value="Delete All" ng-click="delall()" style="width:80px" />
            </div>
        </div>
    </form>
    <div class="TBL">
        <table id="dt" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-bordered table-hover table-condensed table-responsive table-striped"></table>
    </div>
</div>
<script type="text/javascript">
    var app = angular.module('app', ['datatables']);
    app.controller('Ctrl',
        function ($scope, $http, $compile,$window, DTOptionsBuilder, DTColumnBuilder) {
            function CLR()
            {
                $scope.EMP = {
                    EID: null,
                    NAME: null,
                    DID:null
                };
            } CLR();
            $scope.save = function ()
            {
                $http.post("/Test/Save", $scope.EMP).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
            $scope.update = function () {
                $http.post("/Test/Update", $scope.EMP).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
            $scope.edit = function (s) {
                $http.get("/Test/Get?EID="+s).then(function (promise) {
                  $scope.EMP=   promise.data;
                });

            }
            $scope.delete = function (s) {
                if (confirm('Do you want to delete it ?'))
                {
                    $http.get("/Test/Delete?EID=" + s).then(function (promise) {
                        alert(promise.data);
                        $window.location.reload();
                    });

                }
            }
            $scope.reset = function () {
                CLR();
            }
            $scope.selected = [];
         
            $('.TBL').on("click", '.hcb', function () {
                if ($(this).is(":checked")) {
                    $('#dt_paginate').css("display", "none");
                    $('#dt').find('.cb').prop("checked", true);
                    $('#dt').find('tr').find('td:first').next().each(function (i, j) {
                        $scope.selected.push($(j).html());
                    });
                }
                else {
                    $('#dt_paginate').css("display", "block");
                    $('#dt').find('.cb').prop("checked", false);
                }
                   
            });
            $('.TBL').on("click", '.cb', function () {
                if ($('#dt .cb').length == $('#dt .cb:checked').length)
                    $('#dt .hcb').prop("checked", true);
                else
                    $('#dt .hcb').prop("checked", false);
               $scope.selected.push($(this).parents('tr:first').children('td:first').next().html());
            });
            $scope.delall = function ()
            {
                if ($('#dt .cb:checked').length == 0)
                {
                    alert('Please select atleast one item from the gride.');
                    return;
                }
                if (confirm('Do you want to delete it ?'))
                {
                    $http.post("/Test/DeleteAll", $scope.selected).then(function (promise) {
                        alert(promise.data);
                        $window.location.reload();
                    });
               
                }
            }
            function fill()
            {
                $scope.dtColumns = [
                   
                     DTColumnBuilder.newColumn("Select")
                    .withTitle('<input type="checkbox"  class="hcb" />')
                    .notSortable()
                    .withOption("searchable", false)
                    .renderWith(function (data, type, full, meta) {
                        return '<input type="checkbox"  class="cb"   />';
                    }).withClass("text-center"),
                DTColumnBuilder.newColumn('EID').withTitle('Eid'),
                DTColumnBuilder.newColumn("NAME", "NAME"),
                DTColumnBuilder.newColumn("DID", "DID").notVisible(),
                DTColumnBuilder.newColumn(null).withTitle('ACTION').notSortable()
                   .renderWith(function (data, type, full, meta) {
                       return '<button class="glyphicon glyphicon-edit" ng-click="edit(' + data.EID + ')">' +
                        '</button>&nbsp;' +
                        '<button class="glyphicon glyphicon-remove" ng-click="delete(' + data.EID + ')">' +
                        '</button>';
                   })
            ]
            $scope.dtOptions = DTOptionsBuilder.newOptions()
                .withOption('responsive', true)
                .withOption("bProcessing", true)
                .withOption('bFilter', true)
                .withOption('ajax', {
                    url: "/Test/Gets",
                    type: "Get",
                    catch:false
            })
            .withOption('aLengthMenu', [2, 10, 20, 30, 50])
            .withPaginationType('full_numbers')
            .withDisplayLength(2)
             .withOption('createdRow', function (row, data, dataIndex) {
                 $compile(angular.element(row).contents())($scope);
               
             });
            } fill();
         

        });


</script>


Saturday 27 January 2018

DML operation using angular-datatables,angularjs,MVC


MVC Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
        
        public JsonResult Save(EMP emp)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                obj.Entry(emp).State = System.Data.Entity.EntityState.Added;
                obj.SaveChanges();
                return Json("Data Saved", JsonRequestBehavior.AllowGet);
            }
        }
       
        public JsonResult Update(EMP emp)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                obj.Entry(emp).State = System.Data.Entity.EntityState.Modified;
                obj.SaveChanges();
                return Json("Data Updated", JsonRequestBehavior.AllowGet);
            }
        }
     
        public JsonResult Delete(int EID)
        {
            using (Database1Entities obj = new Models.Database1Entities())
            {
                EMP emp = obj.EMPs.Find(EID);
                obj.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
                obj.SaveChanges();
                return Json("Data Deleted", JsonRequestBehavior.AllowGet);
            }
        }
       
        [OutputCache(Duration =0)]
        public JsonResult Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.EMPs.ToList(), JsonRequestBehavior.AllowGet);
            }
                
        }
       
        public JsonResult Get(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return Json(obj.EMPs.SingleOrDefault(m=>m.EID==EID), JsonRequestBehavior.AllowGet);
            }

        }

    }
}


Angular Js Code :



@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2></h2>
<style>
    .TBL {
        border: solid 1px #000000;
        height: auto;
        width: auto;
    }
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables_themeroller.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/angular-datatables.js"></script>
<div class="container" ng-app="app" ng-controller="Ctrl" style="margin-top:20px">
    <form class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-lg-4">EID</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.EID" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4">NAME</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.NAME" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4">DID</label>
            <div class="col-lg-4">
                <input type="text" ng-model="EMP.DID" class="form-control" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <input type="button"  class="btn btn-primary" value="Save" ng-click="save()" style="width:80px" />
                <input type="button" class="btn btn-primary" value="Update" ng-click="update()" style="width:80px" />
                <input type="button" class="btn btn-primary" value="Reset" ng-click="reset()" style="width:80px" />
            </div>
        </div>
    </form>
    <div class="TBL">
        <table id="dt" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-bordered table-hover table-condensed table-responsive table-striped"></table>
    </div>
</div>
<script type="text/javascript">
    var app = angular.module('app', ['datatables']);
    app.controller('Ctrl',
        function ($scope, $http, $compile,$window, DTOptionsBuilder, DTColumnBuilder) {
            function CLR()
            {
                $scope.EMP = {
                    EID: null,
                    NAME: null,
                    DID:null
                };
            } CLR();
            $scope.save = function ()
            {
                $http.post("/Test/Save", $scope.EMP).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
            $scope.update = function () {
                $http.post("/Test/Update", $scope.EMP).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
            $scope.edit = function (s) {
                $http.get("/Test/Get?EID="+s).then(function (promise) {
                  $scope.EMP=   promise.data;
                });

            }
            $scope.delete = function (s) {
                if (confirm('Do you want to delete it ?'))
                {
                    $http.get("/Test/Delete?EID=" + s).then(function (promise) {
                        alert(promise.data);
                        $window.location.reload();
                    });

                }
            }
            $scope.reset = function () {
                CLR();
            }
            function fill()
            { 
            $scope.dtColumns = [
                DTColumnBuilder.newColumn('EID').withTitle('Eid'),
                DTColumnBuilder.newColumn("NAME", "NAME"),
                DTColumnBuilder.newColumn("DID", "DID").notVisible(),
                DTColumnBuilder.newColumn(null).withTitle('ACTION').notSortable()
                   .renderWith(function (data, type, full, meta) {
                       return '<button class="glyphicon glyphicon-edit" ng-click="edit(' + data.EID + ')">' +
                        '</button>&nbsp;' +
                        '<button class="glyphicon glyphicon-remove" ng-click="delete(' + data.EID + ')">' +
                        '</button>';
                   })
            ]
            $scope.dtOptions = DTOptionsBuilder.newOptions()
                .withOption('responsive', true)
                .withOption("bProcessing", true)
                .withOption('bFilter', true)
                .withOption('ajax', {
                    url: "/Test/Gets",
                    type: "Get",
                    catch:false
            })
            .withOption('aLengthMenu', [2, 10, 20, 30, 50])
            .withPaginationType('full_numbers')
            .withDisplayLength(2)
             .withOption('createdRow', function (row, data, dataIndex) {
                 $compile(angular.element(row).contents())($scope);
             });
            } fill();

        });


</script>



Using jquery data table in angular js & MVC



MVC code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult Gets()
        {
            List<EMP> lst1 = new List<EMP>() {
                 new EMP { DID=1, NAME="A",EID=1 },
                 new EMP { DID=1, NAME="B",EID=2 },
                 new EMP { DID=2, NAME="C" ,EID=3},
                 new EMP { DID=2, NAME="D" ,EID=4},
                 new EMP { DID=3, NAME="E" ,EID=5},
                 new EMP { DID=3, NAME="F" ,EID=6}
            };
            return Json(lst1.ToList(), JsonRequestBehavior.AllowGet);

        }
       public class EMP
        {
            public int EID { get; set; }
            public string NAME { get; set; }
            public int DID { get; set; }
        }
    }
}

View Code :


@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2></h2>
<style>
    .TBL{
    border:solid 1px #000000;
    height:auto;
    width:auto
    }
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables_themeroller.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/angular-datatables.js"></script>
<div class="container" ng-app="app" ng-controller="Ctrl" style="margin-top:20px">
    <div class="TBL">
        <table id="entry-grid" datatable="" dt-options="dtOps" dt-columns="dtCol" class="table table-bordered table-hover table-condensed table-responsive table-striped"></table>
    </div>
</div>
<script type="text/javascript">
    var app = angular.module('app', ['datatables']);
    app.controller('Ctrl',
        function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
            $scope.dtCol = [
                DTColumnBuilder.newColumn("EID", "EID"),
                DTColumnBuilder.newColumn("NAME", "NAME"),
                DTColumnBuilder.newColumn("DID", "DID")
            ]
            $scope.dtOps = DTOptionsBuilder.newOptions().withOption('ajax', {
                url: "/Test/Gets",
                type: "Get"
            })
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        });

 
</script>


Thursday 25 January 2018

Nested jquery datatable in MVC


MVC CODE :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
       
        [HttpGet]
        public JsonResult Gets()
        {
            List<EMP> lst1 = new List<EMP>() {
                 new EMP { DID=1, NAME="A",EID=1 },
                 new EMP { DID=1, NAME="B",EID=2 },
                 new EMP { DID=2, NAME="C" ,EID=3},
                 new EMP { DID=2, NAME="D" ,EID=4},
                  new EMP { DID=3, NAME="E" ,EID=5},
                 new EMP { DID=3, NAME="F" ,EID=6}
            };
            List<DEPT> lst = new List<DEPT>() {
                 new DEPT { DID=1, DNAME="X", LEMP=lst1.Where(m=>m.DID==1).ToList() },
                 new DEPT { DID=2, DNAME="Y",LEMP=lst1.Where(m=>m.DID==2).ToList() },
                 new DEPT { DID=3, DNAME="Z" ,LEMP=lst1.Where(m=>m.DID==3).ToList()}
            };
                 return Json(lst.ToList(), JsonRequestBehavior.AllowGet);
           
        }
        public class DEPT
        {
            public int DID { get; set; }
            public string DNAME { get; set; }
            public List<EMP> LEMP { get; set; }
        }
        public class EMP
        {
            public int EID { get; set; }
            public string NAME { get; set; }
            public int DID { get; set; }
        }
    }
}

VIEW CODE :



@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Jay Jagannath...</h2>

<style>
    .tbl {
        border:solid 1px #000000;
        height:auto;
        width:auto
    }
    td.details-control {
        background: url('../Content/DataTables/images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    td.abc {
        background: url('../Content/DataTables/images/details_close.png') no-repeat center center;
    }
 
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.12.4.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>
<div class="container">
    <div >
        <table id="exampleTable" class="tbl">
            <thead>
                <tr>
                    <th>DID</th>
                    <th>DNAME</th>
                   
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <div style="display:none" >
        <table id="detailsTable">
            <thead>
                <tr>
                    <th>EID</th>
                    <th>NAME</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>


</div>
<script type="text/javascript">

    function fnFormatDetails(table_id, html) {
        var sOut = "<table class='tbl' id=\"exampleTable_" + table_id + "\">";
        sOut += html;
        sOut += "</table>";
        return sOut;
    }
    var iTableCounter = 1;
    var oTable;
    var oInnerTable;
    var detailsTableHtml;
    $(document).ready(function () {
        detailsTableHtml = $("#detailsTable").html();
        var nCloneTh = document.createElement('th');
       var nCloneTd = document.createElement('td');
        nCloneTd.className = "center";
        $('#exampleTable thead tr').each(function () {
            this.insertBefore(nCloneTh, this.childNodes[0]);
        });
   
        var newRowData;
        var oTable = null;
        $.ajax({
            "url": "/Test/Gets",
            type: 'Get',
            datatype: 'json',
            cache: false,
            success: function (Data) {
                newRowData = Data;
                oTable = $('#exampleTable').dataTable({
                    "pagingType": "full_numbers",
                    "lengthMenu": [2, 10, 20],
                    "bJQueryUI": true,
                    "aaData": Data,
                    "aoColumns": [
                         {
                             "className": 'details-control',
                             "orderable": false,
                             "data": null,
                             "defaultContent": ''

                         },
                        { "mDataProp": "DID" },
                        { "mDataProp": "DNAME" }
                    ],
                    "oLanguage": {
                        "sInfo": "_TOTAL_ entries"
                    },
                    "aaSorting": [[1, 'asc']]
                });
            }
        });


        $('#exampleTable tbody').on('click', 'td.details-control', function () {
            var nTr = $(this).parents('tr')[0];
            var nTds = this;
            if (oTable.fnIsOpen(nTr)) {
                $(this).parents('tr:first').children('td:first').removeClass("abc");
                oTable.fnClose(nTr);
            }
            else {
                $(this).parents('tr:first').children('td:first').addClass("abc");
                var rowIndex = oTable.fnGetPosition($(nTds).closest('tr')[0]);
                var detailsRowData = newRowData[rowIndex].LEMP;
                oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, detailsTableHtml), 'details');
                oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
                    "bJQueryUI": true,
                    "bFilter": false,
                    "aaData": detailsRowData,
                    "bSort": true,
                    "aoColumns": [
                 { "mDataProp": "EID" },
                 { "mDataProp": "NAME" },
                 ],
                    "bPaginate": false,
                    "oLanguage": {
                        "sInfo": "_TOTAL_ entries"
                    }
                   
                });
                iTableCounter = iTableCounter + 1;
            }
        });


    });

</script>

Wednesday 24 January 2018

Nested datatable using jquery datatable

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Jay Jagannath...</h2>
<style>
   body {
    font-size: 14px;
    font-family: Helvetica, Arial, sans-serif;
    color: #666;
}

h4 {
    font-size: 16px;
    color: #dd007d;
}

table{
    font-size: 14px;
    font-family: Helvetica, Arial, sans-serif;
    color: #666;
}
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.12.4.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>
<div class="container">
    <table id="exampleTable">
        <thead>
            <tr>
                <th>Race</th>
                <th>Year</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div style="display:none">
        <table id="detailsTable">
            <thead>
                <tr>
                    <th>Photo</th>
                    <th>Name</th>
                    <th>Team</th>
                    <th>Server</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>


</div>
<script type="text/javascript">
   
    function fnFormatDetails(table_id, html) {
        var sOut = "<table id=\"exampleTable_" + table_id + "\">";
        sOut += html;
        sOut += "</table>";
        return sOut;
    }

    //////////////////////////////////////////////////////////// EXTERNAL DATA - Array of Objects

    var terranImage = "https://i.imgur.com/HhCfFSb.jpg";
    var jaedongImage = "https://i.imgur.com/s3OMQ09.png";
    var grubbyImage = "https://i.imgur.com/wnEiUxt.png";
    var stephanoImage = "https://i.imgur.com/vYJHVSQ.jpg";
    var scarlettImage = "https://i.imgur.com/zKamh3P.jpg";

    // DETAILS ROW A
    var detailsRowAPlayer1 = { pic: jaedongImage, name: "Jaedong", team: "evil geniuses", server: "NA" };
    var detailsRowAPlayer2 = { pic: scarlettImage, name: "Scarlett", team: "acer", server: "Europe" };
    var detailsRowAPlayer3 = { pic: stephanoImage, name: "Stephano", team: "evil geniuses", server: "Europe" };

    var detailsRowA = [detailsRowAPlayer1, detailsRowAPlayer2, detailsRowAPlayer3];

    // DETAILS ROW B
    var detailsRowBPlayer1 = { pic: grubbyImage, name: "Grubby", team: "independent", server: "Europe" };

    var detailsRowB = [detailsRowBPlayer1];

    // DETAILS ROW C
    var detailsRowCPlayer1 = { pic: terranImage, name: "Bomber", team: "independent", server: "NA" };

    var detailsRowC = [detailsRowCPlayer1];

    var rowA = { race: "Zerg", year: "2014", total: "3", details: detailsRowA };
    var rowB = { race: "Protoss", year: "2014", total: "1", details: detailsRowB };
    var rowC = { race: "Terran", year: "2014", total: "1", details: detailsRowC };

    var newRowData = [rowA, rowB, rowC];

    ////////////////////////////////////////////////////////////

    var iTableCounter = 1;
    var oTable;
    var oInnerTable;
    var detailsTableHtml;

    //Run On HTML Build
    $(document).ready(function () {

        // you would probably be using templates here
        detailsTableHtml = $("#detailsTable").html();

        //Insert a 'details' column to the table
        var nCloneTh = document.createElement('th');
        var nCloneTd = document.createElement('td');
        nCloneTd.innerHTML = '<img src="http://i.imgur.com/SD7Dz.png">';
        nCloneTd.className = "center";

        $('#exampleTable thead tr').each(function () {
            this.insertBefore(nCloneTh, this.childNodes[0]);
        });

        $('#exampleTable tbody tr').each(function () {
            this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
        });


        //Initialse DataTables, with no sorting on the 'details' column
        var oTable = $('#exampleTable').dataTable({
            "bJQueryUI": true,
            "aaData": newRowData,
            "bPaginate": false,
            "aoColumns": [
                {
                    "mDataProp": null,
                    "sClass": "control center",
                    "sDefaultContent": '<img src="http://i.imgur.com/SD7Dz.png">'
                },
                { "mDataProp": "race" },
                { "mDataProp": "year" },
                { "mDataProp": "total" }
            ],
            "oLanguage": {
                "sInfo": "_TOTAL_ entries"
            },
            "aaSorting": [[1, 'asc']]
        });

        /* Add event listener for opening and closing details
        * Note that the indicator for showing which row is open is not controlled by DataTables,
        * rather it is done here
        */
        $('#exampleTable tbody td img').on('click', function () {
            var nTr = $(this).parents('tr')[0];
            var nTds = this;

            if (oTable.fnIsOpen(nTr)) {
                /* This row is already open - close it */
                this.src = "http://i.imgur.com/SD7Dz.png";
                oTable.fnClose(nTr);
            }
            else {
                /* Open this row */
                var rowIndex = oTable.fnGetPosition($(nTds).closest('tr')[0]);
                var detailsRowData = newRowData[rowIndex].details;

                this.src = "http://i.imgur.com/d4ICC.png";
                oTable.fnOpen(nTr, fnFormatDetails(iTableCounter, detailsTableHtml), 'details');
                oInnerTable = $("#exampleTable_" + iTableCounter).dataTable({
                    "bJQueryUI": true,
                    "bFilter": false,
                    "aaData": detailsRowData,
                    "bSort": true, // disables sorting
                    "aoColumns": [
                    { "mDataProp": "pic" },
                { "mDataProp": "name" },
                { "mDataProp": "team" },
                { "mDataProp": "server" }
                    ],
                    "bPaginate": false,
                    "oLanguage": {
                        "sInfo": "_TOTAL_ entries"
                    },
                    "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                        var imgLink = aData['pic'];
                        var imgTag = '<img width="100px" src="' + imgLink + '"/>';
                        $('td:eq(0)', nRow).html(imgTag);
                        return nRow;
                    }
                });
                iTableCounter = iTableCounter + 1;
            }
        });


    });
</script>

Tuesday 23 January 2018

Nested jquery Datatable


@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Jay Jagannath...</h2>
<style>
    td.details-control {
        background: url('../Content/DataTables/images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    tr.shown td.details-control {
        background: url('../Content/DataTables/images/details_close.png') no-repeat center center;
    }
    .c {
    list-style:none;
    }
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.12.4.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>
<div class="container">
    <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th></th>
                <th>DID</th>
                <th>DNAME</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script type="text/javascript">
   
    function format(d) {

        var tr = $(document.createElement('div'));
        $.ajax({
                 url: "/Test/Get",
                 type: 'Get',
                 datatype: 'json',
                 cache: false,
                 data: { DID: d.DID },
                 success: function (Data) {
                     $.each(Data, function (i, j) {
                         tr.append("<li  >" + j.EID + "<\li><li >" + j.NAME + "<\li>");
                     });

                 }

        });
        tr.addClass("c");
        return tr;
    }

    $(document).ready(function () {

        var table = null;
        $.ajax({
            "url": "/Test/Gets",
            type: 'Get',
            datatype: 'json',
            cache:false,
            success: function (Data) {
             table=$('#example').DataTable({
                    data:Data,
                    columns: [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        { "data": "DID" },
                        { "data": "DNAME" }
                    ],
                    "order": [[1, 'asc']]
                });
            }
            });

       
        $('#example tbody').on('click', 'td.details-control', function () {

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
               
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
               
                row.child(format(row.data())).show();
                tr.addClass('shown');
            }
        });
    });
</script>

Nested jquery Data Table


@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Jay Jagannath...</h2>
<style>
    td.details-control {
    background: url('../Content/DataTables/images/details_open.png') no-repeat center center;
    cursor: pointer;
}
tr.shown td.details-control {
    background: url('../Content/DataTables/images/details_close.png') no-repeat center center;
}
</style>
<link type="text/css" rel="stylesheet" href="~/Content/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="~/Content/DataTables/css/jquery.dataTables.css" />
<script type="text/javascript" src="~/scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/scripts/DataTables/jquery.dataTables.js"></script>
<div class="container">
    <table cellpadding="3" cellspacing="0" border="0" style="padding-left:50px;" id="tb"></table>
    <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th></th>
                <th>DID</th>
                <th>DNAME</th>
            </tr>
        </thead>
        <tbody></tbody>
        </table>
</div>
<script type="text/javascript">
    /* Formatting function for row details - modify as you need */
    function format(d) {

        //var n = $('#tb');
        //n.find('tr').each(function (i, j) {
        //    $(j).remove();
        //});
        //$.ajax({
        //         url: "/Home/Get",
        //         type: 'Get',
        //         datatype: 'json',
        //         cache: false,
        //         data: { DID: d.DID },
        //         success: function (Data) {
        //             $.each(Data, function (i, j) {
        //            n.append("<tr class='c'><td>"+j.EID+"</td><td>"+j.NAME+"</td></tr>");
        //             });

        //         }

        //});
        //return n;
       
       
            // `d` is the original data object for the row
            return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                '<tr>' +
                    '<td>Full name:</td>' +
                    '<td>' + d.name + '</td>' +
                '</tr>' +
                '<tr>' +
                    '<td>Extension number:</td>' +
                    '<td>' + d.extn + '</td>' +
                '</tr>' +
                '<tr>' +
                    '<td>Extra info:</td>' +
                    '<td>And any further details here (images etc)...</td>' +
                '</tr>' +
            '</table>';
       

     
     
    }

    $(document).ready(function () {

        var table = null;
        $.ajax({
            "url": "/Home/Gets",
            type: 'Get',
            datatype: 'json',
            cache:false,
            success: function (Data) {
             table=$('#example').DataTable({
                    data:Data,
                    columns: [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        { "data": "DID" },
                        { "data": "DNAME" }
                    ],
                    "order": [[1, 'asc']]
                });
            }
            });
       
        // Add event listener for opening and closing details
        $('#example tbody').on('click', 'td.details-control', function () {
           
            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');
            }
        });
    });
</script>