Trying to load datatable with few records initially and once datatable loaded, trying to click pagination buttons, here trying like if we click on pagination button need to reload the API with latest with updated params and load set of records instead of all records at a time. Developed below code for pagination for huge data,
loadTable() {
this.dtOptions = {
processing: true,
destroy: true,
pagingType: 'full_numbers',
pageLength: 10,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
params = new HttpParams()
.set('param1', '111')
.set('param2', '222')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
}
};
this.http
.get<any[]>(
'https://angular-datatables-demo-server.herokuapp.com/',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
Stackblitz
Related
I am using angular-datatable ( http://l-lin.github.io/angular-datatables/#/basic/server-side-angular-way) .
Instead on assigning to this.dtOptions in ngOnInit, I want to do it in the response of another api, but the ajax call is not going through.
My code :-
ngOnInit(){
this.firstCall();
}
firstCall(){
this.api.serviceMethod().subscribe((data : model1) => {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: data.pageLength,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
that.http
.post<DataTablesResponse>(
'api.com/api',
dataTablesParameters, data.req_body, {}
).subscribe(resp => {
that.persons = resp.data;
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [{ data: 'id' }, { data: 'firstName' }, { data: 'lastName' }]
};
})
}
When I am putting the dtOptions assignment in ngOnInit, it is getting called, what am I missing here.
Thank you in advance.
You must set a check in super tag (like : tbody or table when you loop in tr tag).
component.html
<table *ngIf="!loading" ...>
...
...
component.ts
loading = true;
... .subscribe(resp => {
that.persons = resp.data;
loading = false;
Trying to implement pagination, Initially I'm trying to load datatable with few records, once page loaded trying to click pagination buttons like next or any pagination buttons to update the new set of records. I'm able to get the iStart, iEnd records but unable to update the url for every pagination click. Trying to print the console but function is not calling and console.log is not updated with new params. Could you please suggest me how to do the update the params for API. Here is the sample code,
Sample Demo datatatble is not work with pagination, for verification printing the console for the updated querystring.
ngOnInit(): void {
this.dtOptions = {
processing: true,
destroy: true,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
// this.loadTable();
}
};
}
loadTable(){
let params = new HttpParams()
.set('param1', '123')
.set('param2', '456')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
this.http
.get<any[]>(
'https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
HTML code:
<button (click)="loadTable()">Load Table</button>
Sample Demo Stackblitz
If I understand your question correctly, you wanted to apply server-side pagination right?
Here is an official documentation for this.
Add ajax method in dtOptions.
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('Params', dataTablesParameters);
//If you have different key for page number/size change it
dataTablesParameters.minNumber = dataTablesParameters.start + 1;
dataTablesParameters.maxNumber =
dataTablesParameters.start + dataTablesParameters.length; this.http
.post<any[]>(
'YOUR_API_NAME_HERE',
dataTablesParameters,
{}
)
.subscribe(resp => {
this.persons = resp.data;
//Once API fetched data successfully inform datatable by invoking the callback
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [{ data: 'id' }, { data: 'firstName' }, { data: 'lastName' }]
};
Working Stackbliz Demo
The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.
Hi I am using webgrid this time.and Binding json data using JQuery. My ajax call script providing data but I am unable to get it some how.I have gone thorugh all the questions available here but nothing worked. Look at the components and tell me what is wrong.
This is the web grid
<div id="GridContent">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 15, selectionFieldName: "Id", ajaxUpdateContainerId: "GridContent", canSort: true);
}
#grid.GetHtml(
tableStyle: "webgrid-table",
rowStyle: "webgrid-row-style",
htmlAttributes:"grid",
emptyRowCellValue: "--",
headerStyle: "webgrid-header",
selectedRowStyle: "webgrid-alternating-row",
columns: grid.Columns(
grid.Column(columnName: "CenterId", header: "Id"),
grid.Column(columnName: "CenterName", header: "CenterName"),
grid.Column(columnName: "CenterCode", header: "CenterCode"),
grid.Column(columnName: "Address", header: "Address"),
grid.Column(columnName: "EmailId", header: "EmailId"),
grid.Column(format: #<a id="EditCenter" class="fa-anchor" data-id="#item.CenterId">Edit</a>),
grid.Column(format: (item) => Html.ActionLink((string)"Delete", "DeleteCenter", new { CenterId = item.CenterId }, new { id = "DeleteCenter", onclick = "return confirm('Are You Sure Want To Delete The Center Data?');" }))))
</div>
and here is my ajax call for binding the data on dropdown change.
$(document).ready(function () {
$("#ListType").change(function () {
var webgrid;
$.ajax({
type: 'POST',
url: ListTypeUrl,
data: { id: $("#ListType").val() },
datatype:'html',
success: function (result) {
$("#GridContent").html(result);
alert("Success");
},
error: function (result) {
alert("On select Failed " + result);
}
});
})
});
Here is Controller method for getting JSON Results
public JsonResult GetCenterList(int id)
{
List<CenterDetails> cd = objDal.GetCenterListItem(id.ToString(), Session["AgentId"].ToString());
return Json(cd,JsonRequestBehavior.AllowGet);
}
public List<CenterDetails> GetCenterListItem(string type, string AgentId)
{
XElement xl = new XElement("root"
, new XAttribute("OType", "Select")
, new XAttribute("Target", "CenterList")
, new XElement("Type",Convert.ToInt32(type))
, new XElement("AgentId", AgentId));
ds = ExecuteDataSet("Sp_CenterAction", CommandType.StoredProcedure, new MySqlParameter("#xml", xl.ToString()));
dt = ds.Tables[0];
drc = dt.Rows;
List<CenterDetails> objList = new List<CenterDetails>();
foreach (DataRow dr in drc)
{
objList.Add(new CenterDetails
{
CenterId = Convert.ToInt32(dr["cm_Id"].ToString()),
CenterName = dr["cm_Name"].ToString(),
CenterCode = dr["cm_CenterCode"].ToString(),
Address = dr["cm_Address"].ToString(),
EmailId = dr["cm_EmailId"].ToString()
});
}
return objList;
}
I have a modal that I want to display pre-selected rows in. However, I keep getting a 'cannot read 'grid' of undefined' error. The UI Grids are defined within the modal, and I declare two Grid Apis with two different names. Here is my code:
This launches the modal:
//edit user group
$scope.editSelectedGroup = function(){
//get the selected row
var row = $scope.gridApiInfo.selection.getSelectedRows();
var modalInstance = $modal.open({
animation: true,
templateUrl: 'userGroupModal.html',
controller: 'UserGroupModalController',
resolve: {
modalTitle: function () {
return "Edit User Group"
},
allDepartments: function () {
return $scope.allDepartments;
},
allRegions: function() {
return $scope.allRegions;
},
isEdit: function(){
return true;
},
row: function(){
return row[0];
}
}
});
This is the modal controller:
.controller('UserGroupModalController',function($scope,$modalInstance,$modal,$window,modalTitle,allDepartments,allRegions,isEdit,row,referenceDataService){
$scope.modalTitle = modalTitle;
$scope.isEdit = isEdit;
$scope.allDepartments= allDepartments;
$scope.allRegions = allRegions;
$scope.form= {
value: "",
description: "",
departments: [],
regions: []
};
$scope.departmentsGrid = {
enableRowSelection: true,
multiSelect: true,
enableRowHeaderSelection: false,
onRegisterApi: function(gridApi) {
$scope.deptGridApi= gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
],
data: $scope.allDepartments
};
$scope.regionsGrid = {
enableRowSelection: true,
multiSelect: true,
enableRowHeaderSelection: false,
onRegisterApi: function(gridApi) {
$scope.gridApiRegions = gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
],
data: $scope.allRegions
};
if ($scope.isEdit){
$scope.form.value = row.value;
$scope.form.description = row.description;
//pushing selected depts
angular.forEach(row.departments, function(department) {
var deptElementPos=angular.findIndexOf($scope.allDepartments, department.id);
$scope.form.departments.push($scope.allDepartments[deptElementPos]);
});
//pushing selected regions
angular.forEach(row.regions, function(region) {
var regionElementPos=angular.findIndexOf($scope.allRegions, region.id);
$scope.form.regions.push($scope.allRegions[regionElementPos]);
});
//setting pre-selected rows
angular.forEach($scope.form.departments, function(department) {
$scope.deptGridApi.grid.rows.map(function (row) {
if (row.entity.id == department.id) {
row.setSelected(true);
$log.log("row selected: " + row.entity.id);
}
});
});
angular.forEach($scope.form.regions, function(region) {
$scope.gridApiRegions.grid.rows.map(function (row) {
if (row.entity.id == region.id) {
row.setSelected(true);
$log.log("row selected region: " + row.entity.id);
}
});
});
$scope.form.id = row.id;
}
$scope.close = function () {
$modalInstance.dismiss();
};
})
When I click the button to launch the modal, no modal shows up - instead I get a console error saying that it 'Cannot read property 'grid' of undefined' at the line with $scope.deptGridApi.grid.rows.map. Anyone have any suggestions for how to fix this? Thanks in advance!
EDIT: Getting selected rows using deptGridApi and gridApiRegions work - I wrote a test function activated by clicking a button in the modal, shown below:
$scope.getDeptandRegions= function(form){
$log.log($scope.gridApiRegions.selection.getSelectedRows());
$log.log($scope.deptGridApi.selection.getSelectedRows())
};
These log the selected rows fine, even though this also uses the grid APIs. Is it this is only fired after I press a button?
Cannot read property 'grid' of undefined' at the line with $scope.deptGridApi.grid.rows.map
means that :
$scope.deptGridApi === undefined
Looking at your code it is because onRegisterApi is either
Never called
Called with "undefined" as paramener
If you can provide a working code snippet I may be able to help you better