Friday, 1 July 2022

MVC Jquery Table sorting,paging,filtering

 UI

===================================================================


@model MITS.ViewModels.StaffViewModel


<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="~/lib/jquery/dist/jquery.min.js"></script>

@*<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>*@


@*<script src="~/lib/jquery/dist/jquery.min.js"></script>

    <script src="~/js/minutes.js"></script>*@

@*<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>*@


@*@using (Html.BeginForm(null, null, null, new { name = "frm", id = "frm" }))

    {*@

@*<form id="frm">*@

    <div class="container-fluid">

        @Html.AntiForgeryToken()

        @Html.HiddenFor(x => x.StaffId, new { id = "hdnMinuteID" })


        @Html.HiddenFor(x => x.Role, new { id = "hdnReviewPrevMinComments" })

        @Html.HiddenFor(x => x.County, new { id = "hdnPartners" })

        @Html.HiddenFor(x => x.Level, new { id = "hdnServiceComplaints" })

        @Html.HiddenFor(x => x.Region, new { id = "hdnWorkplaceSafety" })

        @Html.HiddenFor(x => x.Team, new { id = "hdnEmployeeRecognition" })



        @Html.ValidationSummary(false, "", new { @class = "text-danger" })

        <div class="col-md-12 no-margin">

            <div class="panel panel-info">


                <div class="panel-heading">

                    <h3 id="dvMachinesRegistrationHeader" class="panel-title labelh3" title="Minutes Entry">Staff Entry</h3>

                </div>

                <div class="panel-body">

                    <div class="dvMachinesRegistrationInfoPanel">

                        <div class="form-group row" id="dvDescription">

                            <Label class="control-label col-sm-2 text-left" for="FacilityNo">First Name:</Label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", @title = "First Name" } })

                            </div>

                            <label class="control-label col-sm-2" for="cntName">Last Name:</label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @title = "Last Name" } })

                            </div>

                        </div>

                        <div class="form-group row" id="dvtxtLocation">



                            <label class="control-label col-sm-2" for="cntPhNo">Role :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(model => model.Role, Model.RoleOptions, "Select", new { @class = "form-control", @title = "Role" })

                            </div>

                        </div>


                        <div class="form-group row">

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Cqi Level :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Level, Model.LevelOptions, "Select", new { @class = "form-control" })

                            </div>

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Region :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Region, Model.RegionOptions, "Select", new { @class = "form-control" })

                            </div>


                        </div>


                        <div class="form-group row">

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">County :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.County, Model.CountyOptions, "Select", new { @class = "form-control" })

                            </div>

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Team :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Team, Model.TeamOptions, "Select", new { @class = "form-control" })

                            </div>


                        </div>


                        <div class="form-group row  col-md-12" clientidmode="Static">

                            @Html.LabelFor(e => e.Scribe, new { htmlAttributes = new { @class = "control-label col-sm-2 text-left" } })

                            <div class="col-md-3">

                                @Html.RadioButtonFor(e => e.Scribe, true, new { id = "Scribe-true" })

                                @Html.Label("Scribe-true", "Yes")


                                @Html.RadioButtonFor(e => e.Scribe, false, new { id = "Scribe-false" })

                                @Html.Label("Scribe-false", "No")

                            </div>

                        </div>


                        <div class="form-group row  col-md-12" clientidmode="Static">

                            @Html.LabelFor(e => e.CQISpecialist, new { htmlAttributes = new { @class = "control-label col-sm-2 text-left" } })

                            <div class="col-md-3">

                                @Html.RadioButtonFor(e => e.CQISpecialist, true, new { id = "CQISpecialist-true" })

                                @Html.Label("Scribe-true", "Yes")


                                @Html.RadioButtonFor(e => e.CQISpecialist, false, new { id = "CQISpecialist-false" })

                                @Html.Label("CQISpecialist-false", "No")

                            </div>

                        </div>






                        <div class="panel-body">

                            <div class="col-md-2">

                                <button id="btnSearch" type="submit" class="btn btn-success btn-block" title="Search" data-loading-text="Searching...">Search</button>

                                

                            </div>

                            <div class="col-md-2">

                                

                                <a class="btn btn-primary btn-sm" href="@Url.Action("Index", "Staff")">Return to Home</a>

                            </div>

                        </div>

                        <div class="panel-body">

                            <div id="ResultsGrid" class="dvIssues">

                                <div class="table-responsive" style="width:100%;">

                                    <table id="dtIssues" cellpadding="0" cellspacing="0" class="details custom-webgrid2-table">

                                        <thead>

                                        </thead>

                                        <tbody>

                                        </tbody>

                                    </table>

                                </div>

                            </div>


                        </div>

                    </div>

                </div>



            </div>

        </div>

    </div>


    <div class="panel-body">

    </div>


    <div id="showmodalSuccess" class="modal" tabindex="-1" role="dialog">

        <div class="modal-dialog" role="document">


        </div>

    </div>


    <div id="loader"></div>


    <div id="cover-spin"></div>


