Wednesday 28 March 2018

Bootstrap Multi select example


View Model :

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

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public int CID { get; set; }
        public List<SelectListItem> LCOUNTRY { get; set; }
        public List< int> SID { get; set; }
        public EMPVM()
        {
            LCOUNTRY = new List<SelectListItem>();
            SID = new List<int>();
        }
    }
}


View code :

@model WebApplication1.Models.EMPVM

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
     
        <div class="form-horizontal">
     
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.CID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.ListBoxFor(model => model.SID,Model.LCOUNTRY, new {@class = "form-control" ,@style="width:200px" } )
                    @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
                </div>
            </div>
 
            <br /><br />
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
 
 
</body>
</html>
<link rel="stylesheet" href="~/bootstrap-3.3.2.min.css" />
<link rel="stylesheet" href="~/bootstrap-multiselect.css" />
<script src="~/scripts/jquery-1.12.4.min.js"></script>
<script src="~/scripts/bootstrap-3.3.2.min.js"></script>
<script src="~/scripts/bootstrap-multiselect.js"></script>

<script type="text/javascript">
    $(function () {
        $('#SID').multiselect();
    });
</script>

Reset Multiselect :

$('#SID option:selected').each(function () {
                $(this).prop('selected', false);
            })


            $('#SID').multiselect('refresh');

Multiselect with autocomplete example

Press Me


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

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public int CID { get; set; }
        public List<SelectListItem> LCOUNTRY { get; set; }
        public List< int> SID { get; set; }
        public EMPVM()
        {
            LCOUNTRY = new List<SelectListItem>();
            SID = new List<int>();
        }
    }
}

View code :

@model WebApplication1.Models.EMPVM

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal">
     
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.CID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.ListBoxFor(model => model.SID,Model.LCOUNTRY, new {@class = "form-control" ,@style="width:200px" } )
                    @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <br /><br />
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
   
 
</body>
</html>
<link rel="stylesheet" href="~/chosen.css" />
<script src="~/scripts/jquery-1.12.4.min.js"></script>
<script src="~/scripts/chosen.jquery.js"></script>
<script src="~/scripts/chosen.proto.js"></script>
<script type="text/javascript">
    $(function () {
        $('#SID').chosen();
    });
</script>

Drop down with autocomplete Example


View Model  :

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

namespace WebApplication1.Models
{
    public class EMPVM
    {
        public int CID { get; set; }
        public List<SelectListItem> LCOUNTRY { get; set; }
        public List< int> SID { get; set; }
        public EMPVM()
        {
            LCOUNTRY = new List<SelectListItem>();
            SID = new List<int>();
        }
    }
}

View code.

@model WebApplication1.Models.EMPVM

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
       
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.CID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.CID,Model.LCOUNTRY,"Select...", new {@class = "form-control" ,@style="width:200px" } )
                    @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <br /><br />
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
   
</body>
</html>
<link rel="stylesheet" href="~/chosen.css" />
<script src="~/scripts/jquery-1.12.4.min.js"></script>
<script src="~/scripts/chosen.jquery.js"></script>
<script src="~/scripts/chosen.proto.js"></script>
<script type="text/javascript">
    $(function () {
        $('#CID').chosen();
    });
</script>

Reset Dropdown Code :

$('#CID').val('').trigger('chosen:updated');

Sunday 18 March 2018

CURD oration with multiple delete using angular js & web api.


