Hi Everyone,
I've been on this now for days without solution but with Edward effort, the issue is almost close.
I'm trying to submit data i loaded into JQuery Datatables. Below is my complete code
This is Model Class
publicclassGradeStep:Base.Configurations{publicintId{get;set;}[Required,StringLength(250),Display(Name="Grade Name")]publicstringGradeName{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.")]publicstringStepName{get;set;}[NotMapped][Display(Name="Grade Code"),RegularExpression(RegularExpressionPatternForFields.Pattern,ErrorMessage="Invalid Grade Code. Please remove any special character, leading or trailing spaces, etc.")]publicstringGradeCode{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.")]publicstringGradeFrom{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.")]publicstringGradeTo{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.")]publicstringNoOfStep{get;set;}[Display(Name="Paygroup")]publicintPaygroupId{get;set;}[ForeignKey("PaygroupId")]publicPaygroupPaygroup{get;set;}}
This is my Repository Class
publicclassGradeStepRep:IGPay<GradeStep>{privatereadonlyGPayContext context;privatereadonlyIGPay<AuditTrail> auditTrail;privatereadonlyAuditTrailRep auditTrailRep;publicGradeStepRep(GPayContext _context,IGPay<AuditTrail> _auditTrail,AuditTrailRep _auditTrailRep){ context = _context; auditTrail = _auditTrail; auditTrailRep = _auditTrailRep;}public async TaskDeleteAsync(List<GradeStep> model,HttpContext httpContext =null){try{string gradeStepName =string.Empty;foreach(var deleteModel in model){if(deleteModel.Checked){var gradeStep = await context.GradeStep.FindAsync(deleteModel.Id);if(gradeStep !=null){ context.GradeStep.Remove(gradeStep); gradeStepName +=$"{deleteModel.GradeName}/{deleteModel.StepName},";}}} await context.SaveChangesAsync();AuditTrail audit =newAuditTrail{Module=Module.Configurations,SubModule=SubModule.GradeStep,Operation=Operation.Delete,NewValue=$"(Grade/Step-{gradeStepName})"}; await auditTrail.AddAsync(audit, httpContext);}catch(Exception){throw;}}publicTask<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();returnTask.FromResult(gradeStep);}catch(Exception){throw;}}}
This is my Controller Class
publicclassGradeStepController:Controller{privatereadonlyIGPay<GradeStep> gradeStep;privatereadonlyIGPay<Paygroup> paygroup;publicGradeStepController(IGPay<GradeStep> _gradeStep,IGPay<Paygroup> _paygroup){ gradeStep = _gradeStep; paygroup = _paygroup;}[HttpGet,Route("[Action]"),Authorize(Policy="GradeStepView")]publicIActionResultGradeStep()=>View();[HttpPost,Route("[Action]"),Authorize(Policy="GradeStepView")]public async Task<IActionResult>GradeStep([FromBody]List<GradeStep> model,[FromQuery]Operation operation){try{if(model.Any(gradeStepChecked => gradeStepChecked.Checked)){switch(operation){caseOperation.Delete: await gradeStep.DeleteAsync(model,HttpContext);break;caseOperation.Authorize: model[0].Status=Status.B.ToString(); await gradeStep.UpdateAsync(model,HttpContext);break;caseOperation.Approve: model[0].Status=Status.A.ToString(); await gradeStep.UpdateAsync(model,HttpContext);break;caseOperation.Reject: model[0].Status=Status.R.ToString(); await gradeStep.UpdateAsync(model,HttpContext);break;}}else{returnBadRequest("Please, Select GradeStep!");}}catch(Exception ex){returnBadRequest(ex.InnerException!=null? ex.InnerException.Message: ex.Message);}returnView();}[IgnoreAntiforgeryToken]public async Task<JsonResult>GradeStepJson(){List<GradeStep> gradeStepPartialApprovedList =newList<GradeStep>(); gradeStepPartialApprovedList = await LoadGradeStep(newGradeStep{Status=Status.A.ToString()});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();returnJson(new{ draw = draw1, recordsTotal = recordsTotal1, recordsFiltered = filterTotal, data = data1 });}}
This is my View Page
@{ ViewData["Title"] = "GradeStep"; } @section Header{ @ViewData["Title"] }<div id="divGradeStepApproved"class="form-group"><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">
Approved GradeStep
</div><div class="card-body"><div class="form-group row">class="col-sm-2 col-form-label">Search<div class="col-sm-4 input-group"><div class="input-group-prepend">class="input-group-text fa fa-search"></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">id="gradeStepApprovedTable"class="table table-striped table-bordered table-sm compact">scope="col"class="text-center"><div class="form-check"><input id="gradeStepApprovedCheckAll"type="checkbox"class="form-check-input"/>class="form-check-label"></div>scope="col"class="text-center">Paygroupscope="col"class="text-center">Gradescope="col"class="text-center">Stepscope="col"class="text-center">Remarksscope="col"class="text-center">Statusscope="col"></div></div></div><div class="card-footer"><div class="btn-group-sm"> @if (await Context.IsUserInRoleAsync(User.Identity.Name, Role.GradeStepAdd.ToString())) {id="btnGradeStepAdd"asp-controller="GradeStep"asp-action="GradeStepAddEdit"class="btn btn-outline-success">class="fa fa-plus"> Add } @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');">class="fa fa-trash"> Delete</button> }</div></div></div></form></div><script type="text/javascript"> function gettoken() {
var token = '@Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
functionDelete(formId, btnId){if($(formId).valid()){ClearValidationSummary();if(confirm("Do you want to delete GradeStep(s)")){var btn =$(btnId);var btnContent =$(btnId).html();var table =$('#gradeStepApprovedTable').DataTable() console.log(JSON.stringify(table.rows().data().toArray()));$.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.");}).fail(function(jqXHR, textStatus, errorThrown){ErrorAlert(jqXHR.responseText);}).always(function(jqXHR, textStatus){ButtonOffLoadingText(btn, btnContent);});}}}$(document).ready(function(){var jTableFilter =@Configuration.GetSection("GPayCustomSettings").GetValue(typeof(string),"JTableFilter");var dataTableGradeStepApproved =$("#gradeStepApprovedTable").DataTable({"ordering":false,"destroy":true,"pagingType":"full_numbers","lengthMenu": jTableFilter,"processing":true,"serverSide":true,"ajax":{"url":"@Url.Action("GradeStepJson", "GradeStep")","type":"post","dataType":"json"},"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"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())) { + data +'" class="btn btn-outline-success btn-sm">Edit }';}}]});$("#gradeStepApprovedSearch").bind("keyup search input paste cut",function(){ dataTableGradeStepApproved.search($(this).val()).draw();});});</script>
Initially the data couldn't be loaded into Model but after i applied Edward modified Delete Function and GradeStep Action Method Parameter by including [FromBody] and [FromQuery] Model Binding, the data loaded into Model but there is one major issue to be resolved.
- If you notice, I render checkbox in first column. The issue here is, if i check the checkbox(es), it doesn't reflect in the model as true. How do i resolve this?
Thanks in advance.