@*</form>*@

@*}*@



<script type="text/javascript">




           $("input").keypress(function (event) {

        if (event.which == 13) {

            event.preventDefault();

            $("#btnSearch").click();

        }

    });

    var oTable;

    $(document).ready(function () {

        $.noConflict();

        bindDatatable();

    });

    function bindDatatable() {

        oTable = $('#dtIssues').DataTable(

             {

                 "drawCallback": function () {

                     $('.paginate_button').each(function () {

                         var text = $(this).text(),

                             title = isNaN(text) ? 'Search Page ' + text + ' Page' : 'Search Page ' + text;

                         $(this).attr('title', title);

                     });

                 },

                 "oLanguage": {

                     "sLengthMenu": 'Display <select title="Display records per page">' +

                         '<option value="10">10</option>' +

                         '<option value="25">25</option>' +

                         '</select> records',

                     "oAria": {

                         "sSortAscending": " - click/return to sort ascending",

                         "sSortDescending": " - click/return to sort descending"

                     }

                 },

                 "bStateSave": false,

                 "searching": true,

                 "bServerSide": true,

                 "sAjaxSource": "@Url.Action("SearchResults", "Staff")",


                 "bProcessing": true,

                "language": {

                    "emptyTable": "No record found.",

                    "processing":

                        '<i class="fa fa-spinner fa-spin fa-3x fa-fw" style="color:#2a2b2b;"></i><span class="sr-only">Loading...</span> '

                },


                 "order": [ 1, "desc"],


                "columnDefs": [

                {

                    "title": "",

                    "targets": [0],

                    "width": "0%",

                    "mRender": function (data,type,full)

                    {

                        debugger;

                         return '<a href='+'@Url.Action("Edit", "Staff")/' + full[1] +

                          '>View/Update</a>'

                    }

                    },

                    {

                        "title": "Staff Id",

                        "targets": [1],

                        "width": "0%",

                    },

                {

                    "title": "First Name",

                    "targets": [2],

                    "width": "0%",

                },

                {

                    "title": "Last Name",

                    "width": "1%",

                    "targets": [3]

                    },

                    {

                        "title": "Role",

                        "width": "4%",

                        "targets": [4]

                    },


                {

                    "title": "Level",

                    "width": "25%",

                    "targets": [5]



                },

                {

                    "title" : "Region",

                    "width": "10%",

                    "targets": [6],

                    "type": "date "


                 },

                 {

                     "title": "County",

                     "width": "4%",

                     "targets": [7]

                 },

                 {

                     "title": "Team",

                     "width": "4%",

                     "targets": [8]

                    }

]

        });

        $("#btnSearch").on("click", function () {

            oTable.search($("#FirstName").val() + ','

                + $("#LastName").val() + ','

                + $("#Role Option:selected").text() + ','

                + $("#CqiLevel Option:selected").text() + ','

                + $("#Region Option:selected").text() + ','

                + $("#County Option:selected").text() + ','

                + $("#Team Option:selected").text()+','+""+','+"").draw();

     });

    }

</script>



Entry screen:

===============================================================


@model MITS.ViewModels.StaffViewModel


<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">


@*<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>*@


@*<script src="~/lib/jquery/dist/jquery.min.js"></script>

    <script src="~/js/minutes.js"></script>*@

@*<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>*@


