Interesting: implementing jquery autoComplete with jqgrid without overriding the exciting searchOptions - jquery-ui

Oleg - are you here???
I am using jqGrid, were i set in colModel my searchoption according to the type
Like this:
var columnModel = [{ name: 'ID', index: 'ID', sortable: true,searchoptions: { sopt: ['gt']}},
{ name: 'FirstName', index: 'FirstName', sortable: true, searchoptions: { sopt: ['cn']} },
{ name: 'LastName', index: 'LastName', sortable: true ,searchoptions: { sopt: ['ge']}}
];
Now after i load the grid i want to use the fallowing code in order to add auticomplete to the search box of the grid:
for (var i = 0; i < columnModel.length; i++) {
var nameCol = columnModel[i].name;
myGrid.jqGrid('setColProp', nameCol,
{
searchoptions: {
dataInit: function (elem) {
$(elem).autocomplete({
source: function (request, response) {
autoFillSearch(request, response, $(elem).attr('name'));
},
minLength: 1
});
}
}
});
}
myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });
the autoFillSearch function is like this:
function autoFillSearch(request, response, columnToSearchName) {
var paramters = {
colName: columnToSearchName,
prefixText: request.term
};
$.ajax({
url: './ViewNQueryData.asmx/AutoCompleteSearch',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function (data) {
response($.each(data.d, function (index, value) {
return {
label: value,
value: index
}
}));
}
});
}
The problem is that new the colModels have the search option that were created the second time and dont have my specific "sopt" i want them to have....
I there any way of changing the second searchoption so that it will get the "sopt" option from the original colMadel?
Thank you in advance.

the answer for this is:
for (var i = 0; i < columnModel.length; i++) {
var nameCol = columnModel[i].name;
var soptOption = columnModel[i].searchoptions.sopt;
myGrid.jqGrid('setColProp', nameCol,
{
searchoptions: {
sopt: soptOption,
dataInit: function (elem) {
$(elem).autocomplete({
source: function (request, response) {
autoFillSearch(request, response, $(elem).attr('name'));
},
minLength: 1
});
}
}
});
}

Related

How can I get the selected checkbox in kendo grid?

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.

Grid Not populating in kendoGrid

