RSS

Tag Archives: jqgrid

JqGrid+ Traditional asmx webservice + Multiple search + Sorting Using Custom Linq Extension Methods

I’m back to experimenting with jggrid again, this time trying to get server side multi search and sorting.

This time I am using asp.net and linq and traditional asmx web service. Why not WCF? I’m not sure, I just started down this road this time. WCF is the recommended way I gather, or maybe asp.net MVC.

I also needed a way to have a concise search strategy to allow searching across several column sand with different search operations (equal, not equal, contains)

I found this solution on code project that uses asp.net MVC   by Ilya Builuk. I included his helpers in my project (see project explorer below) and got the grid working –yay!!!

Image

So here’s the code – sarting with the html page, then the entities and classes representing the filters, then finally the asmx web service using the linq extension methods I got from Ilya Builuk

1st the html page


<!-- all the header html stuff here -->
<script type="text/javascript">


$(function() {
$.extend($.jgrid.defaults,
{
jsonReader: {
root: "d.rows", page: "d.page", total: "d.total", records: "d.records", repeatitems: false, cell: "", id: "0"
},
datatype: 'json',
ajaxGridOptions: { contentType: "application/json;charset=utf-8" },
mType: 'POST',
serializeGridData: function(postData) { return JSON.stringify(postData); }
});

$('#grid').jqGrid({
url: "/GridService.asmx/SearchGrid",
datatype: 'local',
colNames: ['ProductID', 'Name', 'ProductModel', 'Culture','Description'],
colModel: [
{ name: 'ProductID', width: 100, index: 'ProductId',
searchoptions: { sopt: ['eq', 'ne'] }
},
{ name: 'Name', index: 'Name',
searchoptions: { sopt: ['eq', 'ne', 'cn'] }
},
{ name: 'ProductModel', index: 'ProductModel',
searchoptions: { sopt: ['eq', 'ne', 'cn'] }
},
{ name: 'Culture', index: 'Culture',
searchoptions: { sopt: ['eq', 'ne', 'cn'] }
},
{ name: 'Description', index: 'Description',
searchoptions: { sopt: ['eq', 'ne', 'cn'] }
}
],
sortname: 'Name',
rowNum: 10,
rowList: [10, 20, 50],
sortorder: "asc",
pager: 'pager',
caption: 'Product Descriptions',
viewrecords: true,
mtype: 'POST'
});
$('#grid').jqGrid('navGrid', '#pager', { add: false, edit: false, view: false, del: false,
beforeRefresh:function(){
$('#grid').jqGrid('setGridParam', { datatype: 'local' }).trigger('reloadGrid');
}
// refresh:false
},
{}, {}, {},
{ multipleSearch: true,
closeAfterSearch: true,
closeOnEscape:true,
onSearch: function() {
//console.log('search clicked');
$('#grid').jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
},
onReset: function() {
$('#grid').jqGrid('setGridParam', { datatype: 'local' }).trigger('reloadGrid');
}
});
$('#grid').jqGrid('gridResize');
$('#loadGrid').button();
$('#loadGrid').click(function() {
$('#grid').jqGrid('setGridParam', { url: "/GridService.asmx/GetGrid", datatype: 'json' }).trigger('reloadGrid');
});
//$('#grid').jqGrid('setGridParam', {datatype: 'json' }).trigger('reloadGrid');

});


</script>

</head>
<body>

<input id= "loadGrid" type="button" value="Load Grid" />

<table id="grid" />
<div id="pager" />

</body>
</html>

The entities and filter objects


namespace JqGridFilter.Data
{
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string ProductModel { get; set; }
public string Culture { get; set; }
public string Description { get; set; }

}
public class JgGrid
{
public List<vProductAndDescription> rows;
public int page { get; set; }
public int total { get; set; }
public int records { get; set; }

public JgGrid()
{

}
public JgGrid(int page, IQueryable<vProductAndDescription> products, int rows)
{
this.page = page;
this.records = products.Count();
this.total = (int)Math.Ceiling((double)this.records / rows);
this.rows = products.Skip(page * rows - rows).Take(rows).ToList();
}

}
[Serializable()]
public class rule
{
public string field { get; set; }
public string op { get; set; }
public string data { get; set; }
}
[Serializable()]
public class filters
{
public string groupOp { get; set; }
public List<rule> rules;
}
}

