jqGrid - edit data - jqgrid

I am quite new to jquery and jqgrid. I use ASP.NET WebForms. I am able to get some data prom server and show it in grid. I use PageMethods to get data from server. Usually my code is
function CreateGrid(){
$("#sestGrid").jqGrid({
datatype: GetData,
//toolbar: [true, "top"],
colNames: ['Name', 'Age'],
colModel: [
{ name: 'Name', index: 'Name', width: 170, align: 'left',
sortable: false, key: true },
{ name: 'Age', index: 'Age', width: 40, align: 'center',
sortable: false, editable: true },
],
ondblClickRow: function () {
var row_id = $("#sestGrid").getGridParam('selrow');
$('#sestGrid').editRow(row_id, true);
}
});
}
function GetData() {
PageMethods.GetSestevalniStevecData(GotData);
}
function GotData (data) {
$("#sestGrid").clearGridData(false);
for (var j = 0; j <= data.length; j++)
$("#sestGrid").jqGrid('addRowData', j + 1, data[j]);
}
So, now I would like to edit some data and post it to server. How can I do that using PageMethods? Should I use any other approach?
And one more thing. I checked the demos http://trirand.com/blog/jqgrid/jqgrid.html and in all edit examples you are able to edit only one row and then you have to save changes… Is it possible to edit more than one row and save all changes in one step?
Thanks all.

jqGrid is designed to be used together with ajax services. So if the user change the data of some row then the changes will be send to the server: to the URL which you configure through jqGrid parameter editurl. So the easiest way to implement row editing will be to include an ASMX web-service or a WCF service in you web site. It is not important whether you use ASP.NET WebForms, ASP.NET MVC or just pure HTML for your pages. So just choose the technology which you prefer and add the corresponding page to your site.
The ASMX or WCF should has a method with the signature like
public string MyDataEdit (string Age, string oper, string id)
(see this old answer for more information). The method should return the id of the new added item (the Name in your case) in case of Add operation.
One more small remark. You can change the definition of the ondblClickRow function from function() to function(row_id) and remove the line used getGridParam('selrow').

I used your example and changed it a bit:
ondblClickRow: function (rowid) {
if (rowid && rowid != lastsel) {
changedRows.push(rowid); //keep row id
jQuery('#jqgrid').editRow(rowid, true);
}
}
Under the save button click event:
$.each(changedRows, function () {
var row = $("#jqgrid").getRowData(this);
var Id = row['ID'];
var price = $(row['Price']).val(); //this is an input type
});
HTH someone :)

Related

Kendo grid data source update approach not working

I have JSON data flowing via Pusher to a simple MVC5 website housing a Kendo Grid. The data, upon arrival, renders successfully in the grid however I'm creating and setting the data source every time. As this seems sinful, I'm trying to determine why my approach to simply updating the data source doesn't render the data.
The grid:
<div id="dashboard"></div>
<script>
$(document).ready(function () {
$("#dashboard").kendoGrid({
columns: [
{ field: "SystemName", width: "50px", title: "System" },
{ field: "Description", width: "100px", title: "Description" },
{ field: "SystemStatus", width: "30px", title: "Status" }
],
height: 600,
scrollable: true,
sortable: true,
});
var dataSource = new kendo.data.DataSource();
var grid = jQuery("#dashboard").data("kendoGrid");
grid.setDataSource(dataSource);
})
</script>
My failed attempt to read in the data without creating and binding a new data source (body of a function call which does happen):
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data = array;
grid.dataSource.read(array);
grid.refresh();
I have confirmed that the data arrives from Pusher correctly yet the above approach does not update the grid.
Thanks in advance for any consideration.
jbt
Use the data() method on the dataSource to set it's data.
var array = JSON.parse(data.updateGrid);
var grid = jQuery("#dashboard").data("kendoGrid");
grid.dataSource.data(array);
You can only set the string value of data on the dataSource if the source is of XML type. Since you are using JSON, you need to call the data function and pass in the new data.
See documentation... http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-data

ExtJS4 dataView - Select node id

