JqGrid Treegrid sorting issue - jqgrid

I hope you can help me, I have a structure like this:
- root A
-child_A1
-child_A1_1
-child_A1_2
-child_A1_3
-child_A2
-child_A2_1
-child_A2_2
-child_A2_3
- root B
- child_B1
-child_B1_1
-child_B1_2
-child_B1_3
But when I show the data in TreeGrid, it shows like this:
- root A
-child_A1
-child_A2
-child_A1_1
- root B
- child_B1
-child_B1_1
-child_B1_2
-child_B1_3
-child_A1_2
-child_A1_3
-child_A2_1
-child_A2_2
-child_A2_3
Anybody knows why..??? please help, I search information about this error but don`t have luck....
Here's my JavaScript:
<script type="text/javascript">
$(document).ready(function () {
var lastsel;
$(function () {
jQuery('#tree').jqGrid({
url: '/Ubicacion/TreeGrid/',
datatype: 'json',
height: 250,
colNames: ['Nombre', 'Descripcion'],
colModel: [
{ name: 'Nombre', index: 'Nombre', width: 100, sortable: true, editable: true, edittype: "text"},
{ name: 'Descripcion', index: 'Descripcion', width: 80, editable: true, edittype: "text" }
],
caption: 'Listado de Ubicaciones',
treeGridModel: 'adjacency',
sortname: 'Nombre',
loadonce: true,
height: 'auto',
width: '500',
pager: "#pager",
treeGrid: true,
ExpandColumn: 'Id',
ExpandColClick: true,
});
});
});
And here is the server side function that I used for generate json string:
public ActionResult TreeGrid(string sidx, string sord, int? page, int? rows)
{
List<Ubicacion> ubicacion = new List<Ubicacion>();
ubicacion = UbicacionRepository.GetAll().ToList<Ubicacion>();
int pageIndex = Convert.ToInt32(page) - 1;
int totalrecords = ubicacion.Count();
JsonResult json = new JsonResult();
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
json.Data = new
{
sidx = "Nombre",
sord = "asc",
page = page,
records = totalrecords,
rows = (from ubi in ubicacion
select new
{
cell = new string[]
{
ubi.Nombre,
ubi.Descripcion,
ubi.Nivel.ToString(),
ubi.IdPadre == 0 ? "null" : ubi.IdPadre.ToString(),
ubi.Nivel < 2 ? "false" : "true",
"false",
"true"
}
})
};
return json;
}
And here's the json generated:
{"total":1,"page":null,"records":18,"rows":[
{"cell":["Parent A","ubicacion","0","null","false","false","true"]},
{"cell":["Child A1","ubicacion","1","1","false","false","true"]},
{"cell":["Child A2","ubicacion","1","1","false","false","true"]},
{"cell":["Child A1_1","ubicacion","2","2","true","false","true"]},
{"cell":["Parent B","ubicacion","0","null","false","false","true"]},
{"cell":["Child B1","ubicacion","1","5","false","false","true"]},
{"cell":["Child B1_1","ubicacion","2","6","true","false","true"]},
{"cell":["Child B1_2","ubicacion","2","6","true","false","true"]},
{"cell":["Child B1_3","ubicacion","2","6","true","false","true"]},
{"cell":["Child A1_2","ubicacion","2","2","true","false","true"]},
{"cell":["Child_A1_3","ubicacion","2","2","true","false","true"]},
{"cell":["Child A2_1","ubicacion","2","3","true","false","true"]},
{"cell":["Child A2_2","ubicacion","2","3","true","false","true"]},
{"cell":["Child A2_3","ubicacion","2","3","true","false","true"]}
]}

I got it! you need to order recursively the list, because it's rendering in the exact order you extracted from your db..
private static List<MENU> Listado = new List<MENU>();
private static List<MENU> lstOrdenada = new List<MENU>();
public List<MENU> MenuRecursivo()
{
//the whole list of MENU
Listado = (from m in db.MENU where m.men_eliminado == "N" select m).ToList();
// a list where we'll put the ordered items
lstOrdenada = new List<MENU>();
foreach (MENU item in Listado.Where(x => x.ID_MENU == x.id_menu_padre).ToList()) // in my case, only the root items match this condition
{
lstOrdenada.Add(item);
GMenuHijo(item.ID_MENU, ref lstOrdenada);
}
return lstOrdenada;
}
`
Then, for each root item, recursively find the next levels:
private static void GMenuHijo(int idPadre, ref List<MENU> lst)
{
List<MENU> listado2 = Listado.Where(x => x.id_menu_padre == idPadre && x.ID_MENU != x.id_menu_padre).ToList();
if (listado2.Count > 0)
{
foreach (MENU item in listado2)
{
lst.Add(item);
GMenuHijo(item.ID_MENU, ref lst);
}
}
}

