I am using select2 dropdown. It's working fine for smaller number of items.
But when the list is huge (more than 40000 items) it really slows down. It's slowest in IE.
Otherwise simple Dropdownlist works very fast, till 1000 records. Are there any workarounds for this situation?
///////////////**** Jquery Code *******///////////////
var CompanypageSize = 10;
function initCompanies() {
var defaultTxtOnInit = 'a';
$("#DefaultCompanyId").select2({
allowClear: true,
ajax: {
url: "/SignUpTemplate/GetCompanies",
dataType: 'json',
delay: 250,
global: false,
data: function (params) {
params.page = params.page || 1;
return {
keyword: params.term ? params.term : defaultTxtOnInit,
pageSize: CompanypageSize,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.result,
pagination: {
more: (params.page * CompanypageSize) < data.Counts
}
};
},
cache: true
},
placeholder: {
id: '0', // the value of the option
text: '--Select Company--'
},
width: '100%',
//minimumInputLength: 3,
});
}
//////////******* Have to initialise in .ready *******///////////////
$(document).ready(function () {
initCompanies();
});
//////////******* C# code :: Controller is : SignUpTemplateController************/////
public JsonResult GetCompanies(string keyword, int? pageSize, int? page)
{
int totalCount = 0;
if (!string.IsNullOrWhiteSpace(keyword))
{
List<Companies> listCompanies = Companies.GetAll(this.CurrentTenant, (keyword ?? string.Empty).Trim(), false, 11, page.Value, pageSize.Value, ref totalCount, null, null, null, null, null).ToList();
var list = listCompanies.Select(x => new { text = x.CompanyName, id = x.CompanyId }).ToList();
return Json(new { result = list, Counts = totalCount }, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
Related
I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.
I have a huge json data source (over 50,000 + lines) loaded in memory from a static file.
Note: It's not important why I have it in a static file.
I use select2 (v 4.0.5) that initializes as:
function initSelect2(selectName, dataSelect) {
var pageSize = 20;
$.fn.select2.amd.require(["select2/data/array", "select2/utils"],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var data = {};
data.results = dataSelect.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < dataSelect.length;
callback(data);
};
$('#mySelect3').select2({
ajax: {},
dataAdapter: CustomData,
width: '100%'
});
});
}
I have one big problem. I can not set the value to select from jQuery. If I try like this:
$ ("#mySelect3").val(17003).trigger("change");
nothing will happen. But I think I'm doing it badly. If I understand the documentation I think I should implement function:
CustomData.prototype.current = function (callback) {}
that should create the data, and then function:
CustomData.prototype.query = function (params, callback) {}
should only filter them.
Can you please help me, how do I implement select2 initialization, that can work with many options and can by set from jQuery?
With custom data adapter you don't need pagination :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
callback(data);
};
return CustomData;
}
);
//
$('#mySelect3').select2({
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
And with search you can do like this :
// create huge array
function mockData() {
var hugeArray = [];
for (let i = 0; i < 50000; i++) {
el = {
id: i,
text: 'My mock data ' + i,
};
hugeArray.push(el);
}
return hugeArray;
};
// define custom dataAdapter
$.fn.select2.amd.define("myCustomDataAdapter",
['select2/data/array','select2/utils'],
function (ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
// here replace mockData() by your array
results: mockData()
};
if ($.trim(params.term) === '') {
callback(data);
} else {
if (typeof data.results === 'undefined') {
return null;
}
var filteredResults = [];
data.results.forEach(function (el) {
if (el.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
filteredResults.push(el);
}
});
if (filteredResults.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.results = filteredResults;
callback(modifiedData);
}
return null;
}
};
return CustomData;
}
);
//
$('#mySelect3').select2({
minimumInputLength: 2,
tags: false,
allowClear: true,
// use dataAdapter here
dataAdapter:$.fn.select2.amd.require("myCustomDataAdapter"),
});
I had the same issue and this is how I solved it.
Note: We are using dataAdapter because we dealing with large that, so I am assuming your drop-down will contain large amount of data.
After implementing your DataAdapter with a query use this example to initialize your select2.
if(selectedValue !== null )
{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
data: [{ id: selectedValue, text: selectedValue }],
dataAdapter: customData
});
$("#item_value").val(selectedValue).trigger('change');
}else{
$("#item_value").select2({
placeholder: 'Select an option',
allowClear: true,
disabled: false,
formatLoadMore: 'Loading more...',
ajax: {},
dataAdapter: customData
});
}
To set selected value in select2 you need to pass some data into data option, but as we are dealing with large amount of data. You can't pass the complete array of large data you have as it's going to cause your browser window to freeze and lead to a bad user performance.
But instead set the data option only with the selected value you got from db or variable.
I hope this helps.
I am trying to implement server side filtering for a Kendo UI grid (client only). I am not sure how to pass the filter operator and value entered on the filter box. I was able to implement server paging and want the filtering to work alongside the server paging, i.e. show page 2 of 5 items of filtered rows. I saw some example of binding the request to "DataSourceRequest" object but we do not have licence for the server side Kendo UI and have to achieve it using the client side changes only.
Here is my jQuery code:
var page = 1;
var pageSize = 5;
var title = "test";
var selectWork = function (e) {
alert("selected");
};
$("#selectWorkGrid").empty();
$("#selectWorkGrid").kendoGrid({
dataSource:
{
transport: {
read: {
url: "http://example.com/" + "work/SearchWorkJ?worktitle=" + title,
dataType: "json",
contentType: "application/json",
data: {
page: page,
pageSize: pageSize
}
},
serverFiltering: true,
parameterMap: function (data, type) {
if (type == "read") {
return {
page: data.page,
pageSize: data.pageSize
}
}
}
},
schema: {
model: {
id: "workId",
fields: {
workId: { type: "number" },
workTitle: { type: "string" },
writers: { type: "string" },
durationInMmSs: { type: "string" }
}
},
data: "data",
total: "total"
},
pageSize: pageSize,
serverPaging: true,
serverFiltering: true
},
sortable: true,
resizable: true,
columnMenu: false,
filterable: {
mode: "row",
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
noRecords: {
template: "No results available."
},
pageable: {
numeric: false,
refresh: true,
buttonCount: 15
},
scrollable: false,
columns: [
{
field: "workTitle",
title: "Title",
template: "#=workTitle#"
},
{
field: "writers",
title: "Writers",
filterable: false,
template: "${writers == null ? '':writers}",
width: 300
},
{
field: "durationInMmSs",
title: "Duration",
filterable: false,
headerAttributes: { style: "text-align:right;" },
attributes: { style: "text-align:right;" },
width: 80
},
{ command: { text: "Select", click: selectWork }, title: "", width: 60 }
]
});
Controller action returning json:
public ContentResult SearchWorkJ(string workTitle, int page = 0, int pageSize = 0)
{
var worksJson = "";
var works = WorkService.SearchWork(workTitle, page, pageSize);
if (works != null)
{
// Set total to upto current record + 1 so that next button works in kendo
int totalCount = page * pageSize + 1;
var sortedWorks = new List<WorkViewModel>();
sortedWorks.AddRange(works.Select(w => new WorkViewModel
{
WorkId = w.WorkId,
WorkTitle = w.WorkTitle,
Writers = w.Writers,
DurationInMmSs = w.Duration
}).OrderBy(w => w.WorkTitle));
worksJson = JsonConvert.SerializeObject(new { total = totalCount, data = sortedWorks });
}
return new ContentResult { Content = worksJson, ContentType = "application/json" };
}
If you look at this
https://dojo.telerik.com/EhUNUwOr
<div id="my-grid"></div>
<script>
$('#my-grid').kendoGrid({
dataSource: {
serverFiltering: true,
serverSorting: true,
serverPaging: true,
pageSize: 5,
transport: {
read: function(options) {
$.ajax({
url: '/yourapi',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
data: JSON.stringify(options.data),
success: function(result) {
options.success(result);
}
})
}
},
schema: {
id: 'Id',
data: 'Data',
total: 'Total',
errors: 'Errors',
fields: [
{ field: 'Id', type: 'number' },
{ field: 'FirstName', type: 'string' },
{ field: 'LastName', type: 'string' }
]
},
filter: {
filters: [{ field: 'FirstName', operator: 'eq', value: 'David' }]
}
},
});
</script>
This will send
{"take":5,"skip":0,"page":1,"pageSize":5,"filter":{"filters":[{"field":"FirstName","operator":"eq","value":"David"}]}}
to your server / api
now if you have a model that shares this structure you can respond in the following format
{
"Data" : <your array of models>,
"Total" : the number of models that fits your filter regardless of the filter, this helps kendo grid knowing how many pages there is for the pager.,
"Errors" : is mostely used for create and update so just return null
}
From here its a bonus to the answer above.
I noticed you are using CSharp so you have two options to apply create dynamic queries from Queryable.
use a library I open sourced
https://github.com/PoweredSoft/DynamicLinq
which is available on Nuget https://www.nuget.org/packages/PoweredSoft.DynamicLinq/
There is an example you can look at on git hub.
You'll have to adapt the code around but it should get you started.
https://github.com/PoweredSoft/DynamicLinq#how-it-can-be-used-in-a-web-api
[HttpGet][Route("FindClients")]
public IHttpActionResult FindClients(string filterField = null, string filterValue = null,
string sortProperty = "Id", int? page = null, int pageSize = 50)
{
var ctx = new MyDbContext();
var query = ctx.Clients.AsQueryable();
if (!string.IsNullOrEmpty(filterField) && !string.IsNullOrEmpty(filterValue))
query = query.Query(t => t.Contains(filterField, filterValue)).OrderBy(sortProperty);
// count.
var clientCount = query.Count();
int? pages = null;
if (page.HasValue && pageSize > 0)
{
if (clientCount == 0)
pages = 0;
else
pages = clientCount / pageSize + (clientCount % pageSize != 0 ? 1 : 0);
}
if (page.HasValue)
query = query.Skip((page.Value-1) * pageSize).Take(pageSize);
var clients = query.ToList();
return Ok(new
{
total = clientCount,
pages = pages,
data = clients
});
}
An alternative is using
https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library
I am using jqgrid to display,sort and filter records. At the moment, I have go the js code working, but I think there is something wrong with my controller code, that is not populating the grid. I can see only an empty blak jqgrid with the message "No records to display". Please let me know whats going wrong.
Here is my code:
Controller:
public JsonResult GetData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pagesize = rows;
var custList = db.Customers.Select(
c => new
{
c.ID,
c.Company,
c.FirstName,
c.EMail,
c.Status
});
int totalCustomers = custList.Count();
var totalPages = (int)Math.Ceiling((float)totalCustomers / (float)rows);
if(sord.ToUpper() == "DESC")
{
custList = custList.OrderByDescending(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
else
{
custList = custList.OrderBy(s => s.FirstName);
custList = custList.Skip(pageIndex * pagesize).Take(pagesize);
}
var jsonData = new
{
total = totalPages,
page,
customers = totalCustomers,
rows = custList
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Solved my problem. Dint know I would get the solution so quickly. I removed all the existing code from the controller and just added this:
public JsonResult GetData()
{
var customers = db.Customers.Select(m => new { ID = m.ID, Company = m.Company, FirstName = m.FirstName, Email = m.EMail, Status = m.Status }).ToList();
return Json(customers, JsonRequestBehavior.AllowGet);
}
This is all it needs,just two lines of code, rest of the functionalities, ie paging, sorting, filtering is already provided by jqwidgets:) Hope this helps someone who was facing a similar problem as mine.
The script is as follows:
var source =
{
//localdata: GetData(),
url: '/Client/GetData',
datatype: "json",
mtype: 'POST',
datafields: [
{ name: 'ID', type: 'int' },
{ name: 'Company' },
{ name: 'FirstName' },
{ name: 'EMail' },
{ name: 'Status' }
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
$("#jqxgrid").jqxGrid(
{
source: dataAdapter,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ text: 'Client Id', datafield: 'ID', width: 200 },
{ text: 'Company', datafield: 'Company', width: 200 },
{ text: 'Username', datafield: 'FirstName', width: 180 },
{ text: 'Email', datafield: 'EMail', width: 100 },
{ text: 'Status', datafield: 'Status', width: 140 }
]
});
});
I have been using Select2 version 3 for my dropdowns for a while. However, I am trying to upgrade to the latest v4 release and am struggling to understand their documentation. Would someone be able to point me in the right direction in converting the below v3.5 code to v4 so that I can understand how to convert the rest of my code?
$("##hp.ID").select2(
{
dropdownAutoWidth: true,
minimumInputLength: 0,
allowClear: getBool("#hp.bAllowClear"),
width: "#hp.Width",
formatResult: formatResults,
formatSelection: formatSelection,
matcher: SetMatcher,
sortResults: SortSelect2,
initSelection: function (element, callback)
{
var id = "#Model"
if ((id != "") && (id != "0") && (id != undefined))
{
$.ajax("#Url.Action("GetVendorsInit", "DropDownManagerAjax")",
{
data: JSON.stringify({ VendorID: id }),
dataType: "json"
}).done(function (data)
{
callback({ id: data.id, text: data.text });
});
}
},
ajax: {
url: "#Url.Action("GetVendors", "DropDownManagerAjax")",
dataType: 'json',
quietMillis: 250,
data: function (term, page)
{
return {
q: term,
iDisplayStart: (page - 1) * 100,
iDisplayLength: 100,
sEcho: 0,
iSortCol_0: 0,
sSortDir_0: 'asc',
};
},
results: function (data, page)
{
var more = (page * 30) <= data.total;
return { results: data.data, more: more };
},
cache: true
},
dropdownCssClass: "autoWidth",
escapeMarkup: function (m) { return m; },
placeholder: 'Select Vendor...'
});