Please find my code attached :
Jqgrid creation:
<script type="text/javascript">
$(function () {
$("#datagrid").jqGrid({
url: 'jqgridwithwebmethod.aspx/ConvertDataTabletoString',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
// return JSON.stringify(postData);
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['Name', 'Age', 'Mobile', 'City', 'Sex', 'FirstName', 'LatName', 'Address', 'Landline'],
colModel: [
{ name: 'Name', index: 'Name', width: 200, frozen: true, editable: true },
{ name: 'Age', index: 'Age', sorttype: 'int', width: 200, editable: true },
{ name: 'Mobile', index: 'Mobile', sorttype: 'int', width: 200, editable: true },
{ name: 'City', index: 'City', width: 200, editable: true },
{ name: 'Sex', index: 'Sex', width: 200, editable: true },
{ name: 'FirstName', index: 'FirstName', width: 200, editable: true },
{ name: 'LastName', index: 'LastName', width: 200, editable: true },
{ name: 'Address', index: 'Address', width: 200, editable: true },
{ name: 'Landline', index: 'Landline', width: 300, editable: true }
],
pager: '#nav',
rowNum: 10,
sortname: 'Name',
autowidth: true,
sortorder: "desc",
shrinkToFit: false,
//forceFit:false,
loadonce: true,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false
//id: "0"
},
caption: 'My first grid'
});
$("#datagrid").jqGrid('setFrozenColumns');
});
**$('#datagrid').jqGrid('navGrid', '#nav',**
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
});
</script>
The function ConvertDataTabletoString is defined as:
[WebMethod]
public static List<Dictionary<string, object>> ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from studen with(nolock)", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
The Jqgrid use data received from SQL server.
The edit/add/delete icons are not dispalying on the Jqgrid..
Kindly help..
You placed call of navGrid method on the wrong place. You have block $(function () {...}); which meany document ready event handler. You placed call of navGrid method out of the block. It's wrong. You should mode it one line above (directly after the call of setFrozenColumns) to fix the problem.
Related
I have a jqGrid that loads fine and the drop down loads fine as well but I'm not sure hot to go about updating(loading) the second dropdown based on the first dropdown's onchange event.
Here is my grid. As you can see I load countries but now I would like to load the available currencies based on the selected country.
$("#jqgrid").jqGrid
({
url: '#Url.Action("GetSupplierData", "Maintenance")',
datatype: 'json',
mtype: 'Get',
//table header name
colNames: [
'Id', 'Code', 'Name', 'Account Number', 'Contact Person', 'Contact Number',
'Email', 'Address', 'Country', 'Currency', 'InsertUserId',
'InsertDateTime', 'InsertUserName', 'UpdateUserId', 'UpdateDateTime', 'UpdateUserName'
],
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'id',
index: 'id',
editable: true
}, {
key: false,
name: 'code',
index: 'code',
editable: true
}, {
key: false,
name: 'name',
index: 'name',
editable: true
}, {
key: false,
name: 'accountnumber',
index: 'accountnumber',
editable: true
}, {
key: false,
name: 'contactperson',
index: 'contactperson',
editable: true
}, {
key: false,
name: 'contactnumber',
index: 'contactnumber',
editable: true
}, {
key: false,
name: 'email',
index: 'email',
editable: true
}, {
key: false,
name: 'address',
index: 'address',
editable: true
}, {
key: false,
name: 'countryId',
index: 'countryId',
editable: true,
edittype: 'select',
editoptions: {
dataInit: function(element) {
$.ajax({
url: '#Url.Action("GetCountries", "Maintenance")',
dataType: 'json',
type: 'POST',
success: function(response) {
var array = response;
if (array != null) {
var i;
for (i in array) {
if (array.hasOwnProperty(i)) {
if (ctyId == array[i].id) {
$(element).append("<option value=" + array[i].id +" selected>" + array[i].name +"</option>");
} else {
$(element).append("<option value=" + array[i].id + ">" + array[i].name + "</option>");
}
}
}
}
}
});
},
dataEvents:
{
type: 'change',
fn: function (e) {
}
}
},
editrules: { required: true, integer: true }
}, {
key: false,
name: 'currencyId',
index: 'currencyId',
editable: true
}, {
key: false,
hidden: true,
name: 'insertUserId',
index: 'insertUserId',
editable: true
}, {
key: false,
hidden: true,
name: 'insertDateTime',
index: 'insertDateTime',
editable: true
}, {
key: false,
hidden: true,
name: 'insertUserName',
index: 'insertUserName',
editable: true
}, {
key: false,
hidden: true,
name: 'updateUserId',
index: 'updateUserId',
editable: true
}, {
key: false,
hidden: true,
name: 'updateDateTime',
index: 'updateDateTime',
editable: true
}, {
key: false,
hidden: true,
name: 'updateUserName',
index: 'updateUserName',
editable: true
}
],
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
caption: 'Suppliers',
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
pager: '#pjqgrid',
sortname: 'id',
toolbarfilter: true,
viewrecords: true,
sortorder: "asc",
autowidth: true,
multiselect: false,
onSelectRow: function(id) {
var selRowId = $("#jqgrid").jqGrid('getGridParam', 'selrow');
ctyId = $("#jqgrid").jqGrid('getCell', selRowId, 'currencyId');
}
//pager-you have to choose here what icons should appear at the bottom
//like edit,create,delete icons
}).navGrid('#pjqgrid',
{
edit: true,
add: false,
del: true,
search: true,
refresh: true
},
{
// edit options
zIndex: 1000,
url: '#Url.Action("EditSupplier", "Maintenance")',
dataType: "html",
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function(response) {
$('#alerts').html(response.responseText);
}
},
{
// add options
},
{
// delete options
zIndex: 1000,
url: '#Url.Action("DeleteSupplier", "Maintenance")',
type: "POST",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this?",
afterComplete: function(response) {
$('#alerts').html(response.responseText);
}
});
This Guriddo of jqGrid example will point you in the right direction.
I'm trying to put a GridPanel powered by an ArrayStore in a Window, but no matter what I do, it just looks like this with no data rows inside:
Here's my code:
var ticketsStore = new Ext.data.ArrayStore
(
{
autoDestroy: false,
remoteSort: false,
data: result,
fields:
[
{ name: 'articleId', type: 'int' },
{ name: 'heatTicketRef', type: 'string' },
{ name: 'username', type: 'string' },
{ name: 'dateLinked', type: 'date' }
]
}
);
var ticketsGrid = new Ext.grid.GridPanel({
store: ticketsStore,
id: this.id + 'ticketsGrid',
viewConfig: {
emptyText: 'No data'
},
autoShow: true,
idProperty: 'heatTicketRef',
columns: [
{ id: 'heatTicketRef', header:"Ticket ID", width: 100, dataIndex: 'heatTicketRef', sortable: false },
{ header: "User", width: 100, dataIndex: 'username', sortable: false },
{ header: "Date Linked", width: 100, dataIndex: 'dateLinked', xtype: 'datecolumn', format: 'j M Y h:ia', sortable: false }
]
});
var window = new Ext.Window
(
{
renderTo: Ext.getBody(),
id: this.id + 'linkedHeatTickets',
closable: true,
modal: true,
autoHeight: true,
width: 500,
title:'Linked Heat Tickets',
resizable: false,
listeners:
{
close: function () { // do something }
},
items:
{
style: 'padding:5px;',
items: ticketsGrid
},
buttons:
{
text: 'Close',
handler: function () {
window.close();
}
}
}
);
window.show();
When I debug, I can see that my "result" object is healthy and the ArrayStore is of the right length:
But the GridPanel doesn't like the data because it's not in its items (although it's in the store) array:
What little thing have I done wrong?
Thanks!
Because I'm an idiot... I used an ArrayStore instead of a JsonStore!
I want to use a complete jqgrid but it is not working. It is not showing any data but controller action returning the values. Here is my controller action code which is used in my project. My purpose is to use pager in jqgrid. Please help me and i need some solutions & tips for using jqgrid in mvc.
public ActionResult itemList(jqGridViewModel jqGridParameters)
{
var item = from t in db.tbl_Item select t;
var count = item.Count();
int pageIndex = jqGridParameters.page;
int pageSize = jqGridParameters.rows;
int startRow = (pageIndex * pageSize) + 1;
int totalRecords = count;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
rows = item.Select(x => new
{
x.id,
x.itemcode,
x.name,
x.qtyLimit,
x.Quantity,
x.sellingPrice,
x.supplier,
x.unitType,
x.vat,
x.batchno,
x.brand,
x.buyingPrice,
x.catg
}
).ToArray()
.ToPagedList(pageIndex, pageSize)
.Select(x => new
{
id = x.id,
cell = new string[] { x.id.ToString(),
x.name,
x.itemcode,
Convert.ToString(x.qtyLimit),
x.Quantity.ToString(),
x.sellingPrice.ToString(),
x.supplier,
x.unitType,
x.vat.ToString(),
x.batchno,
x.brand,
x.buyingPrice.ToString(),
x.catg
}
}
).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
And my view code
jQuery("#list").jqGrid({
cache: false,
async: false,
url: '/Settings/itemList/',
datatype: 'json',
mtype: 'GET',
colNames: ['New Item', 'Batch No', 'Supplier', 'Unit', 'B. Price', 'S. Price','Item Code','Vat','Limit'],
colModel: [
{ name: 'name', index: 'name', width: 110, align: 'center' },
{ name: 'batchno', index: 'batchno', width: 110, align: 'center' },
{ name: 'supplier', index: 'supplier', width: 110, align: 'center' },
{ name: 'unitType', index: 'unitType', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'buyingPrice', index: 'buyingPrice', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'sellingPrice', index: 'sellingPrice', align: 'center' },
{ name: 'itemcode', index: 'itemcode', width: 110, align: 'center'},
{ name: 'vat', index: 'vat', width: 110, align: 'center', editoptions: { readonly: 'readonly' } },
{ name: 'qtyLimit', index: 'qtyLimit', align: 'center' }
],
pager: jQuery('#pager'),
rowNum: 15,
rowList: [5, 10, 20, 50],
sortname: 'iid',
sortorder: "desc",
viewrecords: true,
width: 960,
height: 200,
loadOnce: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'Stock Information',
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
recordtext: "Products {0} - {1} of {2}",
rownumbers: true,
pagerpos: 'center'
});
You define JsonReader like this:
jsonReader: {
root: "Data",
page: "CurrentPage",
total: "TotalPages",
records: "TotalRecords",
repeatitems: false,
id: "0"
},
And ther on controller side you passing data to anonimous object that have this properties:
var result = new
{
total = totalPages,
page = pageIndex,
records = count,
...
}
Your property names should be the same as you define in your JsonReader
I have an Editor Grid and a store with a custom type in it.
store :
var sourceStore = new Ext.data.JsonStore({
url: hp,
storeId: 'labels-data-store',
idProperty: 'ID',
root: 'results',
fields: [{
name: 'ID',
type: 'int'
}, {
name: 'LanguageID',
type: 'int'
}, {
name: 'KeyID',
type: 'int'
}, {
name: 'Value',
type: 'string'
}, {
name: 'ToolTip',
type: 'string'
}, {
name: 'LanguageName',
type: 'string'
}, {
name: 'KeyInfo',
type: 'LanguageKeyInfo'
},
CUSTOM TYPE HERE !! !{
name: 'ServerComments',
type: 'string'
}]
});
Editor Grid :
var sourceGrid = new Ext.grid.EditorGridPanel({
id: 'source-grid',
region: 'center',
title: localize.sourceView,
iconCls: 'source-view-title',
store: sourceStore,
trackMouseOver: true,
disableSelection: false,
loadMask: true,
split: true,
stripeRows: true,
border: true,
autoExpandColumn: 'label',
cm: sourceColModel,
// customize view config
viewConfig: {
forceFit: true,
enableRowBody: true,
showPreview: false,
emptyText: localize.noRecordsFound
},
sm: new Ext.grid.RowSelectionModel({
singleSelect: false,
moveEditorOnEnter: true
})
});
Custome Type implementation:
LanguageKeyInfo = function () {
this.ID = arguments[0];
this.Value = arguments[1];
this.Description = arguments[2];
}
Ext.data.Types.LANGUAGEKEYINFO = {
convert: function (v, data) {
if (!data) {
return null;
}
if (!data.KeyInfo) {
return null;
}
return new LanguageKeyInfo(
data.KeyInfo.ID,
data.KeyInfo.Value,
data.KeyInfo.Description);
},
sortType: function (key) {
return key.ID;
},
type: 'LanguageKeyInfo'
}
Source Column Model:
var sourceColModel = new Ext.grid.ColumnModel({
columns: [{
header: 'ID',
dataIndex: 'ID',
width: 50,
hidden: true,
sortable: true
}, {
header: 'Language ID',
dataIndex: 'LanguageID',
width: 50,
hidden: true,
sortable: true
}, {
header: 'Language',
dataIndex: 'LanguageName',
width: 20,
hidden: true,
sortable: true
}, {
header: 'Key ID',
dataIndex: 'KeyID',
width: 30,
hidden: true,
sortable: true
}, {
header: 'Key',
dataIndex: 'KeyValue',
width: 40,
sortable: true,
editor: new Ext.form.TextField({
allowBlank: false,
maxLength: 200
})
}, {
header: 'Label',
dataIndex: 'Value',
sortable: true,
editor: new Ext.form.TextField({
allowBlank: false,
maxLength: 500
}),
renderer: function (sc) {
var lanID = getSelectedLanguageID() ? getSelectedLanguageID() : 1;
switch (parseInt(lanID)) {
case 2:
return '<div class="rtl">' + sc + '</div>';
default:
return sc;
}
}
}, {
header: 'Description',
dataIndex: 'KeyDescription',
width: 30,
editor: new Ext.form.TextField({
allowBlank: true,
vtype: 'englishOnly',
maxLength: 100
})
}, {
header: 'Tool Tip',
dataIndex: 'ToolTip',
width: 80,
sortable: true,
editor: new Ext.form.TextField({
allowBlank: true,
maxLength: 200
})
}]
});
When I start editing the first column row the text field value is [object,object] which mean the grid is passing the KeyInfo object to the textbox value.
How can I send one of KeyInfo properties to the textbox and have it mapped to the store record ??
For starters your dataIndex does not reference a valid record mapping:
dataIndex: 'KeyValue', should probably be dataIndex: 'KeyInfo',
Secondly I don't think there is any support for custom types on grid editors. I might be wrong of course.
The following ExtJS grid worked until I put the checkbox column in it, now I get this error:
I based the checkbox column code on this code.
What do I need to do to get the checkbox column to work?
var myData = [
[4, 'This is a whole bunch of text that is going to be word-wrapped inside this column.', 0.24, true, '2010-11-17 08:31:12'],
[16, 'Computer2', 0.28, false, '2010-11-14 08:31:12'],
[5, 'Network1', 0.02, false, '2010-11-12 08:31:12'],
[1, 'Network2', 0.01, false, '2010-11-11 08:31:12'],
[12, 'Other', 0.42, false, '2010-11-04 08:31:12']
];
var myReader = new Ext.data.ArrayReader({}, [{
name: 'id',
type: 'int'
}, {
name: 'object',
type: 'object'
}, {
name: 'status',
type: 'float'
}, {
name: 'rank',
type: 'boolean'
}, {
name: 'lastChange',
type: 'date',
dateFormat: 'Y-m-d H:i:s'
}]);
var grid = new Ext.grid.GridPanel({
region: 'center',
style: 'margin: 10px',
store: new Ext.data.Store({
data: myData,
reader: myReader
}),
columns: [{
header: 'ID',
width: 50,
sortable: true,
dataIndex: 'id',
hidden: false
},
{
header: 'Object',
width: 120,
sortable: true,
dataIndex: 'object',
renderer: columnWrap
}, {
header: 'Status',
width: 90,
sortable: true,
dataIndex: 'status'
},
{
xtype: 'checkcolumn',
header: 'Test',
dataIndex: 'rank',
width: 55
},
{
header: 'Last Updated',
width: 120,
sortable: true,
renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s'),
dataIndex: 'lastChange'
}],
viewConfig: {
forceFit: true,
getRowClass: function(record, rowIndex, rp, ds){
if(rowIndex == 2){
return 'red-row';
} else {
return '';
}
}
},
title: 'Computer Information',
width: 500,
autoHeight: true,
frame: true,
listeners: {
'rowdblclick': function(grid, index, rec){
var id = grid.getSelectionModel().getSelected().json[0];
go_to_page('edit_item', 'id=' + id);
}
}
});
You get this error because you have not included the CheckColumn extension. You can get the extension from : http://dev.sencha.com/deploy/dev/examples/ux/CheckColumn.js .. include it and you should be able to remove the error..