I encountered this same problem. It would appear that jqGrid expects the data to be already sorted in the tree structure (i.e. it does not perform the sort at the client) but I may be wrong. Below are some extensions I created to perform a tree sort of a generic IEnumerable that contains objects with the specified ID and Parent ID properties. Objects will null in the Parent ID property are placed at the root.
public static class TreeSortExtensions
{
public static IEnumerable<T> OrderByTreeStructure<T>(
this IEnumerable<T> source,
string objectIDProperty,
string parentIDPropery)
{
IEnumerable<T> result = source;
if (!string.IsNullOrEmpty(objectIDProperty) && !string.IsNullOrEmpty(parentIDPropery))
{
result = source.GetChildrenOfTreeNode(null, objectIDProperty, parentIDPropery, true);
}
return result;
}
public static IEnumerable<T> GetChildrenOfTreeNode<T>(
this IEnumerable<T> source,
object parent,
string property,
string parentProperty,
bool recurse)
{
if (!string.IsNullOrEmpty(property) && !string.IsNullOrEmpty(parentProperty))
{
IEnumerable<T> children;
if (parent == null)
{
children = source.Where(x => x.GetPropertyValue(parentProperty) == null);
}
else
{
var parentIDValue = parent.GetPropertyValue(property);
children = source.Where(x => (x.GetPropertyValue(parentProperty) != null) &&
(x.GetPropertyValue(parentProperty).Equals(parentIDValue)));
}
foreach (T child in children)
{
yield return child;
if (recurse)
{
var grandChildren = source.GetChildrenOfTreeNode(child, property, parentProperty, true).ToArray();
foreach (T grandchild in grandChildren)
{
yield return grandchild;
}
}
}
}
}
public static object GetPropertyValue(this object obj, string property)
{
return obj.GetType().GetProperty(property).GetValue(obj, null);
}
}
Note that the "parent" argument is of type object and not T. This allows a null to be passed as the parent of root level objects.
Usage:
var result1 = someEnumerable.OrderByTreeStructure("SomeIDProperty", "SomeParentIDProperty");
var result2 = someDbContext.SomeTable.OrderByTreeStructure("ID", "ParentID");

Related

How to working with data from client side using Observables