I have an ExtJS 4 dataView and i would like to catch the id of a selected node.
It is the first time that i'm using the dataView, then, there are some troubles.
The store is loaded correctly and i see the datas into the view very well. The problem which i'm having, concern the "classic" actions of update and delete, particularly getting the id of a selected item.
For example into a grid i click, then select a record and through a button's pressing i open a window (or other actions) with a loaded form (by sending in AJAX to the store, the id of the selected row) and i update the datas.
I'm not still able to do it with the ExtJS 4 dataView.
Below my dataView:
dataView_player = Ext.create('Ext.Panel', {
id: 'images-view',
frame: true,
collapsible: false,
autoWidth: true,
title: 'Giocatori (0 items selected)',
items: [ Ext.create('Ext.view.View', {
id:'players-view',
store: store_player,
multiSelect: true,
height: 310,
trackOver: true,
overItemCls: 'x-item-over',
itemSelector: 'div.thumb-wrap',
emptyText: 'Nessun giocatore visualizzato',
tpl: [
'<tpl for=".">',
'<div class="thumb-wrap" id="{id}-{name}">',
'<div class="thumb">',
'<img src="/img/players/{picture}" title="{name} {surname}" alt="{name} {surname}" style="">',
'</div>',
'<span class="" style="height:30px;">{general_description}{name} {surname}</span>',
'</div>',
'</tpl>',
'<div class="x-clear"></div>'
],
plugins: [
Ext.create('Ext.ux.DataView.DragSelector', {}),
Ext.create('Ext.ux.DataView.LabelEditor', {dataIndex: 'name'})
],
prepareData: function(data) {
Ext.apply(data, {
name: data.name,
surname: data.surname,
general_description: Ext.util.Format.ellipsis(data.general_description, 15)
});
return data;
},
listeners: {
'selectionchange': function(record, item, index, e) {
var node = this.getNode(record); //this.getNode(record);
console.log(node.get('id'));
}
}
}) ],
dockedItems: [{
xtype: 'toolbar',
items: [{
iconCls: 'delete',
text: 'Cancella Selezionati',
scale: 'medium',
tooltip: 'Per <b>cancellare</b> i giocatori selezionati',
tooltipType: 'qtip',
id: 'delete-player',
disabled: true,
handler: delete_news
}, '-', {
iconCls: 'edit',
text: 'Aggiorna Selezionata',
scale: 'medium',
tooltip: 'Per <b>aggiornare</b> un giocatore selezionato',
tooltipType: 'qtip',
disabled: false,
id: 'update-player',
handler: function(nodes) {
var l = nodes.get('id');
console.log(l);
}
}
}
]
}]
});
Of course, this is a wrong example (because the listeners don't work) but it's just to make an idea.
There are two main things what i would like to do:
1) Catch the id (and other store's fields) of the selected item on the action "selectionchange". Obviously, now it doesn't work because of this: node.get('id'). Of course it's a wrong syntax but make up the idea of my will.
2) Catch the id of the selected item on the handler event of the "update-player" button. As above, the issue is the nodes.get('id'). Further trouble, is how to pass the selected item's features. in handler: function(nodes) { the nodes variable does not assume any value and i don't know how to pass the params from the dataview to the handler function.
I hope that somebody will able to help me.
According to the docs the selectionchange event provides the selection model as well as the array of selected records, so you are probably assuming the wrong parameters in your listener.
Without doing further testing, I think it should be something like this:
listeners: {
'selectionchange': function(selModel, selection, eOpts) {
var node = selection[0];
console.log(node.get('id'));
}
}
Note that you're using multiSelect: true, so it could be more than one record in the selection array.
Answer for second part of the question:
In button handler, you need to get selection model of the view and from it get information about selected records:
handler: function(nodes) {
// find view component
var view = dataView_player.down('dataview');
// get all selected records
var records = view.getSelectionModel().getSelection();
// process selected records
for(var i = 0; i < records.length; i++) {
console.log(records[i].getId());
}
}

jqGrid - form editing issues