@*@using (Html.BeginForm(null, null, null, new { name = "frm", id = "frm" }))

    {*@

<form id="frm">

    <div class="container-fluid">

        @Html.AntiForgeryToken()

        @Html.HiddenFor(x => x.StaffId, new { id = "hdnStaffId" })


        @Html.HiddenFor(x => x.Role, new { id = "hdnReviewPrevMinComments" })

        @Html.HiddenFor(x => x.County, new { id = "hdnPartners" })

        @Html.HiddenFor(x => x.Level, new { id = "hdnServiceComplaints" })

        @Html.HiddenFor(x => x.Region, new { id = "hdnWorkplaceSafety" })

        @Html.HiddenFor(x => x.Team, new { id = "hdnEmployeeRecognition" })



        @Html.ValidationSummary(false, "", new { @class = "text-danger" })

        <div class="col-md-12 no-margin">

            <div class="panel panel-info">


                <div class="panel-heading">

                    <h3 id="dvMachinesRegistrationHeader" class="panel-title labelh3" title="Minutes Entry">Staff Entry</h3>

                </div>

                <div class="panel-body">

                    <div class="dvMachinesRegistrationInfoPanel">

                        <div class="form-group row" id="dvDescription">

                            <Label class="control-label col-sm-2 text-left" for="FacilityNo">First Name:</Label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", @title = "First Name" } })

                            </div>

                            <label class="control-label col-sm-2" for="location">Middle Name :</label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { @class = "form-control", @title = "Middle Name" } })

                            </div>

                        </div>

                        <div class="form-group row" id="dvtxtLocation">


                            <label class="control-label col-sm-2" for="cntName">Last Name:</label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @title = "Last Name" } })

                            </div>

                            <label class="control-label col-sm-2" for="cntPhNo">Role :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(model => model.Role, Model.RoleOptions, "Select", new { @class = "form-control", @title = "Role" })

                            </div>

                        </div>



                        <div class="form-group row col-md-12" clientidmode="Static">

                            @Html.LabelFor(e => e.GetNotifications, new { htmlAttributes = new { @class = "control-label col-sm-2 text-left" } })

                            <div class="col-md-3">

                                @Html.RadioButtonFor(e => e.GetNotifications, true, new { id = "GetNotifications-true" })

                                @Html.Label("GetNotifications-true", "Yes")


                                @Html.RadioButtonFor(e => e.GetNotifications, false, new { id = "GetNotifications-false" })

                                @Html.Label("GetNotifications-false", "No")

                            </div>

                        </div>

                        <div class="form-group row col-md-12" clientidmode="Static">

                            @Html.LabelFor(e => e.Scribe, new { htmlAttributes = new { @class = "control-label col-sm-2 text-left" } })

                            <div class="col-md-3">

                                @Html.RadioButtonFor(e => e.Scribe, true, new { id = "Scribe-true" })

                                @Html.Label("Scribe-true", "Yes")


                                @Html.RadioButtonFor(e => e.Scribe, false, new { id = "Scribe-false" })

                                @Html.Label("Scribe-false", "No")

                            </div>

                        </div>


                        <div class="form-group row" clientidmode="Static">

                            @Html.LabelFor(e => e.CQISpecialist, new { htmlAttributes = new { @class = "control-label col-sm-2 text-left" } })

                            <div class="col-md-3">

                                @Html.RadioButtonFor(e => e.CQISpecialist, true, new { id = "CQISpecialist-true" })

                                @Html.Label("Scribe-true", "Yes")


                                @Html.RadioButtonFor(e => e.CQISpecialist, false, new { id = "CQISpecialist-false" })

                                @Html.Label("CQISpecialist-false", "No")

                            </div>

                        </div>


                        <div class="form-group row" id="dvddlScribe">

                            <label for="scribe" class="control-label col-sm-2 text-left">Email:</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(model => model.Email, Model.EmailOptions, "Select", new { @class = "form-control", @title = "Email" })

                            </div>

                            <label for="scribe" class="control-label col-sm-2 text-left">Staff login:</label>

                            <div class="col-md-3">

                                @Html.EditorFor(model => model.Stafflogin, new { htmlAttributes = new { @class = "form-control", @title = "Stafflogin" } })

                            </div>


                        </div>


                        <div class="form-group row">

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Cqi Level :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Level, Model.LevelOptions, "Select", new { @class = "form-control" })

                            </div>

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Region :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Region, Model.RegionOptions, "Select", new { @class = "form-control" })

                            </div>


                        </div>


                        <div class="form-group row">

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">County :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.County, Model.CountyOptions, "Select", new { @class = "form-control" })

                            </div>

                            <label for="AttendeeId" class="control-label col-sm-2 text-left">Team :</label>

                            <div class="col-md-3">

                                @Html.DropDownListFor(x => x.Team, Model.TeamOptions, "Select", new { @class = "form-control" })

                            </div>


                        </div>


                        <div class="form-group row" id="dvTopic">

                            <div class="col-xs-12">

                                @if (!string.IsNullOrEmpty(Model.FirstName))

                                {



                                    <button id="btnUpdate" type="button" class="btn btn-primary" title="Update" data-loading-text="Updating...">Save</button>

                                }

                                else

                                {

                                    <button id="btnSaveStaff" type="button" class="btn btn-primary" title="Save" data-loading-text="Saving...">Save</button>

                                }

                                <a class="btn btn-primary btn-sm" href="@Url.Action("Search", "Staff")">Return to Search</a>

                            </div>


                        </div>

                    </div>

                </div>

                <div id="showmodal" class="modal" tabindex="-1" role="dialog">

                    <div class="modal-dialog" role="document">


                    </div>

                </div>



            </div>

        </div>

    </div>


    <div class="panel-body">

    </div>


    <div id="showmodalSuccess" class="modal" tabindex="-1" role="dialog">

        <div class="modal-dialog" role="document">


        </div>

    </div>


    <div id="loader"></div>


    <div id="cover-spin"></div>


</form>

@*}*@