I am using the Grid of Kendo (Angular 2) for Add/Edit/Delete a Row in the grid:
http://www.telerik.com/kendo-angular-ui/components/grid/editing/
In the original Code, the data is obtained from a rest service like this:
private fetch(action: string = "", data?: Product): Observable<Product[]> {
return this.jsonp
.get(`http://demos.telerik.com/kendo-ui/service/Products/${action}? callback=JSONP_CALLBACK${this.serializeModels(data)}`)
.map(response => response.json());
}
But, I want to work with a array for add/edit/delete rows in memory. Next, I want to do click in the button submit and send the data (with all my changes) to the server.
My solution for this is like this:
https://gist.github.com/joedayz/9e318a47d06a7a8c2170017eb133a87e
Overview:
I declare an array:
private view: Array = [{ProductID: 1, ProductName: "pelotas", Discontinued: undefined, UnitsInStock: 80}];
and override the fetch method like this:
private fetch(action: string = "", data?: Product): Observable<Product[]> {
/*return this.jsonp
.get(`http://demos.telerik.com/kendo-ui/service/Products/${action}?callback=JSONP_CALLBACK${this.serializeModels(data)}`)
.map(response => response.json());*/
debugger;
if(action=="create"){
var product : Product = new Product(-1, data.ProductName, data.Discontinued, data.UnitsInStock);
this.view.push(product);
}else if(action=="update"){
var indice = this.view.indexOf(data);
if(indice>=0)
this.view[indice] = (JSON.parse(JSON.stringify(data)));
}else if(action=="destroy"){
var indice = this.view.indexOf(data);
if(indice>=0)
this.view.splice(indice, 1);
}
return Observable.of(this.view);
}
My Question is: Exists some way of communicate the create/update/delete of items in my array of a simple or reactive form to my grid?
As you are using in-memory array you do not need to use Observables. The Grid component is already bound to the array, thus it is just necessary to manipulate the data. For example:
export class AppComponent {
public dataItem: Product;
#ViewChild(GridEditFormComponent) protected editFormComponent: GridEditFormComponent;
private view: Array<Product> = [{ ProductID: 1, ProductName: "pelotas", Discontinued: undefined, UnitsInStock: 80 }];
public onEdit(dataItem: any): void {
this.dataItem = Object.assign({}, dataItem);
}
public onCancel(): void {
this.dataItem = undefined;
}
public addProduct(): void {
this.editFormComponent.addProduct();
}
public onSave(product: Product): void {
if (product.ProductID === undefined) {
this.createProduct(product);
} else {
this.saveProducts(product);
}
}
public onDelete(e: Product): void {
this.deleteProduct(e);
}
public saveProducts(data: Product): void {
var index = this.view.findIndex(x => x.ProductID === data.ProductID);
if (index !== -1) {
this.view = [
...this.view.slice(0, index),
data,
...this.view.slice(index + 1)
];
}
}
public createProduct(data: Product): void {
this.view = [...this.view, data];
}
public deleteProduct(data: Product): void {
this.view = this.view.filter(x => x.ProductID !== data.ProductID);
}
}

Display the 25K records from DB to JQGrid in a fastest manner