WEB API :

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    [RoutePrefix("api/Empservices")]
    public class EmpservicesController : ApiController
    {
        [Route("Countries")]
        [HttpGet]
        public IHttpActionResult Countries()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = obj.COUNTRies.ToList();
                    if (data.Count > 0)
                        return Ok(data);
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }
        [Route("States/{CID:int}")]
        [HttpGet]
        public IHttpActionResult States(int CID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = obj.STATEs.Where(m=>m.CID==CID).ToList();
                    if (data.Count > 0)
                        return Ok(data);
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Hobbies")]
        [HttpGet]
        public IHttpActionResult Hobbies()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = obj.HOBBies.ToList();
                    if (data.Count > 0)
                        return Ok(data);
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Emps")]
        [HttpGet]
        public IHttpActionResult Emps()
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = obj.EMPs.ToList();
                    if (data.Count > 0)
                        return Ok(data);
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Emp/{EID:int}",Name ="Emp")]
        [HttpGet]
        public IHttpActionResult Emp(int EID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = obj.EMPs.Where(m => m.EID == EID).Select(p => new EMPVM { EID = p.EID, NAME = p.NAME, ADDRESS = p.ADDRESS, PASSWORD = p.PASSWORD, GENDER = p.GENDER, CID = p.CID, SID = p.SID, HLIST = obj.EMPMAPs.Where(t => t.EID == EID).Select(v => v.HID.Value).ToList() }).FirstOrDefault();
                    if (data!=null)
                        return Ok(data);
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Save")]
        [HttpPost]
        public IHttpActionResult Save([FromBody]EMPVM eMPVM)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = eMPVM;
                    if (data != null)
                    {
                        EMP emp = new EMP();
                        emp.EID = eMPVM.EID;
                        emp.NAME = eMPVM.NAME;
                        emp.ADDRESS = eMPVM.ADDRESS;
                        emp.PASSWORD = eMPVM.PASSWORD;
                        emp.GENDER = eMPVM.GENDER;
                        emp.CID = eMPVM.CID;
                        emp.SID = eMPVM.SID;
                        obj.Entry(emp).State = EntityState.Added;
                        obj.SaveChanges();
                        obj.EMPMAPs.AddRange(eMPVM.HLIST.Select(p => new EMPMAP { EID = eMPVM.EID, HID = p }).ToList());
                        obj.SaveChanges();
                        return Created(new Uri(Url.Link("Emp", new { EID = eMPVM.EID })), "Data Saved.");
                    }
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Update/{EID:int}")]
        [HttpPut]
        public IHttpActionResult Update([FromUri]int EID,[FromBody]EMPVM eMPVM)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    var data = eMPVM;
                    if (data != null)
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        emp.NAME = eMPVM.NAME;
                        emp.ADDRESS = eMPVM.ADDRESS;
                        emp.PASSWORD = eMPVM.PASSWORD;
                        emp.GENDER = eMPVM.GENDER;
                        emp.CID = eMPVM.CID;
                        emp.SID = eMPVM.SID;
                        obj.Entry(emp).State = EntityState.Modified;
                        obj.SaveChanges();
                        obj.EMPMAPs.RemoveRange(obj.EMPMAPs.Where(m => m.EID == EID));
                        obj.SaveChanges();
                        obj.EMPMAPs.AddRange(eMPVM.HLIST.Select(p => new EMPMAP { EID = eMPVM.EID, HID = p }).ToList());
                        obj.SaveChanges();
                        return Ok("Data Updated.");
                    }
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Delete/{EID:int}")]
        [HttpDelete]
        public IHttpActionResult Delete([FromUri]int EID)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                    EMP data = obj.EMPs.Find(EID);
                    if (data != null)
                    {
                        obj.Entry(data).State = EntityState.Deleted;
                        obj.SaveChanges();
                        obj.EMPMAPs.RemoveRange(obj.EMPMAPs.Where(m => m.EID == EID));
                        obj.SaveChanges();
                        return Ok("Data Deleted.");
                    }
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        [Route("Alldelete")]
        [HttpPost]
        public IHttpActionResult Alldelete([FromBody]List<int> listemp)
        {
            try
            {
                using (Database1Entities obj = new Models.Database1Entities())
                {
                   
                    if (listemp.Count>0)
                    {
                        obj.EMPs.RemoveRange(obj.EMPs.Where(t => listemp.Contains(t.EID)));
                        obj.SaveChanges();
                        obj.EMPMAPs.RemoveRange(obj.EMPMAPs.Where(m => listemp.Contains(m.EID.Value)));
                        obj.SaveChanges();
                        return Ok("Data Deleted.");
                    }
                    else
                        return Content(HttpStatusCode.NoContent, "Data not availeble.");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }


    }
}


Angular js :


AddorEdit page :

<div class="modal-header">
    <button type="button" ng-click="cancel()" class="close" data-dismiss="modal">&times;</button>
    <h4>Employee Details</h4>
</div>
<div class="modal-body">
    <form class="form-horizontal" novalidate name="frmEmp">
        <div class="form-group" ng-class="{'has-error':frmEmp.txtEid.$invalid,'has-success':frmEmp.txtEid.$valid}">
            <label class="control-label col-lg-2">EID</label>
            <div class="col-lg-6">
                <input type="text" class="form-control" ng-model="EMP.EID" required name="txtEid" />
            </div>
            <div class="help-block has-error" ng-show="frmEmp.txtEid.$invalid && frmEmp.txtEid.$touched">
                Eid should not blank.
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.txtName.$invalid,'has-success':frmEmp.txtName.$valid}">
            <label class="control-label col-lg-2">NAME</label>
            <div class="col-lg-6">
                <input type="text" class="form-control" ng-model="EMP.NAME" required name="txtName" />
            </div>
            <div class="help-block has-error" ng-show="frmEmp.txtName.$invalid && frmEmp.txtName.$touched">
                Name should not blank.
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.txtAdd.$invalid,'has-success':frmEmp.txtAdd.$valid}">
            <label class="control-label col-lg-2">ADDRESS</label>
            <div class="col-lg-6">
                <textarea  class="form-control" ng-model="EMP.ADDRESS" required name="txtAdd" ></textarea>
            </div>
            <div class="help-block has-error" ng-show="frmEmp.txtAdd.$invalid && frmEmp.txtAdd.$touched">
                Address should not blank.
            </div>
        </div>

        <div class="form-group" ng-class="{'has-error':frmEmp.txtPwd.$invalid,'has-success':frmEmp.txtPwd.$valid}">
            <label class="control-label col-lg-2">PASSWORD</label>
            <div class="col-lg-6">
                <input type="password" class="form-control" ng-model="EMP.PASSWORD" required name="txtPwd" ng-minlength="6" ng-maxlength="8" />
            </div>
            <div class="help-block has-error">
                <div ng-show="frmEmp.txtPwd.$error.required && frmEmp.txtPwd.$touched">
                    Passwrod should not blank.
                </div>
                <div ng-show="frmEmp.txtPwd.$error.minlength && frmEmp.txtPwd.$touched">
                    Passwrod min length 6.
                </div>
                <div ng-show="frmEmp.txtPwd.$error.maxlength && frmEmp.txtPwd.$touched">
                    Passwrod min length 8.
                </div>
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.ddlgender.$invalid,'has-success':frmEmp.ddlgender.$valid}">
            <label class="control-label col-lg-2">GENDER</label>
            <div class="col-lg-6">
               <select ng-model="EMP.GENDER" class="form-control" required name="ddlgender">
                   <option value="">Select</option>
                   <option value="Male">Male</option>
                   <option value="Female">Female</option>
               </select>
            </div>
            <div class="help-block has-error" ng-show="frmEmp.ddlgender.$invalid && frmEmp.ddlgender.$touched">
                Please select a gender.
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.ddlcid.$invalid,'has-success':frmEmp.ddlcid.$valid}">
            <label class="control-label col-lg-2">COUNTRY</label>
            <div class="col-lg-6">
                <select ng-model="EMP.CID" class="form-control" required name="ddlcid" ng-options="c.CID as c.CNAME for c in listc" ng-change="fillddl()">
                    <option value="">Select</option>
                </select>
            </div>
            <div class="help-block has-error" ng-show="frmEmp.ddlcid.$invalid && frmEmp.ddlcid.$touched">
                Please select a country.
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.ddlsid.$invalid,'has-success':frmEmp.ddlsid.$valid}">
            <label class="control-label col-lg-2">STATE</label>
            <div class="col-lg-6">
                <select ng-model="EMP.SID" class="form-control" required name="ddlsid" ng-options="c.SID as c.SNAME for c in lists">
                    <option value="">Select</option>
                </select>
            </div>
            <div class="help-block has-error" ng-show="frmEmp.ddlsid.$invalid && frmEmp.ddlsid.$touched">
                Please select a state.
            </div>
        </div>
        <div class="form-group" ng-class="{'has-error':frmEmp.ddlhid.$invalid,'has-success':frmEmp.ddlhid.$valid}">
            <label class="control-label col-lg-2">HOBBY</label>
            <div class="col-lg-6">
                <select ng-model="EMP.HLIST" multiple class="form-control" required name="ddlhid" ng-options="c.HID as c.HNAME for c in listh">
                  
                </select>
            </div>
            <div class="help-block has-error" ng-show="frmEmp.ddlhid.$invalid && frmEmp.ddlhid.$touched">
                Please select a hobby.
            </div>
        </div>
    </form>

