Hi Everyone,
I've been battling with this for days now and no solution yet. Below is my complete code.
This is my Model Class
public class GradeStep : Base.Configurations { public int Id { get; set; } [Required, StringLength(250), Display(Name = "Grade Name")] public string GradeName { get; set; } [Required, StringLength(100), Display(Name = "Step Name"), RegularExpression(RegularExpressionPatternForFields.Pattern, ErrorMessage = "Invalid Step Name. Please remove any special character, leading or trailing spaces, etc.")] public string StepName { get; set; } [NotMapped] [Display(Name = "Grade Code"), RegularExpression(RegularExpressionPatternForFields.Pattern, ErrorMessage = "Invalid Grade Code. Please remove any special character, leading or trailing spaces, etc.")] public string GradeCode { get; set; } [NotMapped, Required, Display(Name = "Grade From"), RegularExpression(RegularExpressionPatternForFields.Pattern, ErrorMessage = "Invalid Grade From Value. Please remove any special character, leading or trailing spaces, etc.")] public string GradeFrom { get; set; } [NotMapped, Display(Name = "Grade To"), RegularExpression(RegularExpressionPatternForFields.Pattern, ErrorMessage = "Invalid Grade To Value. Please remove any special character, leading or trailing spaces, etc.")] public string GradeTo { get; set; } [NotMapped, Required, Display(Name = "No. Of Step"), RegularExpression(RegularExpressionPatternForFields.Pattern, ErrorMessage = "Invalid No. Of Step Value. Please remove any special character, leading or trailing spaces, etc.")] public string NoOfStep { get; set; } [Display(Name = "Paygroup")] public int PaygroupId { get; set; } [ForeignKey("PaygroupId")] public Paygroup Paygroup { get; set; } }
This is my Repository Class
public class GradeStepRep : IGPay<GradeStep> { private readonly GPayContext context; private readonly IGPay<AuditTrail> auditTrail; private readonly AuditTrailRep auditTrailRep; public GradeStepRep(GPayContext _context, IGPay<AuditTrail> _auditTrail, AuditTrailRep _auditTrailRep) { context = _context; auditTrail = _auditTrail; auditTrailRep = _auditTrailRep; } public Task<List<GradeStep>> GetAsync(GradeStep model = null, HttpContext httpContext = null) { try { List<GradeStep> gradeStep = context.GradeStep.Include(pg => pg.Paygroup).Where(gdStep => model.Status.Contains(gdStep.Status)).OrderBy(gdStep => gdStep.Paygroup.PaygroupName) .ThenBy(gdStep => gdStep.GradeName).ThenBy(gdStep => gdStep.StepName).ToList(); return Task.FromResult(gradeStep); } catch (Exception) { throw; } } }
This is my Controller Class
public class GradeStepController : Controller { private readonly IGPay<GradeStep> gradeStep; private readonly IGPay<Paygroup> paygroup; public GradeStepController(IGPay<GradeStep> _gradeStep, IGPay<Paygroup> _paygroup) { gradeStep = _gradeStep; paygroup = _paygroup; } [HttpGet, Route("[Action]"), Authorize(Policy = "GradeStepView")] public IActionResult GradeStep() => View(); [HttpPost, Route("[Action]"), Authorize(Policy = "GradeStepView")] public async Task<IActionResult> GradeStep([FromBody]List<GradeStep> model, Operation operation) { try { if (model.Any(gradeStepChecked => gradeStepChecked.Checked)) { switch (operation) { case Operation.Delete: await gradeStep.DeleteAsync(model, HttpContext); break; case Operation.Authorize: model[0].Status = Status.B.ToString(); await gradeStep.UpdateAsync(model, HttpContext); break; case Operation.Approve: model[0].Status = Status.A.ToString(); await gradeStep.UpdateAsync(model, HttpContext); break; case Operation.Reject: model[0].Status = Status.R.ToString(); await gradeStep.UpdateAsync(model, HttpContext); break; } } else { return BadRequest("Please, Select GradeStep!"); } } catch (Exception ex) { return BadRequest(ex.InnerException != null ? ex.InnerException.Message : ex.Message); } return View(); } private async Task<List<GradeStep>> LoadGradeStep(GradeStep gdStep = null) { try { return await gradeStep.GetAsync(gdStep); } catch (Exception) { throw; } } public async Task<PartialViewResult> GradeStepPartialUnauthorized() { List<GradeStep> gradeStepPartialUnauthorizedList = new List<GradeStep>(); try { gradeStepPartialUnauthorizedList = await LoadGradeStep(new GradeStep { Status = $"'{Status.O.ToString()}','{Status.R.ToString()}'" }); } catch (Exception) { } return PartialView(gradeStepPartialUnauthorizedList); } public async Task<PartialViewResult> GradeStepPartialUnapproved() { List<GradeStep> gradeStepPartialUnapprovedList = new List<GradeStep>(); try { gradeStepPartialUnapprovedList = await LoadGradeStep(new GradeStep { Status = Status.B.ToString() }); } catch (Exception) { } return PartialView(gradeStepPartialUnapprovedList); } public PartialViewResult GradeStepPartialApproved() { return PartialView(); } public async Task<JsonResult> GradeStepJson(string status) { List<GradeStep> gradeStepPartialApprovedList = new List<GradeStep>(); gradeStepPartialApprovedList = await LoadGradeStep(new GradeStep { Status = status }); var draw1 = HttpContext.Request.Form["draw"].FirstOrDefault(); var start = HttpContext.Request.Form["start"].FirstOrDefault(); var length = HttpContext.Request.Form["length"].FirstOrDefault(); var searchValue = HttpContext.Request.Form["search[value]"].FirstOrDefault(); int pageSize = length != null ? Convert.ToInt32(length) : 0; int skip = start != null ? Convert.ToInt32(start) : 0; int recordsTotal1 = gradeStepPartialApprovedList.Count(); if (!string.IsNullOrWhiteSpace(searchValue)) { gradeStepPartialApprovedList = gradeStepPartialApprovedList.Where(gd => gd.Paygroup.PaygroupName.ToLower().Contains(searchValue.ToLower()) || gd.GradeName.ToLower().Contains(searchValue.ToLower()) || gd.StepName.ToLower().Contains(searchValue.ToLower())).ToList(); } int filterTotal = gradeStepPartialApprovedList.Count(); var data1 = gradeStepPartialApprovedList.Skip(skip).Take(pageSize).ToList(); return Json(new { draw = draw1, recordsTotal = recordsTotal1, recordsFiltered = filterTotal, data = data1 }); } }
This is my View
@{ ViewData["Title"] = "GradeStep"; } @section Header{ @ViewData["Title"] }<div id="divGradeStepUnAuthorized" class="form-group"> @{ await Html.RenderPartialAsync("GradeStepPartialUnauthorized"); }</div><div id="divGradeStepUnApproved" class="form-group"> @{ await Html.RenderPartialAsync("GradeStepPartialUnapproved"); }</div><div id="divGradeStepApproved" class="form-group"> @{ await Html.RenderPartialAsync("GradeStepPartialApproved"); }</div> @section scripts{ <script type="text/javascript"> function GetToken() { var token = '@Html.AntiForgeryToken()'; token = $(token).val(); return token; } function Delete(formId, btnId, tableId) { if ($(formId).valid()) { ClearValidationSummary(); if (confirm("Do you want to delete GradeStep(s)")) { var btn = $(btnId); var btnContent = $(btnId).html(); var table = $(tableId).DataTable();$.ajax({"method": "post","contentType": "application/json","headers": { "RequestVerificationToken": GetToken() },"data": JSON.stringify(table.rows().data().toArray()),"url": "@Url.Action("GradeStep", "GradeStep", new { operation = Operation.Delete })","beforeSend": function (jqXHR, settings) { ButtonShowLoadingText(btn); } }).done(function (data, textStatus, jqXHR) { SuccessAlert("GradeStep(s) deleted successfully."); LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()"); }).fail(function (jqXHR, textStatus, errorThrown) { ErrorAlert(jqXHR.responseText); }).always(function (jqXHR, textStatus) { ButtonOffLoadingText(btn, btnContent); }); } } } function Authorize(formId, btnId, tableId) { if ($(formId).valid()) { ClearValidationSummary(); var btn = $(btnId); var btnContent = $(btnId).html(); var table = $(tableId).DataTable();$.ajax({"method": "post","contentType": "application/json","headers": { "RequestVerificationToken": GetToken() },"data": JSON.stringify(table.rows().data().toArray()),"url": "@Url.Action("GradeStep", "GradeStep", new { operation = Operation.Authorize })","beforeSend": function (jqXHR, settings) { ButtonShowLoadingText(btn); } }).done(function (data, textStatus, jqXHR) { SuccessAlert("GradeStep(s) authorized successfully."); @*LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()");*@$("#divGradeStepUnAuthorized").load('@(Url.Action("GradeStepPartialUnauthorized", "GradeStep"))'); }).fail(function (jqXHR, textStatus, errorThrown) { ErrorAlert(jqXHR.responseText); }).always(function (jqXHR, textStatus) { ButtonOffLoadingText(btn, btnContent); }); } } function Approve(formId, btnId, tableId) { if ($(formId).valid()) { ClearValidationSummary(); var btn = $(btnId); var btnContent = $(btnId).html(); var divContent = $("#divGradeStepUnApproved").html(); var table = $(tableId).DataTable();$.ajax({"method": "post","contentType": "application/json","headers": { "RequestVerificationToken": GetToken() },"data": JSON.stringify(table.rows().data().toArray()),"url": "@Url.Action("GradeStep", "GradeStep", new { operation = Operation.Approve })","beforeSend": function (jqXHR, settings) { ButtonShowLoadingText(btn); } }).done(function (data, textStatus, jqXHR) { SuccessAlert("GradeStep(s) approved successfully."); LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()"); }).fail(function (jqXHR, textStatus, errorThrown) { ErrorAlert(jqXHR.responseText); }).always(function (jqXHR, textStatus) { ButtonOffLoadingText(btn, btnContent); }); } } function Reject(formId, btnId, tableId) { if ($(formId).valid()) { ClearValidationSummary(); var btn = $(btnId); var btnContent = $(btnId).html(); var table = $(tableId).DataTable();$.ajax({"method": "post","contentType": "application/json","headers": { "RequestVerificationToken": GetToken() },"data": JSON.stringify(table.rows().data().toArray()),"url": "@Url.Action("GradeStep", "GradeStep", new { operation = Operation.Reject })","beforeSend": function (jqXHR, settings) { ButtonShowLoadingText(btn); } }).done(function (data, textStatus, jqXHR) { InfoAlert("GradeStep(s) rejected successfully."); LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()"); }).fail(function (jqXHR, textStatus, errorThrown) { ErrorAlert(jqXHR.responseText); }).always(function (jqXHR, textStatus) { ButtonOffLoadingText(btn, btnContent); }); } } function LoadDataTable(tableId, tableSearch, status) { var jTableFilter = @Configuration.GetSection("GPayCustomSettings").GetValue(typeof(string), "JTableFilter"); var dataTableGradeStep = $(tableId).DataTable({"ordering": false,"destroy": true,"pagingType": "full_numbers","lengthMenu": jTableFilter,"processing": true,"serverSide": true,"ajax": {"url": "@Url.Action("GradeStepJson", "GradeStep")/?status=" + status,"type": "post","dataType": "json","headers": { "RequestVerificationToken": GetToken() } },"columns": [ {"data": "checked", "name": "checked", "searchable": false, "render": function (data, type, row) { return '<input type="checkbox" />'; } }, { "data": "paygroup.paygroupName", "name": "paygroup.paygroupName", "searchable": true }, { "data": "gradeName", "name": "gradeName", "searchable": true }, { "data": "stepName", "name": "stepName", "searchable": true }, { "data": "remarks", "name": "remarks", "searchable": false }, {"data": "status", "name": "status", "searchable": false, "render": function (data, type, row) { switch (data.toUpperCase()) { case "O": return "Authorization Pending"; case "R": return "Rejected"; case "B": return "Approval Pending"; case "A": return "Approved"; default: return "Undefined"; } } }, {"data": "id", "name": "id", "searchable": false, "render": function (data, type, row) { return '@if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepUpdate.ToString())) { <a href="@Url.Action("GradeStepAddEdit", "GradeStep")/' + data + '" class="btn btn-outline-success btn-sm"><span class="fa fa-edit"></span>Edit</a> }'; } } ] });$(tableSearch).bind("keyup search input paste cut", function () { dataTableGradeStep.search($(this).val()).draw(); }); }$(document).ready(function () { LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()"); DataCheckBoxes("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedCheckAll"); DataCheckBoxes("#gradeStepUnApprovedTable", "#gradeStepUnApprovedCheckAll"); DataCheckBoxes("#gradeStepApprovedTable", "#gradeStepApprovedCheckAll"); DataTablesCheckBoxModel("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedCheckAll"); DataTablesCheckBoxModel("#gradeStepUnApprovedTable", "#gradeStepUnApprovedCheckAll"); DataTablesCheckBoxModel("#gradeStepApprovedTable", "#gradeStepApprovedCheckAll"); }).ajaxComplete(function (event, request, settings) { LoadDataTable("#gradeStepUnAuthorizedTable", "#gradeStepUnAuthorizedSearch", "'@Status.O.ToString()', '@Status.R.ToString()'"); LoadDataTable("#gradeStepUnApprovedTable", "#gradeStepUnApprovedSearch", "@Status.B.ToString()"); LoadDataTable("#gradeStepApprovedTable", "#gradeStepApprovedSearch", "@Status.A.ToString()"); }); </script>
These are my three Partial Views
@model List<GPayData.Models.Configurations.GradeStep> @if (Model?.Count > 0) {<form id="fmUnAthorizedGradeStep" method="post" asp-controller="GradeStep" asp-action="GradeStep"><div asp-validation-summary="All" class="text-danger"></div><div class="card text-center"><div class="card-header text-muted"><p><b>UnAuthorized GradeStep</b></p></div><div class="card-body"><div class="form-group row"><label class="col-sm-2 col-form-label">Search</label><div class="col-sm-4 input-group"><div class="input-group-prepend"><span class="input-group-text fa fa-search"></span></div><input id="gradeStepUnAuthorizedSearch" type="text" class="form-control" placeholder="Search by Paygroup, Grade, Step" /></div></div><div class="form-group"><div class="table-responsive-sm"><table id="gradeStepUnAuthorizedTable" class="table table-striped table-bordered table-sm compact"><thead><tr><th scope="col" class="text-center"><div class="form-check"><input id="gradeStepUnAuthorizedCheckAll" type="checkbox" class="form-check-input" /><label class="form-check-label"></label></div></th><th scope="col" class="text-center"><label>Paygroup</label></th><th scope="col" class="text-center"><label>Grade</label></th><th scope="col" class="text-center"><label>Step</label></th><th scope="col" class="text-center"><label>Remarks</label></th><th scope="col" class="text-center"><label>Status</label></th><th scope="col"></th></tr></thead></table></div></div></div><div class="card-footer"><div class="btn-group-sm"> @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepDelete.ToString())) {<button id="btnGradeStepUnAuthorizeDelete" type="button" class="btn btn-outline-success" data-loading-text="Deleting..." onclick="Delete('#fmUnAthorizedGradeStep', '#btnGradeStepUnAuthorizeDelete', '#gradeStepUnAuthorizedTable');"><span class="fa fa-trash"></span> Delete</button> } @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepAuthorize.ToString())) {<button id="btnGradeStepUnAuthorize" type="button" class="btn btn-outline-success" data-loading-text="Authorizing..." onclick="Authorize('#fmUnAthorizedGradeStep', '#btnGradeStepUnAuthorize', '#gradeStepUnAuthorizedTable');"><span class="fa fa-check-square"></span> Authorize</button> } @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepApprove.ToString())) {<button id="btnGradeStepUnAuthorizeApprove" type="button" class="btn btn-outline-success" data-loading-text="Approving..." onclick="Approve('#fmUnAthorizedGradeStep', '#btnGradeStepUnAuthorizeApprove', '#gradeStepUnAuthorizedTable');"><span class="fa fa-check"></span> Approve</button> } @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepApprove.ToString()) || await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepAuthorize.ToString())) {<button id="btnGradeStepUnAuthorizeReject" type="button" class="btn btn-outline-danger" data-loading-text="Rejecting..." onclick="Reject('#fmUnAthorizedGradeStep', '#btnGradeStepUnAuthorizeReject', '#gradeStepUnAuthorizedTable');"><span class="fa fa-remove"></span> Reject</button> }</div></div></div></form> }
@model List<GPayData.Models.Configurations.GradeStep> @if (Model?.Count > 0) {<form id="fmUnApprovedGradeStep" method="post" asp-controller="GradeStep" asp-action="GradeStep"><div asp-validation-summary="All" class="text-danger"></div><div class="card text-center"><div class="card-header text-muted"><p><b>UnApproved GradeStep</b></p></div><div class="card-body"><div class="form-group row"><label class="col-sm-2 col-form-label">Search</label><div class="col-sm-4 input-group"><div class="input-group-prepend"><span class="input-group-text fa fa-search"></span></div><input id="gradeStepUnApprovedSearch" type="text" class="form-control" placeholder="Search by Paygroup, Grade, Step" /></div></div><div class="form-group"><div class="table-responsive-sm"><table id="gradeStepUnApprovedTable" class="table table-striped table-bordered table-sm compact"><thead><tr><th scope="col" class="text-center"><div class="form-check"><input id="gradeStepUnApprovedCheckAll" type="checkbox" class="form-check-input" /><label class="form-check-label"></label></div></th><th scope="col" class="text-center"><label>Paygroup</label></th><th scope="col" class="text-center"><label>Grade</label></th><th scope="col" class="text-center"><label>Step</label></th><th scope="col" class="text-center"><label>Remarks</label></th><th scope="col" class="text-center"><label>Status</label></th><th scope="col"></th></tr></thead></table></div></div></div><div class="card-footer"><div class="btn-group-sm"> @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepDelete.ToString())) {<button id="btnGradeStepUnApproveDelete" type="button" class="btn btn-outline-success" data-loading-text="Deleting..." onclick="Delete('#fmUnApprovedGradeStep', '#btnGradeStepUnApproveDelete', '#gradeStepUnApprovedTable');"><span class="fa fa-trash"></span> Delete</button> } @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepApprove.ToString())) {<button id="btnGradeStepUnApprove" type="button" class="btn btn-outline-success" data-loading-text="Approving..." onclick="Approve('#fmUnApprovedGradeStep', '#btnGradeStepUnApprove', '#gradeStepUnApprovedTable');"><span class="fa fa-check"></span> Approve</button><button id="btnGradeStepUnApproveReject" type="button" class="btn btn-outline-danger" data-loading-text="Rejecting..." onclick="Reject('#fmUnApprovedGradeStep', '#btnGradeStepUnApproveReject', '#gradeStepUnApprovedTable');"><span class="fa fa-remove"></span> Reject</button> }</div></div></div></form> }
<form id="fmApprovedGradeStep" method="post" asp-controller="GradeStep" asp-action="GradeStep"><div asp-validation-summary="All" class="text-danger"></div><div class="card text-center"><div class="card-header text-muted"><p><b>Approved GradeStep</b></p></div><div class="card-body"><div class="form-group row"><label class="col-sm-2 col-form-label">Search</label><div class="col-sm-4 input-group"><div class="input-group-prepend"><span class="input-group-text fa fa-search"></span></div><input id="gradeStepApprovedSearch" type="text" class="form-control" placeholder="Search by Paygroup, Grade, Step" /></div></div><div class="form-group"><div class="table-responsive-sm"><table id="gradeStepApprovedTable" class="table table-striped table-bordered table-sm compact"><thead><tr><th scope="col" class="text-center"><div class="form-check"><input id="gradeStepApprovedCheckAll" type="checkbox" class="form-check-input" /><label class="form-check-label"></label></div></th><th scope="col" class="text-center"><label>Paygroup</label></th><th scope="col" class="text-center"><label>Grade</label></th><th scope="col" class="text-center"><label>Step</label></th><th scope="col" class="text-center"><label>Remarks</label></th><th scope="col" class="text-center"><label>Status</label></th><th scope="col"></th></tr></thead></table></div></div></div><div class="card-footer"><div class="btn-group-sm"> @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepAdd.ToString())) {<a id="btnGradeStepAdd" asp-controller="GradeStep" asp-action="GradeStepAddEdit" class="btn btn-outline-success"><span class="fa fa-plus"></span> Add</a> } @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepDelete.ToString())) {<button id="btnGradeStepApproveDelete" type="button" class="btn btn-outline-success" data-loading-text="Deleting..." onclick="Delete('#fmApprovedGradeStep', '#btnGradeStepApproveDelete', '#gradeStepApprovedTable');"><span class="fa fa-trash"></span> Delete</button> }</div></div></div></form>
The major issue here is GradeStepJson Action Method get calls Indefinitely/Recursively if i add LoadDataTable function to JQuery AjaxComplete.
Is there a way to make it called once because that's what i used to reload those Partial Views by checking the Model.
Everything works perfectly by using JQuery DataTables without Server Side Processing but I prefer to use the Server Side.
Thanks in advance.