Currently, I am using the following Datahandler, which takes lots of time to load the data.
Could anybody send me a working sample which really works with huge amount of records.
Is there any way to bind the data directly to JSON ( I feel the for loop also taking time to load).
JQGridHandler.ahsx
<%# WebHandler Language="C#" Class="JQGridHandler" %>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public Int64 Col1;
public string Col2 ;
public string Col3 ;
public string Col4;
public Int64 Col5;
public Int64 Col6;
public Int64 Col7;
}
[Serializable]
public class User
{
public Int64 Col1 { get; set; }
public string Col2 { get; set; }
public string Col3 { get; set; }
public string Col4 { get; set; }
public Int64 Col5 { get; set; }
public Int64 Col6 { get; set; }
public Int64 Col7 { get; set; }
}
public class JQGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Collections.Specialized.NameValueCollection forms = context.Request.Form;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = forms.Get("_search");
string numberOfRows = forms.Get("rows");
string pageIndex = forms.Get("page");
string sortColumnName = forms.Get("sidx");
string sortOrderBy = forms.Get("sord");
string strOperation = forms.Get("oper");
int totalRecords;
Collection<User> users = new Collection<User>();
var provider = DbProviderFactories.GetFactory("Cassandra.Data.CqlProviderFactory");
var connection = provider.CreateConnection();
connection.ConnectionString = "Contact Points=localhost;Port=9042";
connection.Open();
var command = connection.CreateCommand();
string keyspaceName = "EmpTableSpace";
command = connection.CreateCommand();
command.CommandText = "select Col2, Col3, Col4, Col5, Col6, Col7 from " + keyspaceName + ".Emptable;";
DbDataReader reader = command.ExecuteReader();
User user;
int idx = 1;
while (reader.Read())
{
user = new User();
user.Col1 = idx++;
user.Col2 = Convert.ToString(reader["Col2"]);
user.Col3 = Convert.ToString(reader["Col3"]);
user.Col4 = String.Format("{0:MM/dd/yyyy HH:mm:ss}", reader["Col4"].ToString());
user.Col5 = Convert.ToInt16(reader["Col5"]);
user.Col6 = Convert.ToInt16(reader["Col6"]);
user.Col7 = Convert.ToInt16(reader["Col7"]);
users.Add(user);
}
totalRecords = Convert.ToInt32(reader["Col2"]);
string strResponse = string.Empty;
if (strOperation == null)
{
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
////else if (strOperation == "del")
////{
//// var query = Query.EQ("_id", forms.Get("Col2").ToString());
//// users.Remove(query);
//// strResponse = "Employee record successfully removed";
//// context.Response.Write(strResponse);
////}
else
{
string strOut = string.Empty;
AddEdit(forms, users, out strOut);
context.Response.Write(strOut);
}
}
private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
foreach (User user in users)
{
JQGridRow row = new JQGridRow();
row.Col1 = Convert.ToInt64(user.Col1);
row.Col2 = user.Col2;
row.Col3 = user.Col3;
row.Col4 = user.Col4;
row.Col5 = user.Col5;
row.Col6 = user.Col6;
row.Col7 = user.Col7;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = totalRecords / totalRecords;
result.records = totalRecords;
return new JavaScriptSerializer().Serialize(result);
}
public bool IsReusable
{
get
{
return false;
}
}
private void AddEdit(NameValueCollection forms,Collection<User> users, out string strResponse)
{
string strOperation = forms.Get("oper");
Int64 strRowID = 0;
if (strOperation == "add")
{
strRowID = Convert.ToInt64(forms.Get("Col1"));
}
else if (strOperation == "edit")
{
var result = users.AsQueryable<User>().Select(c => c.Col2).Max();
strRowID = (Convert.ToInt32(result) + 1);
}
string strCol2 = forms.Get("Col2").ToString();
string strCol3 = forms.Get("Col3").ToString();
string dtCol4 = String.Format("{0:MM/dd/yyyy HH:mm:ss}", forms.Get("Col4").ToString());
int intCol5 = Convert.ToInt16(forms.Get("Col5"));
int intCol6 = Convert.ToInt16(forms.Get("Col6"));
int intCol7 = Convert.ToInt16(forms.Get("Col7"));
User objEmp = new User();
objEmp.Col1 = strRowID;
objEmp.Col2 = strCol2;
objEmp.Col3 = strCol3;
objEmp.Col4 = dtCol4;
objEmp.Col5 = intCol5;
objEmp.Col6 = intCol6;
objEmp.Col7 = intCol7;
users.Add(objEmp);
strResponse = "Record(s) successfully updated";
}
}
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
LOADING DATA IN JQGRID
</h2>
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
<script type="text/javascript">
jQuery("#jQGridDemo").jqGrid({
url: 'JQGridHandler.ashx',
datatype: "json",
colNames: ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7'],
colModel: [
{ name: 'Col1', index: 'Col1', width: 20, sortable: true },
{ name: 'Col2', width: 30, sortable: true },
{ name: 'Col3', width: 50, sortable: true },
{ name: 'Col4', width: 55, sortable: true },
{ name: 'Col5', width: 30, sortable: true },
{ name: 'Col6', width: 30, sortable: true },
{ name: 'Col7', width: 30, sortable: true }
],
rowNum: 10,
mtype: 'GET',
height: 450,
width: 1200,
scroll: true,
loadonce: false,
rowList: [1000, 2000, 3000],
prmNames: { npage: 'npage' },
pager: '#jQGridDemoPager',
sortname: 'Col2',
viewrecords: true,
sortorder: 'desc',
caption: "Response Times",
editurl: 'JQGridHandler.ashx'
});
$('#jQGridDemo').jqGrid('navGrid', '#jQGridDemoPager',
{
refreshstate: 'current',
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
},
{sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni']},
{
closeOnEscape: true,//Closes the popup on pressing escape key
reloadAfterSubmit: true,
multipleSearch:true,
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');//Reloads the grid after edit
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [false, response.responseText]//Captures and displays the response text on th Edit window
}
},
editData: {
EmpId: function () {
var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
closeAfterAdd: true,//Closes the add window after add
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [false, response.responseText]
}
}
},
{ //DELETE
closeOnEscape: true,
closeAfterDelete: true,
reloadAfterSubmit: true,
closeOnEscape: true,
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGridDemo").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
},
delData: {
EmpId: function () {
var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{//SEARCH
closeOnEscape: true
}
);
</script>
</asp:Content>
It's important to understand, that if one uses loadonce: true option (and datatype: "json" or datatype: "xml") or if datatype is neither "json" nor "xml" then jqGrid makes filtering, sorting and searching on the client side. You use loadonce: false (which is default value of jqGrid) so jqGrid just send the information about the filter to the server. The server is responsible to filter the data and the return the requested page of the filtered results. The old answer or this one provides demos with server side filtering in C#.
Your current server code don't have server side implementation of sorting, filtering and paging. So I would recommend you first of all to try to use loadonce: true without scroll: true (just remove it). I recommend you additionally to add gridview: true option to improve performance (see the answer). If you would have reliable performance you will don't need to make modification of your server code.

True scrolling data in JQGrid not working with MVC 3

Can someone help me with this issue?
I have a jqgrid(4.4.0) and I want to implement true scrolling. The problem is that it only loads datarows once, meaning the first page only. So when I scroll, it doesn't fetch the other pages. I have checked this issue and still not working.
Here is the jqgrid:
jQuery("#deptProjectsGrid").jqGrid({
url: '#Url.Action("GetUserProjects", "TimesheetByWeek")',
datatype: 'json',
mtype: 'GET',
colNames: ['Projekt', 'Oprettet af'],
colModel: [
{ name: 'project', index: 'project', sortable: true, align: 'left' },
{ name: 'creator', index: 'creator', align: 'left' }
],
height: 300,
width: 250,
altRows: true,
pager: '#pager1',
scroll: 1,
rowNum: 15,
rownumbers: true,
viewrecords: true,
sortname: 'project',
sortorder: 'desc',
gridview: true,
caption: "Projekter",
onSelectRow: function (ids) {
if (ids == null) {
ids = 0;
if ($taskgrid.jqGrid('getGridParam', 'records') > 0) {
$taskgrid.jqGrid('setGridParam', { url: '#Url.Action("GetProjectTasks", "TimesheetByWeek")/' + ids });
$taskgrid.jqGrid('setCaption', "No Tasks " + ids).trigger('reloadGrid');
}
} else {
var data = $("#deptProjectsGrid").getRowData(ids);
$taskgrid.jqGrid('setGridParam', { url: '#Url.Action("GetProjectTasks", "TimesheetByWeek")/' + ids });
$taskgrid.jqGrid('setCaption', "Tasks for " + data.project).trigger('reloadGrid');
}
}
});
The controller action looks like this:
public JsonResult GetUserProjects(int page, int rows, string search, string sidx, string sord)
{
try
{
using (DanishEntities db = new DanishEntities())
{
int totalRecords = 0;
var allProjectEntities = _projectRepository.GetProjectsPaged(page, rows, out totalRecords, db);
var projects = Mapper.Map<List<Project>, List<ProjectModel>>(allProjectEntities);
var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
var jsonData = new
{
total = rows,
page = page++,
records = totalRecords,
rows = (
from p in projects
select new
{
id = p.ID,
cell = new object[] { p.Name, "john doe" }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
throw;
}
}
and the query is:
public List<Project> GetProjectsPaged(int page, int rows, out int totalCount, DanishEntities dbContext)
{
List<Project> pagedProjectEntities = new List<Project>();
try
{
totalCount = dbContext.Projects.Count();
pagedProjectEntities = dbContext.Projects
.OrderBy(p => p.ID)
.Skip((page-1) * rows)
.Take(rows)
.ToList();
}
catch (Exception)
{
throw;
}
return pagedProjectEntities;
}
I have wasted 4 hours of my life trying to figure this out and I just can't see the problem. I have even set "total = totalPages" in the controller action but nothing is working. Help please!!
Just another quick question on jqGrid: How do I disable "rowNum" in a jqGrid so that the grid shows all available rows returned by the query in the data set?

How to navigate in jqgrid

i'm starter in jqgrid, i write this code for create and fill jqgrid(i'm use repository pattrn in asp.net )
namespace Clearance.Helper
{
using System;
public class JQGridRow
{
public int id;
public string[] cell;
}
}
namespace Clearance.Helper
{
public class JQGridResults
{
public int Page { get; set; }
public int Total { get; set; }
public int Records { get; set; }
public JQGridRow[] rows;
}
}
namespace Clearance.Business
{
using System;
using System.Linq;
using Model;
using Clearance.Repository;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Clearance.Helper;
public class TransportTypesBusiness : GenericBusiness<CLEARANCEEntities, TRANSPORT_TYPES>
{
public List<TRANSPORT_TYPES> GetAll(int pageSize, int pageIndex)
{
var repository = new TransportTypesRepository(this.Context);
return (List<TRANSPORT_TYPES>) repository.GetAll().OrderBy(c => c.TRANSPORT_ID).Skip(pageIndex * pageSize).Take(pageSize);
}
public string BuildJQGridResults(int numberOfRows = 0, int pageIndex = 0, int totalRecords = 0)
{
var result = new JQGridResults();
var rows = new List<JQGridRow>();
var list = GetAll(numberOfRows, pageIndex);
int li = list.Count();
totalRecords = list.Count();
foreach (var item in list)
{
var row = new JQGridRow { id = item.TRANSPORT_ID, cell = new string[4] };
row.cell[0] = item.TRANSPORT_ID.ToString();
row.cell[1] = item.TRANSPORT_NAME;
row.cell[2] = item.TRANSPORT_ABBR;
row.cell[3] = item.REMARK;
rows.Add(row);
}
result.rows = rows.ToArray();
if ((numberOfRows != 0) && (pageIndex != 0) && (totalRecords != 0))
{
result.Page = pageIndex;
result.Total = (totalRecords + numberOfRows - 1) / numberOfRows;
result.Records = totalRecords;
}
return new JavaScriptSerializer().Serialize(result);
}
}}
and js code
$(function () {
var grid = $('#list');
grid.jqGrid({
url: 'jQGridHandler.ashx',
editurl: 'jQGridHandler.ashx',
postData: { ActionPage: 'TransportType', Action: 'Fill' },
ajaxGridOptions: { cache: false },
datatype: 'json',
height: 'auto',
colNames: ['TRANSPORT_ID', 'TRANSPORT_NAME', 'TRANSPORT_ABBR', 'REMARK'],
colModel: [
{ name: 'TRANSPORT_ID', index: 'TRANSPORT_ID', key: true, hidden: true, editable: false },
{ name: 'TRANSPORT_NAME', width: 200, sortable: true, editable: true },
{ name: 'TRANSPORT_ABBR', width: 100, sortable: true, editable: true },
{ name: 'REMARK', width: 100, sortable: true, editable: true }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager',
prmNames: { nd: null },
gridview: true,
sortname: 'TRANSPORT_ID',
viewrecords: true,
caption: '',
rownumbers: true
});
when jqgrid load data set current page is 0 and icon next and privice is enable. please help me. thanks all
The problem with page number can be easy to solved. The class JQGridResults has properties Page, Total, Records and rows, but default names which jqGrid wait for are page, total, records and rows. So the rows are the only property which will be read correctly.
To fix the problem you can either rename the property in the JQGridResults or include the following additional parameter in jqGrid:
jsonReader: {page: "Page", total: "Total", records: "Records"}
More additional information (inclusive full working Visual Studio demo project) about the usage of jqGrid together with ASHX handler you can find in the answer.

Difficulty sorting Linq expression with jqGrid

I have seen this code Sortable JqGrid using LINQ to MySQL (DbLinq) and Dynamic LINQ - Orderby doesn't work
and trying to make it work. But it's giving error:
Cannot order by type 'System.Object'
See the line in the code with Error Here.
[HttpPost]
public ActionResult MyGridData(string sidx, string sord, int page, int rows)
{
IQueryable<Company> repository = companyRepository.GetGridCompanies();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = repository.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// first sorting the data as IQueryable<Ticket> without converting ToList()
IQueryable<Company> orderdData = repository;
PropertyInfo propertyInfo = typeof(Company).GetProperty(sidx);
if (propertyInfo != null)
{
orderdData = String.Compare(sord, "desc", StringComparison.Ordinal) == 0 ?
(from x in repository
orderby propertyInfo.GetValue(x, null) descending
select x) :
(from x in repository
orderby propertyInfo.GetValue(x, null)
select x);
}
// paging of the results
IQueryable<Company> pagedData = orderdData
.Skip((page > 0 ? page - 1 : 0) * rows)
.Take(rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from o in pagedData //ERROR HERE : Cannot order by type 'System.Object'
select new
{
i = o.companyID,
cell = new string[] { o.companyID.ToString(), o.companyName, o.companyCity, o.companyState }
}).ToArray()
};
return Json(jsonData);
}
public class CompanyRepository
{
SandGridDataContext db = new SandGridDataContext();
// Send Total Number of Companies
public int CompanyCount()
{
return db.Companies.Count();
}
public IQueryable<Company> GetGridCompanies()
{
return db.Companies;
}
public Company GetCompany(int id)
{
return db.Companies.SingleOrDefault(d => d.companyID == id);
}
}
//JS code
jQuery().ready(function () {
var lastSel;
jQuery("#sandgrid").jqGrid({
url: '/JQSandbox/MyGridData/',
datatype: 'json',
mtype: 'POST',
height: 255,
width: 640,
colNames: ['Index', 'Name', 'City', 'State'],
colModel: [
{ name: 'companyID', index: 'companyID', width: 5 },
{ name: 'companyName', index: 'companyName', width: 30 },
{ name: 'companyCity', index: 'companyCity', width: 30 },
{ name: 'companyState', index: 'companyState', width: 4, sortable: false}],
pager: jQuery('#sandgridp'),
rowNum: 5,
rowList: [5, 10, 20, 50],
sortname: 'companyID',
sortorder: "desc",
viewrecords: true,
altRows: true,
caption: 'Sandbox Grid',
ondblClickRow: function (id) {
if (id && id !== lastSel) {
jQuery('#sandgrid').restoreRow(lastSel);
lastSel = id;
alert("You've seleted " + id);
}
},
subGrid: true,
subGridUrl: '/JQSandbox/MySubGridData/',
subGridModel: [
{
name: ['Name', 'Department', 'Hire Date', 'Supervisor'],
width: [80, 20, 80, 10],
align: ['left', 'left', 'left', 'center'],
params: ['companyID']
}]
}).navGrid('#sandgridp', { edit: false, add: false, del: false });
//Company class is Linq to Sql entity with fields below.
companyID,
companyName,
companyCity,
companyState
I spent too much time to resolve this.
Please check Order LINQ by "string" name.

Resources