</div>
<div class="modal-footer">
    <div class="form-group">
        <input type="button" class="btn btn-primary" value="Save" ng-click="save()" style="width:80px">
        <input type="button" class="btn btn-primary" value="Cancel" ng-click="cancel()" style="width:80px">
    </div>
</div>


Index page :

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title></title>
    <meta charset="utf-8" />
    <style>
        thead {
            background-color: #3276b1;
            color: #fff;
            border-color: 285e8e;
        }
    </style>
    <link rel="stylesheet" href="Content/bootstrap.min.css" />
    <link rel="stylesheet" href="Content/bootstrap-theme.min.css" />
    <link rel="stylesheet" href="Content/styles.css" />
    <link rel="stylesheet" href="Content/Site.css" />
    <link rel="stylesheet" href="Content/jquery.dataTables.min.css" />
    <link rel="stylesheet" href="Content/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>
    <script type="text/javascript" src="Scripts/ui-bootstrap.js"></script>
    <script type="text/javascript" src="Scripts/ui-bootstrap-tpls.js"></script>
</head>
<body>
    <div class="container" ng-controller="Ctrl">
        <div class="row col-xs-12">
            <input type="button" class="btn btn-primary" value="Add New" ng-click="openPop()" />
            
        </div><br />
        <div class="row col-xs-12" style="border:solid 1px #000000;height:auto;width:auto;">
            <br />
            <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 />
        <div class="row col-xs-12">
            <input type="button" class="btn btn-primary" value="Delete All" ng-click="delAll()" />
        </div>

    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", ["datatables", "ui.bootstrap"])
    .controller("Ctrl", function ($scope, empFactory, $uibModal, $compile, $window, DTOptionsBuilder, DTColumnBuilder) {
        $scope.openPop = function () {
            op(0);
        }
        function op(s)
        {
            $uibModal.open({
                templateUrl: 'AddorEdit.html',
                controller: EmpCtrl,
                size: 'lg',
                resolve: {
                    Id: s
                }

            });

        }
        function fill() {
            $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("NAME", "NAME"),
        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: "http://localhost:9742/api/Empservices/Emps",
                    type: "Get",
                    catch: false
                })
            .withOption('aLengthMenu', [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]])
            .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;
            }

        } fill();
        $scope.edit = function (s)
        {
            op(s);
        }
        $scope.delete = function (s)
        {
            if (confirm('Do you want to delete it ?'))
            {
                empFactory.Delete(s).then(function (promise) {
                    alert( promise.data);
                    $window.location.reload(true);
                });

            }
        }
        $scope.delAll = function ()
        {
            angular.forEach($scope.selected, function (i, j) {
                if (i == true) {
                    $scope.arr.push(j);
                }
            });
            if (confirm('Do you want to delete selected items from the list ?')) {
                empFactory.DeleteAll($scope.arr).then(function (promise) {
                    alert(promise.data);
                    $window.location.reload();
                });
            }
        }
        var EmpCtrl = function ($scope, $uibModalInstance, Id) {
            function CLR() {
                $scope.EMP = {
                    EID: null,
                    NAME: null,
                    ADDRESS: null,
                    GENDER: null,
                    CID: null,
                    SID: null,
                    HLIST: []
                }


            }
            if (Id == 0) {
                CLR();
            }
            else {

                empFactory.Get(Id).then(function (promise) {
                    $scope.EMP = promise.data;
                    fx($scope.EMP.CID);
                });
            }
            $scope.save = function () {
                if (Id == 0) {
                    empFactory.Save($scope.EMP).then(function (promise) {
                        alert(promise.data);
                        CLR();
                        $uibModalInstance.close();
                        $window.location.reload(true);
                    });
                }
                else {
                    empFactory.Update($scope.EMP).then(function (promise) {
                        alert(promise.data);
                        CLR();
                        $uibModalInstance.close();
                        $window.location.reload(true);
                    });
                }


            }
            empFactory.Geth().then(function (promise) {
                $scope.listh = promise.data;
            });

            empFactory.Getc().then(function (promise) {
                $scope.listc = promise.data;
            });
            $scope.fillddl = function () {
                fx($scope.EMP.CID);
            }
            function fx(s) {
                empFactory.Gets(s).then(function (promise) {
                    $scope.lists = promise.data;
                });

            }
            $scope.cancel = function () {
                $uibModalInstance.dismiss();
            }
        }
    })
    .factory("empFactory", function ($http) {
        var fac = {};
        fac.Getc = function () {
            return $http.get("http://localhost:9742/api/Empservices/Countries");
        }
        fac.Gets = function (CID) {
            return $http.get("http://localhost:9742/api/Empservices/States/" + CID);
        }
        fac.Geth = function () {
            return $http.get("http://localhost:9742/api/Empservices/Hobbies");
        }
        fac.Gete = function () {
            return $http.get("http://localhost:9742/api/Empservices/Emps");
        }
        fac.Get = function (EID) {
            return $http.get("http://localhost:9742/api/Empservices/Emp/" + EID);
        }
        fac.Save = function (emp) {
            return $http.post("http://localhost:9742/api/Empservices/Save", emp);
        }
        fac.Update = function (emp) {
            return $http.put("http://localhost:9742/api/Empservices/Update/" + emp.EID, emp);
        }
        fac.Delete = function (EID) {
            return $http.delete("http://localhost:9742/api/Empservices/Delete/" + EID);
        }
        fac.DeleteAll = function (lst) {

            return $http.post("http://localhost:9742/api/Empservices/Alldelete", lst);
        }
        return fac;
    })