<script type="text/javascript">




    function myFunction() {

        myVar = setTimeout(showPage, 3000);

    }


    function showPage() {

        document.getElementById("loader").style.display = "none";

        document.getElementById("myDiv").style.display = "block";

    }



    $("#btnSaveStaff").click(function (e) {

        debugger;

        e.preventDefault();

        var vm = {};

        vm.FirstName = $("#FirstName").val();

        vm.LastName = $("#LastName").val();

        vm.CQISpecialist = $("#CQISpecialist-true").val();

        vm.Scribe = $("#Scribe-true").val();

        vm.County = $("#County  option:selected").text();;

        vm.Email = $("#Email  option:selected").text();;

        vm.GetNotifications = $("#GetNotifications-true").val();

        vm.Level = $("#Level  option:selected").text();;

        vm.Login = $("#Stafflogin").val();

        vm.Region = $("#Region  option:selected").text();;

        vm.Role = $("#Role  option:selected").text();;

        vm.Team = $("#Team  option:selected").text();;


        $.ajax({

            url: "/Staff/Save",

            type: "POST",

            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',

            data: vm,

            success: function (data) {

                $('#cover-spin').hide()

                $("#loader").show();

                $("#showmodalSuccess .modal-dialog").html(data);

                $("#showmodalSuccess").modal("show");

            }

        });

    });


    $("#btnUpdate").click(function (e) {

        debugger;

        e.preventDefault();

        var vm = {};

        vm.StaffId = $("#hdnStaffId").val();

        vm.FirstName = $("#FirstName").val();

        vm.LastName = $("#LastName").val();

        vm.CQISpecialist = $("#CQISpecialist-true").val();

        vm.Scribe = $("#Scribe-true").val();

        vm.County = $("#County  option:selected").text();;

        vm.Email = $("#Email  option:selected").text();;

        vm.GetNotifications = $("#GetNotifications-true").val();

        vm.Level = $("#Level  option:selected").text();;

        vm.Login = $("#Stafflogin").val();

        vm.Region = $("#Region  option:selected").text();;

        vm.Role = $("#Role  option:selected").text();;

        vm.Team = $("#Team  option:selected").text();;


        $.ajax({

            url: "/Staff/Update",

            type: "POST",

            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',

            data: vm,

            success: function (data) {

                $('#cover-spin').hide()

                $("#loader").show();

                $("#showmodalSuccess .modal-dialog").html(data);

                $("#showmodalSuccess").modal("show");

            }

        });

    });


    $(document).ready(function () {


    });

</script>


Controller

================================================================



using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Rendering;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using MITS.Business;

using MITS.Models;

using MITS.ViewModels;

using MITS.WebUI;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;


namespace MITS.Controllers

{

    public class StaffController : Controller

    {

        // GET: MinutesController

        private readonly ILogger logger;

        private readonly AppSettingsOptions options;


        private readonly IEnumerable<Level> role;

        private readonly IEnumerable<Level> levels;

        private readonly IEnumerable<Region> regions;

        private readonly IEnumerable<Team> teams;

        private readonly IEnumerable<Team> emails;


        private readonly IEnumerable<County> counties;

        private readonly IEnumerable<Staff> staff;

        public StaffController(ILogger logger

            , IOptions<AppSettingsOptions> options)

        {

            this.logger = logger;

            this.options = options.Value;


            role = HTTPClientWrapper<Level>.GetAll($"{options.Value.BaseUrl}Level").Result;

            levels = HTTPClientWrapper<Level>.GetAll($"{options.Value.BaseUrl}Level").Result;

            regions = HTTPClientWrapper<Region>.GetAll($"{options.Value.BaseUrl}Region").Result;

            counties = HTTPClientWrapper<County>.GetAll($"{options.Value.BaseUrl}County").Result;

            teams = HTTPClientWrapper<Team>.GetAll($"{options.Value.BaseUrl}Team").Result;

            emails = HTTPClientWrapper<Team>.GetAll($"{options.Value.BaseUrl}Team").Result;


            staff = HTTPClientWrapper<Staff>.GetAll($"{options.Value.BaseUrl}Staff").Result;

        }

        public ActionResult Index()

        {

            var model = new StaffViewModel();

            model.RoleOptions = role.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.Description

            });