In the inline editing, before the editing be made, it creates internally an array (savedRow) and fill it with the values of the fields that are being editable, so I can access this values.
I'd like to know if in the form editing it has something similar to this, because I need to access the values of the fields before the editing will be completed to do a validation before the fields are "saved" in the database.
Someone could help me?
EDITED :
I'm posting here a part of my code (the code of one field), and I'm trying to validate in both way (inline editing and form editing). For inline editing I'm validating using dataEvents and there I'm using savedRow to access the data that were not stored yet. But when I try to edit using form editing because of the the use of savedRow, it shows me an error: savedRow is not defined. In the case of this field the editrules fits with what I want to do, but I don't know if this will occurs in all of those fields.
{ name: 'ac_fd', index: 'ac_fd', width: 50, editable: true,
formatter: 'number', editrules: { number:true, required:true, minValue: 0.1,
maxValue: 1.0 }, formatoptions: { decimalPlaces: 1, decimalSeparator: '.'},
editoptions: {
dataEvents: [ {
type: 'blur', fn: function(e) {
var savedrow = $("#list").getGridParam('savedRow');
console.log($(this).val());
if($(this).val() != savedrow[0]['ac_fd']) {
var eid='#' + savedrow[0]['id'] + '_ac_fd';
var val_fd=$(this).val();
var fd_min=0.1;
var fd_max=1.0;
if( isNaN(val_fd) || val_fd > fd_max || val_fd < fd_min) {
setTimeout(function(){
$(eid).focus().select();
},600);
$(eid).qtip({
content: {
text: 'Fator de Demanda deve ser um <b>número</b>
entre <b>' + fd_min.toFixed(1) + '</b> e <b>'
+ fd_max.toFixed(1) + '</b>.',
title: {
text: 'Atenção:',
button: true
}
},
show: {
event: false,
ready: true,
effect: function() {
$(this).stop(0, 1).fadeIn(400);
},
delay: 0,
},
hide: {
event: false,
effect: function(api) {
$(this).stop(0, 1).fadeOut(900).queue(function() {
api.destroy();
});
},
},
style: {
classes: 'qtip-red qtip-rounded trif_tip_err',
tip: {
width: 10,
height:12
}
},
position: {
my: 'bottom left',
at: 'top center',
},
events: {
render: function(event, api) {
tip_timer.call(api.elements.tooltip, event);
}
}
});
}
}
}
} ]
}
},
So if dataEvents is common and used for the three forms of edit, where can I do this type of validation (using qtip too and I want that this validation be used in inline editing too)?
The reason why jqGrid save the editing row in interval savedRow parameter is because jqGrid modify the editing row in-place. Only because of that inline editing and cell editing use interval savedRow parameter. Form editing don't modifies the original row of grid till the editing will be finished. So no savedRow parameter are used by form editing.
If the form are closed or if the server response will contains some error HTTP code the new data entered by user will be not saved in the grid. So simple server side validation is typically enough. If you want implement additional client side validation you can use editrules feature. Custom validation is typically enough. It can help validate one field of the form. If you need compare multiple fields of form during validation (if the value of one field defines valid values of another field) then one uses beforeCheckValues callback additionally.
UPDATED: Inside of fn event handler you can test whether it will be called inside of form editing or not. There are many ways to do this. For example you can test $(e.target).closest(".FormGrid").length > 0. If it's true then the event is inside of form. Additionally it's important to understand that the current editing row is not changed till successful saving on the server. So you can use any time getGridParam with "selrow" option to get the id of editing row and you can use getRowData or getCell to get the data from the grid before modification started (the same as savedrow).

MVC3 JQGrid Set colmodel dynamically from controller