</script>



Sunday 11 March 2018

jquery data table with check boxes using MVC



With view model :

@model IEnumerable<WebApplication6.Models.EMP>

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

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<div style="border:solid 1px #000000; margin-top:2px">
    <br />
    <table class="table table-bordered table-condensed table-hover table-responsive table-striped" id="tb">
        <thead>
            <tr>
                <th><input name="select_all" value="0" id="example-select-all" type="checkbox" /></th>

                <th>
                    @Html.DisplayNameFor(model => model.EID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.NAME)
                </th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
                <tr>
                    <td>
                        <input type="checkbox" style="width:15px;height:15px" class="cb" value="@item.EID" name="id[]" />
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.EID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.NAME)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id = item.EID })  |
                        @Html.ActionLink("Delete", "Delete", new { id = item.EID })
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div><br />
<input type="button" value="DeleteAll" id="btndel" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/Site.css" />
<link rel="stylesheet" href="~/Content/jquery.dataTables.css" />
<link rel="stylesheet" href="~/Content/jquery.dataTables_themeroller.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>

<script type="text/javascript">
    $(function () {

          var table = $("#tb").DataTable({
            "order": [[0, "asc"]],
            "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
            "scroller": true,
            "orderClasses": false,
          })
          $('#example-select-all').on('click', function () {
              // Check/uncheck all checkboxes in the table
              var rows = table.rows({ 'search': 'applied' }).nodes();
              $('input[type="checkbox"]', rows).prop('checked', this.checked);
          });
          $('#tb tbody').on('change', 'input[type="checkbox"]', function () {
              // If checkbox is not checked
              if (!this.checked) {
                  var el = $('#example-select-all').get(0);
                  // If "Select all" control is checked and has 'indeterminate' property
                  if (el && el.checked && ('indeterminate' in el)) {
                      // Set visual state of "Select all" control
                      // as 'indeterminate'
                      el.indeterminate = true;
                  }
              }
          });


          var checkIds = [];
          $('#btndel').click(function () {
              table.$('input[type="checkbox"]').each(function () {
                      if (this.checked) {
                          checkIds.push((this.value));
                  }
              });

              alert(checkIds);


          });


    });
