jsGrid preload pages ahead - jsgrid

I want to load items by page since I have tables with large amount of data, but I don't want to load items for each page once the user clicks it.
Instead, I rather preload 1000 items (for example) ahead and only fetch more results if the user moves to a page I still didn't fetch the data for.
Is it possible?

I found a way to solve it.
Here is the basic logic:
Create a local data cache object that will hold arrays of results for each page.
When fetching data from the server, always return data for a few pages ahead and store them in the local cache object
Write a method for the controller.loadData that will check to see if you have the desired page results in the local cache object, if so - return that array, if not - return a promise that will fetch the results with some extra data for a few pages ahead.
An example of the local cache object snapshot:
{
"1": [{name: "ff"}, {name: "fdd"}],
"2": [{name: "fds"}, {name: "dsr"}],
"3": [{name: "drr"}, {name: "ssr"}]
}

script section
<script type="text/javascript">
$(document).ready(function () {
List();
});
function List() {
//$(function () {
loadjsgrid();
$("#jsGrid").jsGrid({
height: "auto",
width: "100%",
filtering: true,
editing: false,
sorting: true,
autoload: true,
paging: true,
pageSize: 10,
pageButtonCount: 5,
pageLoading: true,
controller: {
loadData: function (filter) {
var startIndex = (filter.pageIndex - 1) * filter.pageSize;
var d = $.Deferred();
$.ajax({
type: 'GET',
url: '#Url.Action("[ActionName]", "[Controllername]")',
data: filter,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.Message == "Failed") {
data.Result = [];
data.Count = 0;
}
console.log(data);
d.resolve(data);
}
});
return d.promise().then(function (q) {
return {
data: q.Result,
itemsCount: q.Count
}
});
}
},
},
fields: [
{ name: "rct_no", type: "text", title: 'Serial Number', autosearch: true, width: '10%' }
],
});
$("#pager").on("change", function () {
var page = parseInt($(this).val(), 10);
$("#jsGrid").jsGrid("openPage", page);
});
}
Controller section
public ActionResult getList(int pageIndex = 1, int pageSize = 10)
{
try
{
var query = #" from rd_receipt_header
var irList = DAL.db.Fetch<[className]>(pageIndex, pageSize, #"select * " + query );
var count = DAL.db.ExecuteScalar<int>("select count(*) " + query);
return Json(new { Message = "Success", Result = irList, Count = count }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex) { return Json(new { Message = "Failed", Result = ex.Message }, JsonRequestBehavior.AllowGet); }
I am using ajax to get data from server as ajax format

Related

select2 ajax dynamic search multipleselect - set values from respons on document ready

I have problem with passing data to select2 (ajax dynamic search) in edit mode on document ready.
I create test button which should add data on click and it doesnt work... Any ideas with that?
$('.select2').select2({
minimumInputLength: 3,
ajax: {
url: (...),
dataType: 'json',
data: function (params) {
return {
query: params.term
};
},
processResults: function (data, params) {
var resData = [];
data.forEach(function (value) {
if (value.name.toLowerCase().indexOf(params.term.toLowerCase()) != -1)
resData.push(value)
})
return {
results: $.map(resData, function (item) {
return {
text: item.name,
slug: item.slug,
id: item.id
}
})
};
},
},
});
$('#preselectObjectDataButton').on('click', function() {
var _array = []
var o = new Object;
o.id = 1;
o.text = "test";
o.slug = "test";
_array.push(o);
$('.select2').val(_array).trigger('change.select2');
});

Kendo UI Grid posting back already Inserted Rows again

I am running into problem, where when an Insert is completed successfully and if i continue to insert another row, in the next insert it is also sending the row that was inserted successfully earlier, so it goes like this.
On the First insert that row is posted back to webAPI and inserted successfully.
On Next Insert Two rows are sent one of them was from first step.
On third Insert it send previous two rows as well as third row and so on.
What could be the cause of this ?
This is the Code in problem.
$(document).ready(function () {
try {
var degreeYearsArray = new Array();
function GetDegreeName(dgID, degreeName) {
for (var i = 0; i < degreeYearsArray.length; i++) {
if (degreeYearsArray[i].dgID_PK == dgID) {
return degreeYearsArray[i].Name;
}
}
return degreeName;
}
var degreeYearModel = {
id: "DGYR_PK",
fields: {
DGID_FK: {
type: "number",
nullable: false,
editable: false
},
Code: {
type: "string",
validation: {
required: true,
minlength: 2,
maxlength: 160
}
},
Year: {
type: "number",
validation: {
required: true
}
},
EffectiveDate: {
type: "date",
validation: true
},
TerminationDate: {
type: "date",
validation: true
}
}
};
var baseURL = "http://localhost:3103/api/Degree";
var degreeYearTransport = {
create: {
url: baseURL + "/PostDegreeYears", // "/PutOrgSchool",
type: "POST",
// contentType: "application/json"
dataType: "json"
},
read: {
url: function () {
var newURL = "";
if (window.SelectedDegree == null)
newURL = baseURL + "/GetDegreeYears"
else
newURL = baseURL + "/GetDegreeYears?degreeID=" + window.SelectedDegree.DGID_PK;
return newURL;
},
dataType: "json" // <-- The default was "jsonp"
},
update: {
url: baseURL + "/PutDegreeYears", //"/PostOrgSchool",
type: "PUT",
// contentType: "application/json",
dataType: "json"
},
destroy: {
url: function (employee) {
return baseURL + "/deleteOrg" + employee.Id
},
type: "DELETE",
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
try {
if (operation != "read") {
options.EffectiveDate = moment(options.EffectiveDate).format("MM-DD-YYYY");
options.TerminationDate = moment(options.TerminationDate).format("MM-DD-YYYY")
}
var paramMap = kendo.data.transports.odata.parameterMap(options);
delete paramMap.$format; // <-- remove format parameter.
return paramMap;
} catch (e) {
console.error("Error occure in parameter Map or Degree.js" + e.message);
}
}
}; //transport
var dsDegreeYears = new kendo.data.DataSource({
serverFiltering: true, // <-- Do filtering server-side
serverPaging: true, // <-- Do paging server-side
pageSize: 2,
transport: degreeYearTransport,
requestEnd: function (e) {
try {
if (e.type == "update"){
$.pnotify({
title: 'Update Sucessful',
text: 'Record was Updated Successfully',
type: 'success'
});
}
if (e.type == "create") {
$.pnotify({
title: 'Insert Sucessful',
text: 'Record was Inserted Successfully',
type: 'success'
});
}
} catch (e) {
console.error("error occured in requestEnd of dsDegreeYears datasource in DegreeYears.js" + e.message);
}
},
schema: {
data: function (data) {
return data.Items; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.Count; // <-- The total items count is the data length, there is no .Count to unpack.
},
model: degreeYearModel
}, //schema
error: function (e) {
var dialog = $('<div></div>').css({ height: "350px", overflow: "auto" }).html(e.xhr.responseText).kendoWindow({
height: "300px",
modal: true,
title: "Error",
visible: false,
width: "600px"
});
dialog.data("kendoWindow").center().open();
},
});
$("#" + gridName).kendoGrid({
dataSource: dsDegreeYears,
autoBind: false,
groupable: true,
sortable: true,
selectable: true,
filterable: true,
reorderable: true,
resizable: true,
columnMenu: true,
height: 430,
editable: "inline",
toolbar: ["create"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [ {
field: "DGID_FK",
title: "Degree Name",
width: 140,
template: function (dataItem) {
if (window.SelectedDegree != null) {
dataItem.DGID_FK = window.SelectedDegree.DGID_PK;
return window.SelectedDegree.Name;
}
else
return "";
}
},
{
field: "Code",
title: "Code",
width: 140
},
{
field: "Year",
title: "Year",
width: 140
},
{
field: "Description",
width: 110
},
{
field: "EffectiveDate",
width: 110,
format: "{0:MM/dd/yyyy}"
},
{
field: "TerminationDate",
width: 110,
format: "{0:MM/dd/yyyy}"
},
{
command: ["edit"] , title: " ", width: "172px"
}
]
}); //grid
//Hide history pull-down menu in the top corner
$.pnotify.defaults.history = false;
$.pnotify.defaults.styling = "bootstrap";
// styling: 'bootstrap'
//styling: 'jqueryui'
} catch (e) {
console.error("Error occured in DegreeYears" + e.message);
}
}); // document
This is the Response that is sent from WebAPI
{"$id":"1","DGYR_PK":27,"DGID_FK":64,"Year":4,"Code":"4THYR","EffectiveDate":"2014-01-11T00:00:00","TerminationDate":"2014-01-11T00:00:00","CreatedByUserID_FK":1,"DateCreated":"0001-01-01T00:00:00","UpdatedByUserID_FK":1,"DateUpdated":"0001-01-01T00:00:00","RowStatusID_FK":1,"Degree":null,"DegreeYearExamSchedules":[],"User":null,"RowStatu":null,"User1":null,"DegreeYearSubjects":[]}
So i do see i am returning ID as suggested by the users in response to the question.
still wondering
After you have inserted a record, you need to return the id of that row, otherwise grid consider the previous row as a new row too.
In your create function you call the web API
baseURL + "/PostDegreeYears", // "/PutOrgSchool",
In the server side consider the below code.
public void Create(ABSModel model)
{
try
{
using (context = new Pinc_DBEntities())
{
tblAB tb = new tblAB();
tb.ABS = model.ABS;
tb.AreaFacility = model.AreaFacility;
context.tblABS.Add(tb);
Save();
model.ABSID = tb.ABSID;//this is the important line of code, you are returning the just inserted record's id (primary key) back to the kendo grid after successfully saving the record to the database.
}
}
catch (Exception ex)
{
throw ex;
}
}
please adjust the above example according to your requirement.
This will happen if you don't return the "DGYR_PK" value of the newly inserted model. The data source needs a model instance to have its "id" field set in order not to consider it "new". When you return the "ID" as a response of the "create" operation the data source will work properly.
You can check this example for fully working Web API CRUD: https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-webapi-crud
Here is the relevant code:
public HttpResponseMessage Post(Product product)
{
if (ModelState.IsValid)
{
db.Products.AddObject(product);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.ProductID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Your primary key cannot be 0 or null. If you are using auto-incrementing values then you should invoke the "re-read" of your dataSource after post. Check the values and make sure your data values are >0. Note: I have set the default value of the PK in the model to -1 in the column model to help with this.
You can attached and respond to the requestEnd event on the DataSource.
requestEnd: function(e) {
if (e.type === "create") {
this.read();
}
}
What that is saying is: "After you created a record, reread the entries (including the newly created one) into the grid". Thereby giving you the newly created entry with key and all. Of course you see that the extra read may have some performance issue.

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

jqGrid Setting id of new added Row intoGrid

jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" }, //form editor
reloadAfterSubmit: true
// afterSubmit: function (response, postdata) {
// return [true, "", $.parseJSON(response.responseText).d];
//}
});
$.extend($.jgrid.defaults, {
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json", type: "POST" },
//row inline editing
serializeGridData: function(postData) { return JSON.stringify(postData); },
jsonReader: {
repeatitems: false,
id: "0",
cell: "",
root: function(obj) { return obj.d.rows; },
page: function(obj) { return obj.d.page; },
total: function(obj) { return obj.d.total; },
records: function(obj) { return obj.d.records; }
}
});
$("#grantlist").jqGrid({
url: 'webservice.asmx/GetGrant',
colNames: ['ID', 'Name', 'Title'],
colModel: [
{ name: 'ID', width: 60, sortable: false },
{ name: 'name', width: 210, editable: true },
{ name: 'title', width: 210, editable: true }
],
serializeRowData: function(data) {
var params = new Object();
params.ID = 0;
params.name = data.name;
params.title = data.title;
return JSON.stringify({ 'passformvalue': params, 'oper': data.oper, 'id': data.id });
},
mtype: "POST",
sortname: 'ID',
rowNum: 4,
height: 80,
pager: '#pager',
editurl: "webservice.asmx/ModifyGrant"
});
$("#grantlist").jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, refresh: false, search: false });
$("#grantlist").jqGrid('inlineNav', '#pager');
//this is my server code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JQGrid<GrantComittee> GetGrantComittee(int? page, int? rows, string sidx, string sord, bool _search)
{
JQGrid<GrantComittee> jqgrid = new JQGrid<GrantComittee>();
List<GrantComittee> data = GetGComittee();
jqgrid.records = data.Count; //total row count
jqgrid.total = (int)Math.Ceiling((double)data.Count / (double)rows); //number of pages
jqgrid.page = page.Value;
//paging
data = data.Skip(page.Value * rows.Value - rows.Value).Take(rows.Value).ToList();
foreach(GrantComittee i in data)
jqgrid.rows.Add(i);
return jqgrid;
}
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int ModifyGrantComittee(GrantComittee passformvalue, string oper, string id)
{
if (String.Compare(id, "_empty", StringComparison.Ordinal) == 0 ||
String.Compare(oper, "add", StringComparison.Ordinal) == 0)
{
GrantComittee data = new GrantComittee();
List<GrantComittee> set = new List<GrantComittee>();
set = (List<GrantComittee>)Session["grantcomittee"];
data = passformvalue;
data.ID = set.Max(p => p.ID) + 1;
set.Add(data);
Session["grantcomittee"] = set;
return data.ID;
}
else if (String.Compare(oper, "edit", StringComparison.Ordinal) == 0)
{
// TODO: modify the data identified by the id
return 0;
}
else if (String.Compare(oper, "del", StringComparison.Ordinal) == 0)
{
// TODO: delete the data identified by the id
return 0;
}
return 0;
}
I am using JqGrid to retrieve and add new records to database. So far i have been able to retrieve and add new items to the DB, I am using "json". I do get in the response {"d": "5"} for the id of the newly created row in the DB. However the new id does not display in the grid.
How can I update that value to new added row?
In the most cases you don't need to do anything because of default setting reloadAfterSubmit: true. It means that the full grid will be reloaded from the server after the user add new row or modify an existing one.
If you want use reloadAfterSubmit: false setting and the server returns the id of the new created row in the response you need implement afterSubmit callback function which will decode the server response and return it for the usage of by jqGrid. The corresponding code could be about the following:
afterSubmit: function (response, postdata) {
return [true, "", $.parseJSON(response.responseText).d];
}
You can define the callback by overwriting the default parameters $.jgrid.edit (see here and here).
I am using 'inlinNav' and after adding a new row i was not getting the grid to reload. The solution I found was to add parametes to the 'inlineNav' declaration. So I end up with the code i am providing as reference:
$("#grantlist").jqGrid('inlineNav', '#pager', { addParams: { position: "last", addRowParams: {
"keys": true, "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); }
}
}, editParams: { "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); } }
});
function reloadgrid(grid) {
grid.trigger("reloadGrid");
}
I was using more than one grid that is why i pass a grid parameter to the reload function.

JqGrid not able to fill itself from Json response

So I have a javascript function that runs on page load, listed below:
function createGrid()
{
var myGrid =
jQuery("#responseMessages"),
reportBtn = "<input style='height:22px;width:100px;' type='button' value='Report' />",
getColumnIndexByName = function(grid,columnName) {
var cm = grid.jqGrid('getGridParam','colModel');
for (var i=0,l=cm.length; i<l; i++) {
if (cm[i].name===columnName) {
return i; // return the index
}
}
return -1;
};
myGrid.jqGrid({
url: "<%= Url.Action("GetMessages", "Home") %>",
datatype: 'json',
myType: 'GET',
height: 'auto',
colModel: [
{ name:'distance', index:'distance', label:'Distance', width:100 },
{ name:'age', index:'age', label:'Age', width:75 },
{ name:'message', index:'message', label:'Message', width:500 },
{ name:'messageId', index:'messageId', key:true, hidden:true },
{ name:'report', index:'report', label: 'Report', width:100,
formatter:function() { return reportBtn; } }
],
loadComplete: function() {
var i=getColumnIndexByName(myGrid,'report');
// nth-child need 1-based index so we use (i+1) below
$("tbody > tr.jqgrow > td:nth-child("+(i+1)+") > input",myGrid[0]).click(function(e) {
var tr=$(e.target,myGrid[0].rows).closest("tr.jqgrow");
var x=window.confirm("Are you sure you want to report this message?")
if (x)
{
reportMessage(tr[0].id);
}
e.preventDefault();
});
},
rowNum:25,
viewrecords:true,
rowList:[10,25,50],
pager: '#pager',
caption: "What's going on in your area!"
});
}
Now it loads the grid fine, actually makes a call to the public ActionResult GetMessages() on the server correctly, and doesn't receive any data from the response, so it doesn't fill the grid and says there are no records. Yay!
Problem is, I click a button on the page, which triggers this javascript method:
function reloadGrid()
{
$("#responseMessages").trigger("reloadGrid");
}
So the grid goes and re-gets the server method, yay! But this time, the server sends a response back that looks like this from firebug:
{"ContentEncoding":null,"ContentType":null,"Data":{"page":1,"records":2,"rows":[{"id":3,"cell":["\u003c 1 mile","25 hour(s)","sdfgsdfgsdfg","3"]},{"id":2,"cell":["\u003c 1 mile","25 hour(s)","adfg","2"]}],"total":1},"JsonRequestBehavior":1}
However, the grid doesn't fill and still says there are no records, when there should be 3.
You use not standard format of JSON data, so you should include the corresponding jsonReader parameter in the jqGrid which describe how jqGrid should get the data from the JSON input:
jsonReader: {
page: "Data.page",
total: "Data.total",
records: "Data.records",
root: "Data.rows"
}
How you can read from the demo the data will be read after the change.

Resources