            model.LevelOptions = levels.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.Description

            });


            model.RegionOptions = regions.Select(x => new SelectListItem()

            {

                Value = x.ID.ToString(),

                Text = x.Name

            });


            model.CountyOptions = counties.Select(x => new SelectListItem()

            {

                Value = x.ID.ToString(),

                Text = x.CountyName

            });


            model.TeamOptions = teams.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.TeamDescription

            });


            model.EmailOptions = emails.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.TeamDescription

            });


            return View("Entry", model);

        }



        // GET: MinutesController/Create

        public async Task<IActionResult> Search()

        {

            var model = new StaffViewModel();

            model.RoleOptions = role.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.Description

            });


            model.LevelOptions = levels.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.Description

            });


            model.RegionOptions = regions.Select(x => new SelectListItem()

            {

                Value = x.ID.ToString(),

                Text = x.Name

            });


            model.CountyOptions = counties.Select(x => new SelectListItem()

            {

                Value = x.ID.ToString(),

                Text = x.CountyName

            });


            model.TeamOptions = teams.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.TeamDescription

            });


            model.EmailOptions = emails.Select(x => new SelectListItem()

            {

                Value = x.Id.ToString(),

                Text = x.TeamDescription

            });



            return View(model);

        }



        [HttpPost]

        public async Task<ActionResult> Save(StaffViewModel vm)

        {

            var model = new MinutesViewModel();

            try

            {

                var staff = new Staff

                {

                    FirstName = vm.FirstName,

                    LastName = vm.LastName,

                    C1Cqispecialists = vm.CQISpecialist.ToLower() == "true" ? "Y" : "N",

                    C1Scribe = vm.Scribe.ToLower() == "true" ? "Y" : "N",

                    County = vm.County,

                    Email = vm.Email,

                    IsNotification = vm.GetNotifications,

                    Level = vm.Level,

                    Login = vm.Role,

                    Region = vm.Region,

                    Role = vm.Role,

                    Team = vm.Team

                };


                var result = await HTTPClientWrapper<Staff>.PostRequest($"{options.BaseUrl}staff", staff);

                if (result != null)

                {

                    model.StatusMessage = result != null ? "Successfully Saved" : "Failed While Saving staff";

                }

                else

                {

                    model.StatusMessage = "Failed While Saving staff";

                }

                return PartialView("_SavedSuccessfullPartial", model);


            }

            catch (Exception ex)

            {

                model.StatusMessage = "Failed While Saving staff";

                return PartialView("_SavedSuccessfullPartial", model);


            }

        }


        // GET: CountyController/Create

        public async Task<ActionResult> SearchResults(JQueryDataTableParams param)

        {

            try

            {

                IEnumerable<Staff> filteredIssues = null;

                IEnumerable<Staff> allIssues = null;

                allIssues = await HTTPClientWrapper<Staff>.GetAll($"{options.BaseUrl}Staff");

                filteredIssues = allIssues.Skip(param.iDisplayStart).Take(param.iDisplayLength);


                if (!string.IsNullOrEmpty(param.sSearch))

                {

                    var firstNameFilter = param.sSearch.Split(',')[0].ToLower();

                    var lastFilter = param.sSearch.Split(',')[1].ToLower();

                    var roleFilter = param.sSearch.Split(',')[2].ToLower();

                    var levelFilter = param.sSearch.Split(',')[3].ToLower();

                    var regionFilter = param.sSearch.Split(',')[4].ToLower();

                    var CountyFilter = param.sSearch.Split(',')[5].ToLower();

                    var teamFilter = param.sSearch.Split(',')[6].ToLower();

                    var ScribeFilter = param.sSearch.Split(',')[7].ToLower();

                    var CQISpecialistFilter = param.sSearch.Split(',')[8].ToLower();


                    var firstNameFilterSearchable = firstNameFilter.Length > 0;

                    var lastFilterSearchable = lastFilter.Length > 0;

                    var roleFilterSearchable = roleFilter.Length > 0 && !roleFilter.Contains("select");

                    var levelFilterSearchable = levelFilter.Length > 0 && !levelFilter.Contains("select");               

                    var regionFilterSearchable = regionFilter.Length > 0 && !regionFilter.Contains("select");

                    var CountyFilterSearchable = CountyFilter.Length > 0 && !CountyFilter.Contains("select");

                    var teamFilterSearchable = teamFilter.Length > 0 && !teamFilter.Contains("select");

                    var ScribeFilterSearchable = ScribeFilter.Length > 0;

                    var CQISpecialistFilterSearchable = CQISpecialistFilter.Length > 0;


                    var predicate = PredicateBuilder.True<Staff>();

                    if (firstNameFilterSearchable)

                    {

                        string firstName = param.sSearch.Split(',')[0].ToLower();

                        predicate = predicate.And(p => p.FirstName.ToLower() == firstName);

                    }

                    if (lastFilterSearchable)

                    {

                        string lastName = param.sSearch.Split(',')[1].ToLower();

                        predicate = predicate.And(p => p.LastName.ToLower() == lastName);

                    }

                    if (roleFilterSearchable)

                    {

                        string originalLevel = param.sSearch.Split(',')[2].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Role) && p.Role.ToLower().Contains(originalLevel));

                    }

                    if (levelFilterSearchable)

                    {

                        string levelFilterSearchableLevel = param.sSearch.Split(',')[3].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Level) && p.Level.ToLower().Contains(levelFilterSearchableLevel));

                    }

                    if (regionFilterSearchable)

                    {

                        string regionFilterSearchableLevel = param.sSearch.Split(',')[4].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Region) && p.Region.ToLower().Contains(regionFilterSearchableLevel));

                    }

                    if (CountyFilterSearchable)

                    {

                        string CountyFilterSearchableLevel = param.sSearch.Split(',')[5].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.County) && p.County.ToLower().Contains(CountyFilterSearchableLevel));

                    }

                    if (teamFilterSearchable)

                    {

                        string teamFilterSearchableLevel = param.sSearch.Split(',')[6].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Team) && p.Team.ToLower().Contains(teamFilterSearchableLevel));

                    }

                    if (ScribeFilterSearchable)

                    {

                        string ScribeFilterSearchableLevel = param.sSearch.Split(',')[7].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.C1Scribe) && p.C1Scribe.ToLower().Contains(ScribeFilterSearchableLevel));

                    }

                    if (CQISpecialistFilterSearchable)

                    {

                        string CQISpecialistFilterSearchableLevel = param.sSearch.Split(',')[8].ToLower();

                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.C1Cqispecialists) && p.C1Cqispecialists.ToLower().Contains(CQISpecialistFilterSearchableLevel));

                    }


                    filteredIssues = allIssues.AsQueryable().Where(predicate);

                }

                else

                {

                    filteredIssues = allIssues;

                }


                var displayMinutes = filteredIssues.Skip(param.iDisplayStart).Take(param.iDisplayLength);

                var result = from c in displayMinutes

                             select new object[] {"",c.Id, Convert.ToString(c.FirstName), Convert.ToString(c.LastName), Convert.ToString(c.Role), c.Level

                             , c.Region, c.County, c.Team

                               };


                return Json(new

                {

                    sEcho = param.sEcho,

                    iTotalRecords = allIssues.Count(),

                    iTotalDisplayRecords = allIssues.Count(),

                    aaData = result

                });

            }

            catch (Exception ex)

            {

                logger.LogError("Failed while Searching Staff", ex);

                return null;

            }

        }



        // GET: IssuesController/Edit/5

        public async Task<IActionResult> Edit(int id)

        {

            //id = 65245;

            try

            {

                var model = new StaffViewModel();

                model.RoleOptions = role.Select(x => new SelectListItem()

                {

                    Value = x.Id.ToString(),

                    Text = x.Description

                });


                model.LevelOptions = levels.Select(x => new SelectListItem()

                {

                    Value = x.Id.ToString(),

                    Text = x.Description

                });


                model.RegionOptions = regions.Select(x => new SelectListItem()

                {

                    Value = x.ID.ToString(),

                    Text = x.Name

                });


                model.CountyOptions = counties.Select(x => new SelectListItem()

                {

                    Value = x.ID.ToString(),

                    Text = x.CountyName

                });


                model.TeamOptions = teams.Select(x => new SelectListItem()

                {

                    Value = x.Id.ToString(),

                    Text = x.TeamDescription

                });


                model.EmailOptions = emails.Select(x => new SelectListItem()

                {

                    Value = x.Id.ToString(),

                    Text = x.TeamDescription

                });



                var staffDetails = await HTTPClientWrapper<Staff>.Get($"{options.BaseUrl}staff/{id}");

                model.StaffId =Convert.ToString(staffDetails.Id);

                model.FirstName = staffDetails.FirstName;

                model.MiddleName = "";

                model.LastName = staffDetails.LastName;

                model.Role =Convert.ToString(role.FirstOrDefault(r=>r.Description==staffDetails.Role)?.Id);

                model.GetNotifications = staffDetails.IsNotification.ToLower()=="true"?"true":"false";

                model.Scribe = staffDetails.C1Scribe.ToLower() == "true" ? "true" : "false";

                model.CQISpecialist = staffDetails.C1Cqispecialists.ToLower() == "true" ? "true" : "false";

                model.Email = Convert.ToString(emails.FirstOrDefault(r => r.TeamDescription == staffDetails.Email)?.Id);

                model.Stafflogin = staffDetails.Login;

                model.CqiLevel = Convert.ToString(levels.FirstOrDefault(r => r.Description == staffDetails.Level)?.Id);

                model.Region = Convert.ToString(regions.FirstOrDefault(r => r.Name == staffDetails.Region)?.ID);

                model.County = Convert.ToString(counties.FirstOrDefault(r => r.RegionName == staffDetails.County)?.ID);

                model.Team = Convert.ToString(teams.FirstOrDefault(r => r.TeamDescription == staffDetails.Team)?.Id);



                return View("Entry", model);

            }

            catch

            {

                return View();

            }

        }


        [HttpPost]

        public async Task<ActionResult> Update(StaffViewModel vm)

        {

            var model = new MinutesViewModel();

            try

            {

                var staffDetails = await HTTPClientWrapper<Staff>.Get($"{options.BaseUrl}staff/{vm.StaffId}");



                staffDetails.FirstName = vm.FirstName;

                staffDetails.LastName = vm.LastName;

                staffDetails.C1Cqispecialists = vm.CQISpecialist.ToLower() == "true" ? "Y" : "N";

                staffDetails.C1Scribe = vm.Scribe.ToLower()=="true"?"Y":"N";

                staffDetails.County = vm.County;

                staffDetails.Email = vm.Email;

                staffDetails.IsNotification = vm.GetNotifications;

                staffDetails.Level = vm.Level;

                staffDetails.Login = vm.Stafflogin;

                staffDetails.Region = vm.Region;

                staffDetails.Role = vm.Role;

                staffDetails.Team = vm.Team;


                var result = await HTTPClientWrapper<Staff>.PostRequest($"{options.BaseUrl}staff", staffDetails);

                if (result != null)

                {

                    model.StatusMessage = result != null ? "Successfully Saved" : "Failed While Saving staff";

                }

                else

                {

                    model.StatusMessage = "Failed While Saving staff";

                }

                return PartialView("_SavedSuccessfullPartial", model);


            }

            catch (Exception ex)

            {

                model.StatusMessage = "Failed While Saving staff";

                return PartialView("_SavedSuccessfullPartial", model);


            }

        }


        // POST: IssuesController/Edit/5

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Edit(int id, IFormCollection collection)

        {

            try

            {

                return RedirectToAction(nameof(Index));

            }

            catch

            {

                return View();

            }

        }

    }

}