I've seen tons of examples about setting the colmodel in the view but I haven't been able to see the controller code!
I am trying to do it but the setup keep being wrong.
I am trying to reach this column formation:
colModel:
[
{ name: 'ID', index: 'ID', hidden: true },
{ name: 'Votes', index: 'Votes', width: 100, align: 'left' },
{ name: 'Question', index: 'Question', width: 300, align: 'left' },
{ name: 'my_clickable_checkbox', index: 'my_clickable_checkbox',
sortable: true,
formatter: chkFmatter, formatoptions: { disabled: false }, editable: true,
edittype: "checkbox"
}
],
This is my trial in the controller:
return Json(
new { colNames = new[] { "ID2", "Votes2", "Question2", "checkbox" },
colModel = new[] {
new { name = "ID", index = "ID", width = 0, formatter="",
edittype="", hidden = true },
new { name = "Votes", index = "Votes", width = 100, formatter="",
edittype="", hidden = false },
new { name = "Question", index = "Question", width = 300, formatter="",
edittype="", hidden = false },
new { name = "checkbox", index = "my_clickable_checkbox", width = 100,
formatter="chkFmatter", edittype="checkbox", hidden = false }
}
}, JsonRequestBehavior.AllowGet);
The creation of this array in the controller is forcing me to have the same number of properties in all rows. For example, I only need the ID to be hidden, but it forces me to supply a hidden property to all other columns.
Second problem, I need to call js function chkFmatter for the fourth column.
how can I reach that colModel formation in controller??
thanks much.
You might be interested in looking at jqGrid Importing and exporting functionality. It allows you to import or export the entire jqGrid configuration to or from another file format.
You can read this blog post:
jqGrid and ASP.NET MVC - Configuration Import/Export
to get the general idea on how to use those functionalities with ASP.NET MVC, but it`s a little bit out of date if it comes to ASP.NET MVC stuff (it is based on ASP.NET MVC 1).
You can also take a look at this jqGrid sample project:
jqGrid in ASP.NET MVC 3 and Razor
which (among other things) contains sample for configuration import/export.
Most imported thing to remember here is that you still need to set any jqGrid events/callbacks or call any additional methods like 'setFrozenColumns' after configuration import.

JQGrid getRowData error

I have the following JQ-Grid with a formatter function which returns some HTML as the column value:
jQuery("#list").jqGrid({
url:jsonUrl,
datatype: 'json',
mtype: 'GET',
colNames:['Id', 'Name', 'Phone', 'Action'],
colModel :[
{name:'id', index:'id', sortable:true},
{name:'name', index:'name', sortable:true},
{name:'phone', index:'phone', sortable:false},
{name:'details', index:'details', sortable: false,
formatter:function(cellvalue,options,rowObject){
return "<p class='trigger'><a href='#'><img src='/images/actions.jpg' /></a></p><div class='toggle_container'><div class='block'><table class='action'><tr><td><a href='#'><img src='/images/open.gif' /></a></td><td><a href='#'><img src='/images/edit.gif' /></a></td><td><a href='#'><img src='/images/delete.gif' /></a></td></tr></table></div></div>"
}
}
]
Later on, I try to get all the column / row data and export it to Excel. Is there a feature in JQ-Grid which allows you to export in Excel / PDF (fyi - I am using JSP/JAVA).
When I try to do something like this:
var mya=new Array();
mya=$("#list").getDataIDs(); // Get All IDs
var data=$("#list").getRowData(mya[0]); // Get First row to get the labels
I get a JavaScript error:
Message: 'l.p.colModel[...].name' is null or not an object
URI: http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.1.2/js/jquery.jqGrid.min.js
I think I may have an answer to your problem - or at least a workaround that will suffice. Take a look at the javascript below. This is the approach I use for ripping the data out of the grid:
var sCell;
var aDataIDs = $Grid.getDataIDs();
//Loop through table rows
for (var i = 0; i < aDataIDs.length; i++) {
try {
//Get row
var oRow = $Grid.getRowData(aDataIDs[i]);
}
catch (e) {
//If problem then fall back to this
for (var j = 0; j < _oJQGUserSettings.aColModel.length; j++) {
if (j > 0) sb.append('\t'); //Add tab
//Get cell data
sCell = $Grid.getCell(aDataIDs[i], _oJQGUserSettings.aColModel[j].name);
sb.append(sCell); //Add data
}
}
If you bear in mind that sb is a javascript stringbuilder class and _oJQGUserSettings.aColModel is just my encapsulation of the ColModel then this should probably give you what you need in terms of extracting the data from the grid as required. (I then copy it to the clipboard which allows me to paste the contents of the grid straight into Excel - handy!)
I suspect there is a bug in getRowData which is thrown when not all columns are displayed to the user. However I haven't isolated this for sure as yet.

Resources