</script>

Without view model :



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

<h2>Index</h2>

<div style="border:solid 1px #000000; margin-top:2px">
    <br />
    <table class="table table-bordered table-condensed table-hover table-responsive table-striped" id="example">
        <thead>
            <tr>
                <th><input name="select_all" value="0" id="example-select-all" type="checkbox" /></th>

                <th>
                    EID
                </th>
                <th>
                    NAME
                </th>

            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<input type="button" value="DeleteAll" id="btndel" />
<link rel="stylesheet" href="~/Content/bootstrap.css" />
<link rel="stylesheet" href="~/Content/Site.css" />
<link rel="stylesheet" href="~/Content/jquery.dataTables.css" />
<link rel="stylesheet" href="~/Content/jquery.dataTables_themeroller.css" />
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>

<script type="text/javascript">
    $(function () {
        var table;
        $.ajax({
            "url": "@Url.Action("Gets", "Test")",
            type: 'Get',
            datatype: 'json',
            cache: false,
            success: function (Data) {
                table = $('#example').DataTable({
                    data: Data,
                    "pagingType": "full_numbers",
                    "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
                    columns: [
                       {
                           data: "EID",
                           render: function (data, type, full, meta) {
                               return '<input type="checkbox" name="id[]" value="'
                                  + data + '">';
                           }
                       },
                        { data: "EID" },
                        { data: "NAME" }


                    ],
                    select: {
                        style: 'multi'
                    },
                    order: [[1, 'asc']]

                });
            }

        });


        // Handle click on "Select all" control
        $('#example-select-all').on('click', function () {
            // Check/uncheck all checkboxes in the table
            var rows = table.rows({ 'search': 'applied' }).nodes();
            $('input[type="checkbox"]', rows).prop('checked', this.checked);
        });

        $('#example tbody').on('change', 'input[type="checkbox"]', function () {
            // If checkbox is not checked
            if (!this.checked) {
                var el = $('#example-select-all').get(0);
                // If "Select all" control is checked and has 'indeterminate' property
                if (el && el.checked && ('indeterminate' in el)) {
                    // Set visual state of "Select all" control
                    // as 'indeterminate'
                    el.indeterminate = true;
                }
            }
        });

        var checkIds = [];
        $('#btndel').click(function () {
           
            table.$('input[type="checkbox"]').each(function () {
                if (this.checked) {
                    checkIds.push((this.value));
                }
            });

            alert(checkIds);


        });

    });


</script>