Then here comes the web service


namespace JqGridFilter
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://wwww.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JgGrid SearchGrid(int rows, int page, string sidx, string sord,string filters)
{
AdvWorksDataContext dc = new AdvWorksDataContext();
JavaScriptSerializer serializer = new JavaScriptSerializer();
filters f = serializer.Deserialize<filters>(filters);

var p = dc.vProductAndDescriptions.AsQueryable();
if (f.groupOp == "AND")
foreach (var rule in f.rules)
p = p.Where<vProductAndDescription>(
rule.field, rule.data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)
);
else
{
//Or
var temp = (new List<vProductAndDescription>()).AsQueryable();
foreach (var rule in f.rules)
{
var t = p.Where<vProductAndDescription>(
rule.field, rule.data,
(WhereOperation)StringEnum.Parse(typeof(WhereOperation), rule.op)
);
temp = temp.Concat<vProductAndDescription>(t);
}
p = temp;
}
p = p.OrderBy<vProductAndDescription>(sidx, sord);

return new JgGrid(page, p, rows);
}
}
}

 
3 Comments

Posted by on March 23, 2012 in software

 

Tags: , , , , ,

Using a JQGrid as a subgrid

This weekend while experimenting with the javascript grid jqgrid, I decided to try out using a full grid as a subgrid.

Its really not that difficult given that the wiki on the jqgrid website shows how to do this. I just needed to tweak a few options to get it to work;

here is my code (php mysql back end):

1st, the html page


<!DOCTYPE html PUBLIC &amp;quot;-//W3C//DTD HTML 4.01 Transitional//EN&amp;quot; &amp;quot;http://www.w3.org/TR/html4/loose.dtd&amp;quot;>
<html>
<head>
<title>JQGrid Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../dojoproject/jquery-ui-1.8.16.custom/css/start/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" type="text/css" href="jquery.jqGrid-4.3.1/css/ui.jqgrid.css">
<style type="text/css">
html, body {
margin: 0;
padding: 0;
font-size: 90%;
}
</style>

<script type="text/javascript" src="../dojoproject/jquery-ui-1.8.16.custom/js/jquery-1.6.2.min.js" ></script>
<script type="text/javascript" src="../dojoproject/jquery-ui-1.8.16.custom/js/jquery-ui-1.8.16.custom.min.js" ></script>
<script type="text/javascript" src="jquery.jqGrid-4.3.1/js/i18n/grid.locale-en.js" ></script>
<script type="text/javascript" src="jquery.jqGrid-4.3.1/js/jquery.jqGrid.min.js" ></script>
<script type="text/javascript" src="../dojoproject/jqGrid-4.1.2/js/JSON-js/json2.js" ></script>
<script>