I am using MVC 4 and kendo UI for grid population. But the grid is not populating correctly.
this is my View :
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data;
var element = $("#grid4").kendoGrid({
dataSource: {
data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
}
});
</script>
Conroller ;
[HttpGet]
public ActionResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
using (var emp = new MockProjectAkarshEntities1())
{
IQueryable<tbl_UserDetails> userDetails = emp.tbl_UserDetails;
DataSourceResult result = userDetails.ToDataSourceResult(request);
return Json(result,JsonRequestBehavior.AllowGet);
}
In the output I am getting something like "[object][object]" and no of rows in the table returned from database.the skeleton of grid is coming but not the data. I am new to MVC and kendo. Please help me out.
The data you received should be started with {"Data": So simply change your code from var dataloc = data; to var dataloc = data.Data; just confirm it by visiting UserSummary/Employee_Read.
You can also set the dataSource later on like this (if you prefer at some stage)
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data.Data;
var element = $("#grid4").kendoGrid({
dataSource: {
// data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
// create data source using the data received
var ds = new kendo.data.DataSource({
data: dataloc
});
$('#grid4').data('kendoGrid').setDataSource(ds);
}
});
</script>

Delete, No url is set in jqgrid

I'm using jqgrid and when deleting a row in the grid i get the alert "Delete selected record?" and when i click ok i have written a code in onClickSubmit to make a ajax call to the controller which takes some parameters and delete the record. The functionality works fine.
But when i click "Delete" button in the alert i get an error "No url is set". Now, i have a url inside my ajax call which does the function. Why is the error thrown?
jqGrid:
var selectedRowId = "125";
$("#AttachmentsGrid").jqGrid({
url: '#Url.Action("LoadTransactionAttachments", "Home")',
postData: { 'transactionId': selectedRowId },
mtype: 'GET',
datatype: 'json',
jsonReader: {
id: 'AttachmentId',
repeatitems: false
},
height: 'auto',
hidegrid: false,
rownumbers: true,
autowidth: true,
shrinkToFit: false,
rowNum: 10,
pager: '#AttachmentsPager',
caption: "Attachments",
colNames: ['AttachmentName'],
colModel: [{ name: 'AttachmentName', index: 'AttachmentName', formatter: imageFormatter, unformat: imageUnFormatter }],
beforeRequest: function () {
responsive_jqgrid($(".jqGrid"));
},
onSelectRow: function (id) {
var statusId;
attachmentId = id;
var selectValues = jQuery('#AttachmentsGrid').jqGrid('getRowData', id);
attachmentName = selectValues.AttachmentName;
if (accessLevel.HasDeleteAttachmentAccess == true)
$("#del_AttachmentsGrid").show();
else
$("#del_AttachmentsGrid").hide();
},
loadComplete: function () {
UnBlockUI();
}
});
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, del: true, search: false, refresh: true, refreshtext: ""
}, {}, {}, {
// url: '#Url.Action("UpdateDummyData", "Home")',
// Delete attachment event.
onclickSubmit: function (response, postData) {
$.ajax({
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
datatype: 'json',
data: { 'attachmentId': JSON.stringify(postData), 'attachmentName': attachmentName, 'transactionId': selectedRowId },
type: 'POST',
success: OnCompleteDeleteAttachments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
It works when i give some Dummy url in delete method which i dont need. I need another way to solve this.?
FYI, This happens for me also during the edit of a row using form editing.
It seems to me that you try to use Delete in a wrong way. What you do is making Ajax request to '#Url.Action("DeleteSelectedTransactionAttachment", "Home")' with some additional data, do some unknown additional action inside of OnCompleteDeleteAttachments in case of successful deleting and do additional error handling in case of "Session TimeOut/UnAuthorized" error in statusText.
I think that correct implementation should looks more as the following
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, search: false, refreshtext: ""
}, {}, {}, {
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
serializeDelData: function (postData) {
return {
attachmentId: JSON.stringify(postData),
attachmentName: attachmentName,
transactionId: selectedRowId
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
afterSubmit: OnCompleteDeleteAttachments
});

jqxgrid not displaying busy or loading indicator

I am using jqxgrid and I have below code snippet and i want to display load indicator on button click which calls the Ajax method and hide it on the success method or anyway other to display it as i need to show loading indicator from the time request made till i get the data
$("#btnSearch").bind('click', function () {
//show indicator here
LoadLookUpSearchGrid();
}
//Ajax call to fetch data
function LoadLookUpSearchGrid() {
var filterRows = getGridRows();
$.ajax({
type: 'POST',
dataType: 'json',
async: false,
cache: false,
url: 'AddEditView.aspx/LoadLookUpSearchGrid',
data: JSON.stringify({ FilterType: $('select#ddlFilterType').val() , Id: $("#txtId").val() , Name: $("#txtName").val(), SearchText: '', FilterRows: filterGridRows}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
error: function (err) {
alert(err.text + " : " + err.status);
}
});
};
//source object to format data
function SetSearchFields(fieldName, source) {
var columns;
if (fieldName == "Operating Company") {
source =
{
datatype: "xml",
datafields: [
{ name: 'COMPANY', type: 'string' },
{ name: 'DESCR', type: 'string' }
],
async: false,
root: "Company",
localdata: source
};
columns = [
{ text: 'OPCO ID', dataField: 'COMPANY', width: '30%' },
{ text: 'Company Name', dataField: 'DESCR', width: '65%' }
];
}
lookupSearchResultGrid(source, columns,fieldName);
}
//adaptor to fill source and bind grid
function lookupSearchResultGrid(source, columns,fieldName) {
var searchViewGridDataAdapter = new $.jqx.dataAdapter(source);
$("#divLookupSearch").jqxGrid(
{
width: '100%',
source: searchViewGridDataAdapter,
theme: theme,
sortable: true,
pageable: true,
autoheight: true,
selectionmode: 'checkbox',
columns: columns
});
//hide indicator here on on success method of ajax call
};
On the click of the button call showloadelement and in the Ajax call success callback function call hideloadelement.
$("#btnSearch").bind('click', function () {
$('#divLookupSearch').jqxGrid('showloadelement');
//show indicator here
LoadLookUpSearchGrid();
}
...
success: function (data) {
$('#jqxGrid').jqxGrid('hideloadelement');
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
...
Best Regards,
Alpesh

JQWidgets jqxGrid: Dataadapter and Paging

i have a newbie question, but i’m scratching my head on this one. I have a grid, bound to a dataadapter. On the grid, paging and filtering is explicit disabled, but the GET-call from the dataadapter allways includes following parameters in the GET-url:
?filterscount=0&groupscount=0&pagenum=0&pagesize=10&recordstartindex=0&recordendindex=18&_=1386768031615
I want to get all data, then cache it clientside for paging and filtering, but in the first step i just want to get my data bound to the grid.
Here’s my code:
var source = {
type: "GET",
datatype: "json",
datafields: [
{ name: 'url' },
{ name: 'category', type: 'int' },
{ name: 'info' },
{ name: 'status', type: 'bool' }
],
url: '/api/redirects/Getallredirects',
id: 'id'
};
var dataAdapter = new $.jqx.dataAdapter(source, {
contentType: 'application/json; charset=utf-8',
loadError: function (xhr, status, error) {
alert(error);
},
downloadComplete: function (data) {
var returnData = {};
returnData.records = data.d;
return returnData;
}
});
$("#jqxgrid").jqxGrid({
source: dataAdapter,
filterable: false,
pageable: false,
virtualmode: false,
columns: [
{ text: 'URL', dataField: 'url', width: 100 },
{ text: 'Category', dataField: 'category', width: 100 },
{ text: 'Info', dataField: 'info', width: 180 },
{ text: 'Status', dataField: 'status', width: 80, cellsalign: 'right' },
]
});
I don’t get any data, the GET-call fails because of the automatically included parameters. How do i get rid of these parameters?
I just found in the jqxGrid documentation a reference to these parameters, but no example, how to remove them:
http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-extra-http-variables.htm
Thanks in advance for any help.
The below will remove the default parameters:
var dataAdapter = new $.jqx.dataAdapter(source,
{
formatData: function (data) {
return {};
}
}
);

Resources