Sorting
=================================================================
public async Task<ActionResult> SearchResults(JQueryDataTableParams param)
        {
            try
            {
                IEnumerable<Minutes> filteredMinutes = null;
               // IEnumerable<Minutes> allMinutes = null;
               // allMinutes = await HTTPClientWrapper<Minutes>.GetAll($"{options.BaseUrl}Minutes");

                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    var minuteIdFilter = param.sSearch.Split(',')[0].ToLower();
                    var descriptionFilter = param.sSearch.Split(',')[1].ToLower();
                    var scribeFilter = param.sSearch.Split(',')[2].ToLower();
                    var facilitatorFilter = param.sSearch.Split(',')[3].ToLower();
                    var meetingDateToFilter = param.sSearch.Split(',')[4].ToLower();
                    var meetingDateFromFilter = param.sSearch.Split(',')[5].ToLower();
                    var teamFilter = param.sSearch.Split(',')[6].ToLower();
                    var countyFilter = param.sSearch.Split(',')[7].ToLower();
                    var regionFilter = param.sSearch.Split(',')[8].ToLower();
                    var levelFilter = param.sSearch.Split(',')[9].ToLower();

                    // The "SELECT" should not come to controller, lets first get the data
                    var isMinuteIdSearchable = minuteIdFilter.Length > 0;
                    var isDescriptionSearchable = descriptionFilter.Length > 0;
                    var isScribeSearchable = scribeFilter.Length > 0 &&  !scribeFilter.Contains("select"); ;
                    var isFacilitatorSearchable = facilitatorFilter.Length > 0 && !facilitatorFilter.Contains("select"); ;
                    var isMeetingDateToSearchable = meetingDateToFilter.Length > 0 ? meetingDateToFilter.ToUpper().Contains("MM/DD/YYYY") ? false : true : false;
                    var isMeetingDateFromSearchable = meetingDateFromFilter.Length > 0 ? meetingDateFromFilter.ToUpper().Contains("MM/DD/YYYY") ? false : true : false;
                    var isTeamSearchable = teamFilter.Length > 0 && !teamFilter.Contains("select");
                    var isCountySearchable = countyFilter.Length > 0 && !countyFilter.Contains("select");
                    var isRegionSearchable = regionFilter.Length > 0 && !regionFilter.Contains("select");
                    var isLevelSearchable = levelFilter.Length > 0 && !levelFilter.Contains("select");

                    var predicate = PredicateBuilder.True<Minutes>();
                    if (isMinuteIdSearchable)
                    {
                        int minuteId = Convert.ToInt32(param.sSearch.Split(',')[0]);
                        predicate = predicate.And(p => p.ID == minuteId);
                    }
                    if (isDescriptionSearchable)
                    {
                        string description = param.sSearch.Split(',')[1].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.MeetingDescription) && p.MeetingDescription.ToLower().Contains(description));
                    }
                    if (isScribeSearchable)
                    {
                        string scribe = param.sSearch.Split(',')[2].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Scribe) && p.Scribe.ToLower().Contains(scribe));
                    }
                    if (isFacilitatorSearchable)
                    {
                        string facilitator = param.sSearch.Split(',')[3].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Facilitator) && p.Facilitator.ToLower().Contains(facilitator));
                    }
                    if (isMeetingDateToSearchable && isMeetingDateFromSearchable)
                    {
                        // string meetingToDate = param.sSearch.Split(',')[4].ToLower();
                        DateTime start = Convert.ToDateTime(param.sSearch.Split(',')[5]);
                        DateTime end = Convert.ToDateTime(param.sSearch.Split(',')[4]);
                        predicate = predicate.And(p => Convert.ToDateTime(p.MeetingDate) >= start && Convert.ToDateTime(p.MeetingDate) <= end);
                        //  predicate = predicate.And(p => !string.IsNullOrEmpty(Convert.ToString(p.MeetingDate)) && Convert.ToString(p.MeetingDate).ToLower().Contains(meetingToDate));
                    }
                    else if (isMeetingDateToSearchable) 
                    {
                        DateTime start = Convert.ToDateTime(param.sSearch.Split(',')[5]);
                        predicate = predicate.And(p => Convert.ToDateTime(p.MeetingDate) >= start);
                    }
                    else if (isMeetingDateFromSearchable)
                    {
                        DateTime end = Convert.ToDateTime(param.sSearch.Split(',')[4]);
                        predicate = predicate.And(p => Convert.ToDateTime(p.MeetingDate) <= end);
                    }
                    if (isTeamSearchable) 
                    {
                        string team = param.sSearch.Split(',')[6].ToLower() ;
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Team) && p.Team.ToLower().Contains(team));
                    }
                    if (isCountySearchable) 
                    {
                        string county = param.sSearch.Split(',')[7].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.County) && p.County.ToLower().Contains(county));
                    }
                    if (isRegionSearchable)
                    {
                        string region = param.sSearch.Split(',')[8].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Region) && p.Region.ToLower().Contains(region));
                    }
                    if (isLevelSearchable) 
                    {
                        string level = param.sSearch.Split(',')[9].ToLower();
                        predicate = predicate.And(p => !string.IsNullOrEmpty(p.Level) && p.Level.ToLower().Contains(level));
                    }

                    filteredMinutes = minutes.AsQueryable().Where(predicate);
                }
                else
                {
                    filteredMinutes = minutes;
                }
                var isMinuteIdSortable = Convert.ToBoolean(Request.Query["bSortable_0"]);
                var isDescriptionSortable = Convert.ToBoolean(Request.Query["bSortable_1"]);
                var isScribeSortable = Convert.ToBoolean(Request.Query["bSortable_2"]);
                var isFacilitatorSortable = Convert.ToBoolean(Request.Query["bSortable_3"]);
                var isMeetingDateToSortable = Convert.ToBoolean(Request.Query["bSortable_4"]);
                var isMeetingDateFromSortable = Convert.ToBoolean(Request.Query["bSortable_5"]);
                var isTeamsSortable = Convert.ToBoolean(Request.Query["bSortable_6"]);
                var isCountySortable = Convert.ToBoolean(Request.Query["bSortable_7"]);
                var isRegionSortable = Convert.ToBoolean(Request.Query["bSortable_8"]);
                var isLevelFromSortable = Convert.ToBoolean(Request.Query["bSortable_9"]);

                var sortColumnIndex = Convert.ToInt32(Request.Query["iSortCol_0"]);
                Func<Minutes, string> orderingFunctionStr = null;
                Func<Minutes, DateTime> orderingFunctionDate = null;
                Func<Minutes, int> orderingFunctionInt = null;

                if (sortColumnIndex == 4 || sortColumnIndex == 5)
                {
                    orderingFunctionDate = (c => sortColumnIndex == 4 && isMeetingDateFromSortable ? Convert.ToDateTime(c.MeetingDate) :
                                             sortColumnIndex == 5 && isMeetingDateToSortable ? Convert.ToDateTime(c.MeetingDate) :
                                     new DateTime());

                }
                else if (sortColumnIndex == 0)
                {
                    orderingFunctionInt = (c => sortColumnIndex == 0 && isMinuteIdSortable ? c.ID :
                                     0);
                }

                else
                {
                    orderingFunctionStr = (c => sortColumnIndex == 1 && isDescriptionSortable ? c.MeetingDescription :
                                                sortColumnIndex == 2 && isScribeSortable ? c.Scribe :
                                                 sortColumnIndex == 3 && isFacilitatorSortable ? c.Facilitator :
                                                  sortColumnIndex == 6 && isTeamsSortable ? c.Team :
                                                  sortColumnIndex == 7 && isCountySortable ? c.County :
                                                  sortColumnIndex == 8 && isRegionSortable ? c.Region :
                                                  sortColumnIndex == 9 && isLevelFromSortable ? c.Level :
                                          "");
                }

                var sortDirection = Request.Query["sSortDir_0"]; // asc or desc

                if (sortDirection == "asc")
                {
                    if (sortColumnIndex == 4 || sortColumnIndex == 5)
                        filteredMinutes = filteredMinutes.OrderBy(orderingFunctionDate);
                    else if (sortColumnIndex == 0)
                        filteredMinutes = filteredMinutes.OrderBy(orderingFunctionInt);
                    else
                        filteredMinutes = filteredMinutes.OrderBy(orderingFunctionStr);

                }
                else
                {
                    if (sortColumnIndex == 4 || sortColumnIndex == 5)
                        filteredMinutes = filteredMinutes.OrderByDescending(orderingFunctionDate);
                    else if (sortColumnIndex == 0)
                        filteredMinutes = filteredMinutes.OrderBy(orderingFunctionInt);
                    else
                        filteredMinutes = filteredMinutes.OrderByDescending(orderingFunctionStr);
                }
                var displayMinutes = filteredMinutes.Skip(param.iDisplayStart).Take(param.iDisplayLength);

                var result = from c in displayMinutes
                             select new object[] { Convert.ToString(c.ID), Convert.ToString(c.ID), Convert.ToString(c.MeetingDate), c.Level
                             , c.Region, c.County, c.Team, c.Facilitator , c.Scribe , c.MeetingDescription 
                               };
                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = minutes.Count(),
                    iTotalDisplayRecords = filteredMinutes.Count(),
                    aaData = result
                });
            }
            catch (Exception ex)
            {
                logger.LogError("Failed while Searching Minutes", ex);
                return null;
            }
        }

No comments:

Post a Comment