$(function() {

  $('#table').jqGrid({
    jsonReader : {
      repeatitems: false,
      cell:"",
      id:"0"
    },
    height:'auto',
    url:'/jqgrid/orders.php',
    datatype: 'json',
    mtype: 'GET',
    rownumbers:true,
    rownumWidth:35,
    colNames:['OrderID','CustomerID','EmployeeID','OrderDate','ShipVia','Freight','ShipName','ShipAddress'],
    colModel :[
      {name:'OrderID', index:'OrderID',search:false,sorttype:'integer'},
      {name:'CustomerID', index:'CustomerID'},
      {name:'EmployeeID', index:'EmployeeID'},
      {name:'OrderDate', index:'OrderDate'},
      {name:'ShipVia', index:'ShipVia'},
      {name:'Freight', index:'Freight'},
      {name:'ShipName', index:'ShipName'},
      {name:'ShipAddress', index:'ShipAddress'},
    ],
    sortname: 'OrderID ',
    rowNum:10,
    sortorder: 'asc',
    width:'100%',
    height:'200',
    viewrecords: true,
    gridview: true,
    caption: 'NorthWind Orders',
    scrollOffset:18,
    multiselect:true,
    pager:'pager'
    ,cellEdit:true,
    cellsubmit:'clientArray',
    afterSaveCell:function(rowid, cellname, value, iRow, iCol){
    },
subGrid:true,
subGridRowExpanded: function(subgrid_id, row_id) {
  var subgrid_table_id;
  subgrid_table_id = subgrid_id+"_t";

  $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table>");
  $("#"+subgrid_table_id).jqGrid({
    jsonReader : {
      repeatitems: false,
      cell:"",
      id:"0"
     },
    url:"order_details.php?id="+row_id,
    datatype: "json",
    colNames: ['OrderID','ProductID','UnitPrice','Quantity','Discount'],
    colModel: [
      {name:"OrderID",index:"OrderID",width:80,},
      {name:"ProductID",index:"ProductID",width:130},
      {name:"UnitPrice",index:"UnitPrice",width:80,align:"right"},
      {name:"Quantity",index:"Quantity",width:80,align:"right"},
      {name:"Discount",index:"Discount",width:100,align:"right"}
    ],
    height: '100%',
    rowNum:20,
   });
  }
 });
});

</script>
</head>
<body>
<table id='table'></table>
<div id='pager'></div>
</body>
</html>

Then, the orders.php

<?php
header('Content-type: application/json');

Class jqGridObject

{
public $page;
public $total;
public $records;
public $rows;
}

$page = $_GET['page'];
$rows = $_GET['rows'];
$arrayOrders = array();
$mysqli =  new mysqli('localhost','root','','northwind');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
};
$resultAll = $mysqli->query('select OrderID,CustomerID,EmployeeID,OrderDate,ShipVia,Freight,ShipName,
ShipAddress from orders');
$records = $resultAll->num_rows;
$total = ceil($records/$rows);
$skip = $page*$rows - $rows;
$queryLtd ='select OrderID,CustomerID,EmployeeID,OrderDate,ShipVia,Freight,ShipName,
ShipAddress from orders LIMIT '.$skip.','.$rows;
if (!$result = $mysqli->query($queryLtd))
{
echo "error\n";
} else {
while ($obj = $result->fetch_object()) {
array_push($arrayOrders,$obj);
};

$myjqGrid = new jqGridObject();
$myjqGrid->total = $total;
$myjqGrid->page = $page;
$myjqGrid->records = $records;
$myjqGrid->rows = $arrayOrders;

echo json_encode($myjqGrid);
}
?>
Then order_details.php
<?php

header('Content-type: application/json');

Class jqGridObject

{

public $page;
public $total;
public $records;
public $rows;
}

$id = $_GET['id'] ;
$rows = $_GET['rows'];
$page = $_GET['page'];
$arrayDetails = array();

$mysqli =  new mysqli('localhost','root','','northwind');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
};

$resultAll = $mysqli->query('select OrderID,ProductID,UnitPrice,Quantity,Discount from order_details where orderid = '.$id);
$records = $resultAll->num_rows;
$total = ceil($records/$rows);
$skip = $page*$rows - $rows;
$queryLtd = 'select OrderID,ProductID,UnitPrice,Quantity,
Discount from order_details where orderid = '.$id.' LIMIT '.$skip.','.$rows;

if (!$result = $mysqli->query($queryLtd))

{

echo "error\n";

} else {

while ($obj = $result->fetch_object()) {
  array_push($arrayDetails,$obj);
  }
$myjqGrid = new jqGridObject();
$myjqGrid->total = $total;
$myjqGrid->page = $page;
$myjqGrid->page = $page;
$myjqGrid->records = $records;
$myjqGrid->rows = $arrayDetails;
echo json_encode($myjqGrid);

}

?>

</div>
<div>
</div>

 
11 Comments

Posted by on February 19, 2012 in software

 

Tags: , , ,