JQuery Datatables Server Side Processing Bug - c#
I am using the latest Nuget Datatables Package.
From the Nuget Package I am using the following two scripts
<link rel="stylesheet" href="/Content/DataTables/css/jquery.dataTables.min.css" type="text/css" />
<script src="/Scripts/DataTables/jquery.dataTables.min.js"></script>
The following is my client table, it contains 28 records in the database and I am trying to display 10 records
Below is my cshtml
<script>
$(document).ready(function () {
$('#clientTable').DataTable({
"order": [[1, "asc"]],
"serverSide": true,
"processing": true,
"paging": true,
"bLengthChange": false,
"iDisplayLength": "10",
"ajax": {
"url": "/Client/GetAll",
"type": "POST",
"dataType": "json"
},
"columns":
[
{
data: "ID", title: "", render: function (o) {
var template = "<div class=\"btn-group\"><button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-toggle=\"dropdown\"> Options <span class=\"caret\"></span></button>"
+ "<ul class=\"dropdown-menu\" role=\"menu\">"
+ "<li style=\"display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ViewInspections)\">"
+ "Edit"
+ "</li>"
+ "<li class=\"divider\"></li>"
+ "<li style=\"display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ManageEmployees)\">"
+ " View Inspections "
+ "</li></ul></div>";
return template;
}
},
{ data: "Name", title: "Company" },
{ data: "CellNumber", title: "Contact Number" }
]
});
});
</script>
<div class="row">
<div class="col-md-12">
<div class="portlet">
<div class="portlet-header">
<h3 class="pull-right">
<a style="display: #InspectionMethods.ValidateDisplayAccessRights(AccessRights.ManageEmployees)" href="#Url.Action("CreateClient")" class="btn btn-success pull-right">New Client</a>
</h3>
</div> <!-- /.portlet-header -->
<div class="portlet-content">
<table id="clientTable" class="table table-striped table-bordered table-hover table-highlight"></table>
</div> <!-- /.portlet-content -->
</div> <!-- /.portlet -->
</div> <!-- /.col -->
</div> <!-- /.row -->
Here is my server side
[HttpPost]
public ActionResult GetAll(JQDTParams model)
{
using (var context = new DatabaseContext())
{
var clients = context.Clients.Where(model).ToList();
var result = new
{
model.sEcho,
model.draw,
recordsFiltered = context.Clients.Count(model), // 28
recordsTotal = context.Clients.Count(), // 28
data = clients // 10 Items in the list
};
return Json(result, JsonRequestBehavior.AllowGet);
}
}
The result I am getting looks like this
EDIT 1:)
Pages now display.
Pressing on Page 1, 2, or 3 it works and displays the correct data.
Now if I go to Page one and Press "Next" I get the result above where the text then says Showing 0,101 to 28 of 28 entries and if I press "Next" again to go to page three it doesn't do anything
Found the problem
It seems that jquery.Datatables handled the "iDisplayLength" as a string instead of an int, simple change
$(document).ready(function () {
$('#clientTable').DataTable({
"order": [[1, "asc"]],
"serverSide": true,
"processing": true,
"paging": true,
"bLengthChange": false,
"iDisplayLength": 10, //Here was the problem
Related
C# MVC ajax call to database with a popup model does not recognize cancel button click
I have a c# application which displays a webgrid populated by a database. When I double click on a grid element, jquery captures the double click, determines the row of the grid, finds the ID column and does an ajax call to pass the ID back to my controller. Ajax is instructed to expect html as the response. When the controller receives the ID from the view, it reads the record from the database with that ID, populates a list with a set of fields, and passes that list as a parameter to a partial view. The partial view returns html to the ajax call. The html includes a form where the database fields are displayed in text boxes so the user can update the data. There is a submit button and a cancel button at the bottom of the form. The is the ajax code: $("body").on("dblclick", "#WebGrid td", function () { var row = $(this).closest("tr"); var FirstName = row.find("td").eq(1).text(); var LastName = row.find("td").eq(2).text(); var ID = row.find("td").eq(0).text(); $.ajax({ url: "/Home/Details", type: "POST", data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" }, dataType: "html", success: function (result) { $('#dialog').html(result); $('#dialog').dialog('open'); }, failure: function (result) { alert("FAILURE " + result.responseText); }, error: function (result) { alert("ERROR " + result.responseText); } }); return false; }); And this is how I define the division that the returned html gets placed into: <div id="dialog" style="display: none"> </div> And this is the function that I have: $(function () { $("#dialog").dialog({ autoOpen: false, modal: true, title: "Update" }); }); When I run the application, and I double click on a grid item and the partial view gets passed back to the ajax call, the dialog division gets displayed correctly with the data from the database. The problem is when I click on the Cancel button nothing happens. And I do not get the 'cancel button clicked' message on the console. I have this code to capture the click of the cancel button: $("#btnCancel").on('click', function (event) { console.log("cancel button clicked"); $('#dialog').hide; toastr.warning("Your update has been cancelled"); clear(); display(); }); Any suggestions? Thank you. edit: Here is the entire code of the initial View where the grid is rendered: #model List<CodingChallengeV4.ViewModels.ContactPassData> #{ ViewBag.Title = "UpdateAllData"; } #{ Layout = null; WebGrid grid = new WebGrid(source: Model, canPage: true, canSort: false); } <!-- jQuery library --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"> </script> <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" /> <!-- Latest compiled JavaScript --> <!-- add thids links for the error message--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" /> <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script> <style type="text/css"> .Grid { border: 1px solid #ccc; border-collapse: collapse; } .Grid th { background-color: #F7F7F7; font-weight: bold; } .Grid th, .Grid td { padding: 5px; width: 150px; border: 1px solid #ccc; } .Grid, .Grid table td { border: 0px solid #ccc; } .Grid th a, .Grid th a:visited { color: #333; } </style> <h2>Update All Contacts</h2> #grid.GetHtml( htmlAttributes: new { #id = "WebGrid", #class = "Grid" }, columns: grid.Columns( grid.Column(header: "", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedID">#item.passedID</div></text>), grid.Column(header: "First Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedfName">#item.passedfName</div></text>), grid.Column(header: "Last Name", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedlName">#item.passedlName</div></text>), grid.Column(header: "eMail Address", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMail">#item.passedeMail</div></text>), grid.Column(header: "eMail Type", format:#<text><div class="edit" data-id="#item.passedID" data-propertyname="passedeMailTypeString">#item.passedeMailTypeString</div></text>) ) ) <div id="dialog" style="display: none;" > </div> <script> $(function () { $("#dialog").dialog({ autoOpen: false, modal: true, title: "View Details" }); }); $(document).ready(function () { $('#toast-container').find('.toast-top-center').removeClass('.toast-top-center'); toastr.options = { "closeButton": true, 'autoWidth': false, "debug": false, "newestOnTop": true, "progressBar": true, "positionClass": "toast-center-center", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "3000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } $("#btnCancel").on('click', function (event) { console.log("cancel button was clicked"); $('#dialog').dialog('hide'); toastr.warning("Your update has been cancelled"); clear(); display(); }); $("body").on("dblclick", "#WebGrid td", function () { var row = $(this).closest("tr"); var FirstName = row.find("td").eq(1).text(); var LastName = row.find("td").eq(2).text(); var ID = row.find("td").eq(0).text(); $.ajax({ url: "/Home/Details", type: "POST", data: { ID: ID, FirstName: "", LastName: "", EmailAddress: "", EmailType: "" }, dataType: "html", success: function (result) { $('#dialog').html(result); $('#dialog').dialog('open'); }, failure: function (result) { alert("FAILURE " + result.responseText); }, error: function (result) { alert("ERROR " + result.responseText); } }); return false; }); }); </script>
kendo grid client template input hidden field become editable once click
I'm trying to make a kendo grid column template like this, based on condition show text input and other way round wrote the following code for this columns.Bound(p => p.MyColumn).Template(#<text></text>).ClientTemplate( "# if (myFirstCondion == true) { #" + "<input type='text' style='width:100%' class='k-textbox' value=#=MyColumn#></input>" + "# } else { #" + "<input type='hidden'></input>" + "# } #" ); but the problem is when I click hidden column, its become input text field, how to make this non editable once click hidden field
You could use the column.Editable handler. e.g. columns.Bound(p => p.MyColumn).Editable("conditionalEditable").Template(#<text></text>).ClientTemplate( "# if (myFirstCondion == true) { #" + "<input type='text' style='width:100%' class='k-textbox' value=#=MyColumn#></input>" + "# } else { #" + "<input type='hidden'></input>" + "# } #" ); ... <script> function conditionalEditable(dataItem){ return dataItem.myFirstCondion; // add the same per item condition as in the client template } </script>
Let me guess: Your grid is editable right? If so, your grid will take control over the cell's content when editing. You need to customize it, like the example below: <!DOCTYPE html> <html> <head> <base href="https://demos.telerik.com/kendo-ui/grid/local-data-binding"> <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style> <title></title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.default-v2.min.css" /> <script src="https://kendo.cdn.telerik.com/2021.2.616/js/jquery.min.js"></script> <script src="https://kendo.cdn.telerik.com/2021.2.616/js/kendo.all.min.js"></script> </head> <body> <script src="../content/shared/js/products.js"></script> <div id="example"> <div id="grid"></div> <script> $(document).ready(function() { $("#grid").kendoGrid({ dataSource: { data: products, schema: { model: { fields: { ProductName: { type: "string" }, UnitPrice: { type: "number" }, UnitsInStock: { type: "number" }, Discontinued: { type: "boolean" }, Test: { type: "string" } } } }, pageSize: 20 }, height: 550, scrollable: true, sortable: true, filterable: true, editable: true, pageable: { input: true, numeric: false }, columns: [ "ProductName", { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" }, { field: "UnitsInStock", title: "Units In Stock", width: "130px" }, { field: "Discontinued", width: "130px" }, { field: "Test", editor: ($td, data) => { if (data.model.Discontinued) { let myColumn = 1; $td.append(`<input type='text' style='width:100%' class='k-textbox' value='${myColumn}'></input>`); } else { $td.append("<input type='hidden'></input>"); } } } ] }); }); </script> </div> </body> </html> Dojo So inside the editor callback, you can create(or not) your own input depending on any condition you need. You also have the model.
Jquery Data Table - No data available in table
I have developed an application using .net core. One of my requirements is datatables. In my controller I am calling a REST Api service and returning a Json result. The view is pretty straight forward in that of my html table and the AJAX call to the controller for data. Upon execution of the application my datatable shows up with 'No data available in table' <table id="datatable"> <thead class="thead-light"> <tr role="row"> <th class="table-column-pr-0 sorting_disabled" rowspan="1" colspan="1" aria-label="" style="width: 44px;"> <div class="custom-control custom-checkbox"> <input id="datatableCheckAll" type="checkbox" class="custom-control-input"> <label class="custom-control-label" for="datatableCheckAll"></label> </div> </th> <th class="table-column-pl-0 sorting" tabindex="0" aria-controls="datatable" rowspan="1" colspan="1" style="width: 299px;">UserID</th> <th class="table-column-pl-0 sorting" tabindex="0" aria-controls="datatable" rowspan="1" colspan="1" style="width: 299px;">UserName</th> <th class="sorting" tabindex="0" aria-controls="datatable" rowspan="1" colspan="1" style="width: 195px;">DepartmentID</th> </tr> </thead> <tbody> </tbody> </table> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js"> </script> <script> $(function () { $.ajax({ type: "POST", url: "/ApplicationUsers/LoadData", data: '{}', contentType: "application/json; charset=utf-8", headers: { 'Access-Control-Allow-Origin': '*' }, dataType: "json", success: function (response) { OnSuccess(response); }, failure: function (response) { alert(response.d); }, error: function (response) { alert(response.d); } }); }); // INITIALIZATION OF DATATABLES // ======================================================= function OnSuccess(response) { console.log(response); $.noConflict(); $('#datatable').DataTable( { dom: 'Bfrtip', bLengthChange: true, lengthMenu: [[5, 10, -1], [5, 10, "All"]], bFilter: true, bSort: true, bPaginate: true, searching: false, data: response, columns: [ { 'data': 'userID', "defaultContent": "", }, { 'data': 'userName', "defaultContent": "", }, { 'data': 'departmentID', "defaultContent": "", }] }); }; </script> public class ApplicationUsersController : Controller { [HttpGet] public ActionResult Users() { return View(); } [HttpPost] public ActionResult LoadData() { var data = ClaimsService.GetUsers(); return Json(new { data = data}); } } JSON DATA {"data":{"result":[{"userID":322,"userName":"Ashnee","departmentID":3,"branchID":1,"name":"Ashnee Pillay ","emailAddress":"Ashnee#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":323,"userName":"BalanC","departmentID":15,"branchID":5,"name":"Balan Chetty ","emailAddress":"BalanC#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":328,"userName":"BrettL","departmentID":1,"branchID":1,"name":"Brett Lange ","emailAddress":"BrettL#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":334,"userName":"CoenieB","departmentID":14,"branchID":4,"name":"Coenie De Beer ","emailAddress":"CoenieB#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":337,"userName":"TraceyA","departmentID":61,"branchID":30,"name":"Tracey De Andrade ","emailAddress":"TraceyA#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":350,"userName":"HenryB","departmentID":18,"branchID":8,"name":"Henry Barber ","emailAddress":"HenryB#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":351,"userName":"HowardG","departmentID":6,"branchID":1,"name":"Howard Gains ","emailAddress":"HowardG#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":354,"userName":"IreneK","departmentID":17,"branchID":7,"name":"Irene Koegelenberg ","emailAddress":"IreneK#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":356,"userName":"JayM","departmentID":2,"branchID":1,"name":"Jay Mahillal ","emailAddress":"JayM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":359,"userName":"TheshniR","departmentID":4,"branchID":1,"name":"Theshni Reddy ","emailAddress":"TheshniR#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":363,"userName":"Mariov","departmentID":15,"branchID":5,"name":"Mario Vincent ","emailAddress":"mariov#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":366,"userName":"Rehana","departmentID":3,"branchID":1,"name":"Rehana Adams ","emailAddress":"Rehana#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":368,"userName":"FrancoisC","departmentID":19,"branchID":9,"name":"Francois Cloete ","emailAddress":"FrancoisC#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":369,"userName":"CharneW","departmentID":22,"branchID":10,"name":"Charne Wagner ","emailAddress":"CharneW#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":372,"userName":"Rajeshree","departmentID":3,"branchID":1,"name":"Rajeshree Singh ","emailAddress":"Rajeshree#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":377,"userName":"SamanthaM","departmentID":2,"branchID":1,"name":"Samantha Murugan ","emailAddress":"SamanthaM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":381,"userName":"SueP","departmentID":2,"branchID":1,"name":"Sue Pillay ","emailAddress":"SueP#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":382,"userName":"Sunitha","departmentID":3,"branchID":1,"name":"Sunitha Kandhai ","emailAddress":"Sunitha#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":385,"userName":"TraceyL","departmentID":20,"branchID":12,"name":"Tracey Lambooy ","emailAddress":"TraceyL#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":387,"userName":"Vinola","departmentID":80,"branchID":30,"name":"Vinola Kalideen ","emailAddress":"Vinola#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":397,"userName":"MarioL","departmentID":5,"branchID":1,"name":"Mario Luis","emailAddress":"MarioL#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":403,"userName":"SteveJ","departmentID":9,"branchID":14,"name":"Steve Jarman","emailAddress":"SteveJ#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":404,"userName":"MarkN","departmentID":18,"branchID":1,"name":"Mark Naicker","emailAddress":"MarkN#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":406,"userName":"MosesQ","departmentID":18,"branchID":8,"name":"MosesQwabe","emailAddress":"MosesQ#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":407,"userName":"Evonn","departmentID":3,"branchID":1,"name":"Evonn Naicker","emailAddress":"Evonn#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":417,"userName":"Brandon","departmentID":18,"branchID":8,"name":"Brandon Booysen","emailAddress":"BrandonBO#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":419,"userName":"SifisoD","departmentID":9,"branchID":14,"name":"Sifiso Dlamini","emailAddress":"SifisoD#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":423,"userName":"Jnb.Workshop","departmentID":9,"branchID":14,"name":"Jnb.Workshop","emailAddress":"Jnb.Workshop#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":425,"userName":"PrenishaS","departmentID":15,"branchID":5,"name":"Prenisha Sami","emailAddress":"Prenishas#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":426,"userName":"Pzb.Operations","departmentID":20,"branchID":12,"name":"Gift Kunene","emailAddress":"Pzb.Operations#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":427,"userName":"SalomeM","departmentID":18,"branchID":8,"name":"Salome Mokwele","emailAddress":"SalomeM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":431,"userName":"GeorgeH","departmentID":12,"branchID":3,"name":"George Horn","emailAddress":"GeorgeH#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":434,"userName":"NadineF","departmentID":22,"branchID":10,"name":"Nadine Feldtmann","emailAddress":"NadineF#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":435,"userName":"ThiroshanN","departmentID":2,"branchID":1,"name":"Thiroshan Naicker","emailAddress":"ThiroshanN#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":442,"userName":"GeneN","departmentID":14,"branchID":4,"name":"Gene Naidoo","emailAddress":"GeneN#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":444,"userName":"Jnb.Boardroom","departmentID":1,"branchID":1,"name":"Jnb.Boardroom","emailAddress":"Jnb.Boardroom#Tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":447,"userName":"Mariob","departmentID":65,"branchID":37,"name":"Mario Botha","emailAddress":"Mariob#tritonfleet.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":449,"userName":"KureshaM","departmentID":3,"branchID":1,"name":"Kuresha Moodley","emailAddress":"KureshaM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":453,"userName":"SeanR","departmentID":3,"branchID":1,"name":"Sean Raidoo","emailAddress":"SeanR#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":459,"userName":"SalonaB","departmentID":3,"branchID":1,"name":"Salona Balram","emailAddress":"SalonaB#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":460,"userName":"JohannesS","departmentID":18,"branchID":8,"name":"Johannes Van Staden","emailAddress":"JohannesS#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":463,"userName":"Dannyg","departmentID":15,"branchID":5,"name":"Danny Govender","emailAddress":"dannyg#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":466,"userName":"Shaneilr","departmentID":5,"branchID":1,"name":"Shaneil","emailAddress":"shaneilr#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":468,"userName":"BlessingM","departmentID":19,"branchID":9,"name":"Blessing Mlimi","emailAddress":"BlessingM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":477,"userName":"EnvorS","departmentID":13,"branchID":2,"name":"Envor Swart","emailAddress":" envors#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":481,"userName":"FritzB","departmentID":59,"branchID":25,"name":"Fritz Beudeker","emailAddress":"FritzB#tritonscs.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":483,"userName":"JuanP","departmentID":6,"branchID":1,"name":"Juan Potgieter","emailAddress":"JuanP#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":484,"userName":"NonhlanhlaMn","departmentID":18,"branchID":8,"name":"Nonhlanhla Mnguni ","emailAddress":"NonhlanhlaM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":488,"userName":"WinnieM","departmentID":18,"branchID":8,"name":"Winnie Mbongo","emailAddress":"WinnieM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":492,"userName":"JaendreS","departmentID":16,"branchID":6,"name":"Jaendre Serfontein","emailAddress":"JaendreS#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":497,"userName":"TshepoM","departmentID":18,"branchID":8,"name":"Tshepo Mbele","emailAddress":"TshepoM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":498,"userName":"ItumelengL","departmentID":18,"branchID":8,"name":"Itumeleng Leso","emailAddress":"ItumelengL#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":499,"userName":"Raynoldn","departmentID":18,"branchID":8,"name":"Raynold Ngwane","emailAddress":"Raynoldn#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":504,"userName":"JarredM","departmentID":58,"branchID":24,"name":"Jarred Metzler","emailAddress":"JarredM#tritonscs.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":511,"userName":"MagdaG","departmentID":6,"branchID":1,"name":"Magda Greeff","emailAddress":"MagdaG#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":513,"userName":"WinstonB","departmentID":55,"branchID":28,"name":"Winston Blaine","emailAddress":"WinstonB#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":517,"userName":"ByronV","departmentID":27,"branchID":17,"name":"Byron Vickers ","emailAddress":"ByronV#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":521,"userName":"GertH","departmentID":61,"branchID":48,"name":"Gert Hael ","emailAddress":"GertH#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":523,"userName":"Nomsat","departmentID":88,"branchID":45,"name":"Nomsa Tshabalala","emailAddress":"NomsaT#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":527,"userName":"AndrewJ","departmentID":18,"branchID":8,"name":"Andrew Julius","emailAddress":"AndrewJ#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":528,"userName":"LeeH","departmentID":4,"branchID":1,"name":"Lee Hamberger","emailAddress":"LeeH#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":530,"userName":"KevinS","departmentID":4,"branchID":1,"name":"Kevin Smith","emailAddress":"KevinS#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":532,"userName":"PhumeleleM","departmentID":63,"branchID":33,"name":"Phumelele","emailAddress":"PhumeleleM#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":533,"userName":"GiftK","departmentID":20,"branchID":12,"name":"Gift Kunene","emailAddress":"Giftk#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":534,"userName":"MiguelF","departmentID":55,"branchID":28,"name":"Miguel","emailAddress":"MiguelF#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":535,"userName":"BilkisA","departmentID":2,"branchID":1,"name":"Bilkis Ahmod","emailAddress":"bilkisa#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":539,"userName":"HermanK","departmentID":24,"branchID":15,"name":"Herman Kleynhans","emailAddress":"HermanK#tritonexpress.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":543,"userName":"SomP","departmentID":58,"branchID":24,"name":"Som Pillay","emailAddress":"SomP#tritonscs.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"},{"userID":544,"userName":"AndriesG","departmentID":73,"branchID":42,"name":"Andries Greyling","emailAddress":"AndriesG#tritonscs.co.za","archive_User":"0","managerID":0,"isHeadOffice":0,"statusID":1,"statusDate":"0001-01-01T00:00:00"}],"id":1601,"exception":null,"status":5,"isCanceled":false,"isCompleted":true,"isCompletedSuccessfully":true,"creationOptions":0,"asyncState":null,"isFaulted":false}}
Your JSON data has the following overall structure: { "data": { "result": [ {...}, {...}, {...}, ... {...} ], "id": 1601, "exception": null, ... "isFaulted": false } } The "result": [ ] array is where you see the data needed to populate the table. Each {...} object in that array represents one row of table data. Therefore you have to point DataTables at that array, so it knows where, inside your JSON, to look for the data it will display. DataTables will automtically handle iteration over each item in that array. This is why you needed to change this: data: response, to this: data: response.data.result, in your DataTable definition. Here, response is the name of the variable containing the overall response JSON. And data.result is the specific location inside that JSON where your table data is stored.
Select2 field not rendering inside partial view
On a main page for example the Edit.cshtml I have this code here which renders a select 2 with the country flags and it works fine, but when I attempt to move it into a partial view it does not work. My Html Field which is inside PleasureCraftEditViewPartial.cshtml <div class="form-group"> #Html.DisplayNameFor(model => model.MooringCountry) <select asp-for="MooringCountry" class="form-control select2" style="height:35px" id="MooringCountry" name="MooringCountry"> <option>Please select Mooring Country</option> </select> <span asp-validation-for="MooringCountry" class="text-danger"></span> </div> The above is in my PleasureCraftEditViewPartial.cshtml #if (#Model.VesselCat == (int)VesselCat.VesselCatType.Commercial) { #await Html.PartialAsync("ComercialEditViewPartial") } #if (#Model.VesselCat == (int)VesselCat.VesselCatType.MotorBoats || #Model.VesselCat == (int)VesselCat.VesselCatType.SailingBoats || #Model.VesselCat == (int)VesselCat.VesselCatType.SmallBoats) { #await Html.PartialAsync("PleasureCraftEditViewPartial") } The below is in my Edit.cshtml <script> $(function () { //Initialize Select2 Elements $('.select2').select2(); var isoCountries = [ { id: 1, flag: 'gbp', text: 'United Kingdom' }, { id: 2, flag: 'usa', text: 'United States' } ]; function formatCountry(country) { if (!country.id) { return country.text; } var $country = $('<span class="flag-icon flag-icon-' + country.flag + ' flag-icon-squared"></span>' + '<span class="flag-text">' + country.text + "</span>"); return $country; }; //Assuming you have a select element with name country // e.g. <select name="name"></select> $("[id='Flag']").select2({ placeholder: "Please Select a Flag", templateResult: formatCountry, data: isoCountries }); $("[id='MooringCountry']").select2({ placeholder: "Please Select a Mooring Country", templateResult: formatCountry, data: isoCountries }); $('#Flag').trigger('change'); }); </script> There are no errors in my console Just an empty dropdown
How to use AJAX on ASP.NET MVC RazorPage
I am trying to create a cascading DropDownList on ASP.NET RazorPage. After doing some research I found the most common way to do the task is utilizing jQuery in my View. Nearly all demos and examples I found online implement a cascading DropDownList in previous ASP.NET versions, more specifically MVC. I tried translating these examples in the context of how I need them but I am having no luck, most likely due to syntax errors and/or other reasons. I am using ASP.NET Core 2.2 I am having trouble specifically implementing the dynamic function call (GetSubCategory) whenever an item is selected in the first DropDownList which is displaying correctly <form asp-controller="my_dropdown" asp-action="CreatePortfolio" method="post" class="form-horizontal" role="form"> <div class="form-group"> <div class="row"> <div class="alert-danger" asp-validation-summary="ModelOnly"></div> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-4"> <label for="CategoryName">Category</label> #Html.DropDownList("categorylist", new SelectList((System.Collections.IEnumerable)ViewData["categorylist"], "CategoryId", "CategoryName"), "Select Category", "CategoryName") <label for="SubCategoryName">Subcategory</label> #section scripts{ <script type="text/javascript"> //Insert default item "Select" in dropdownlist on load $(document).ready(function () { var items = "<option value='0'>Select</option>"; $("#colorselect").html(items); }); </script> <script type="text/javascript"> $(document).ready(function () { $("#CategoryId").on("change", function () { $list = $("#SubCategory"); $.ajax({ type: "GET", url: '/CreatePortfolio', data: { id: $("#CategoryId").val() }, traditional: true, success: function (response) { $list.empty(); $.each(result, function (i, item) { $list.append('<option value="' + item["SubCategoryId"] + '"> ' + item["SubCategoryName"] + '</option>'); }); }, error: function () { alert("Something went wrong"); // Hide loader icon }, }); }) }) </script> } </div> </div> </div> Code behind the view public JsonResult GetSubCategory(int CategoryId) { subcategorylist = _context.GetAllSubCategories(CategoryId); //ViewData["subcategorylist"] = subcategorylist; return new JsonResult(subcategorylist); } public void OnGet() { // ----- Getting Data From Database Using Stored Procedure ----- categorylist = _context.GetAllCategoires(); // ----- Assigning categorylist to ViewData["categorylist"] in order to access it in the view ----- ViewData["categorylist"] = categorylist; } I want the code to correctly display the SubCategories associated to the Category by CategoryId which is a field in both classes/tables