Wednesday, May 25, 2011

Jqgrid for MVC 2

Here i will put in code to demonstrate Jqgrid.This is one of the coolest grids available.There are many ways to implement this grid.There is a lot of documentation available for Jqgrid on its wiki,so i am not going to explain the stuff.The way i have implemented the grid is to have a search form and have ajax call made to the search controller and then let it return us a array data and that we feed directly to the grid.This grid will also have a double click event hooked up for all the rows returned.I have also used Block UI to block the page when we construct a dialog with all the information about the record.One problem i faced with Json is,the default max for JSon Serialization is very small,so i found a class LargeJSon on google which basically increases the default limit to
<jsonSerialization maxJsonLength="2147483644""></jsonSerialization>.

Here is the Main code

<script type="text/javascript" language="javascript">
$(document).ready(function() {


function Search() {
$(loading).show();
$.ajax({
type: "POST",
url: '<%=Url.Content("~/Search/Search")%>',
data: $("#SearchForm").serialize(),
datatype: 'json',
success: function(msg) {
if (msg != null) {
$("#Validation").hide();
var gridData = msg;
if (!loaded) {
loaded = LoadGridWithData(gridData);
}
else {
$("#list").GridUnload();
loaded = LoadGridWithData(gridData);
}
$(loading).hide();
}
},
error: function(xhr, status, error) {
var object = new Array();
object = xhr.responseText.split(';');
var response = '';
for (var i = 0; i < object.length; i++) {
var p = "<div>" + object[i] + "</div>";
response += p;
}
$("#Validation").html(response);
$("#Validation").show();
$(loading).hide();
}
});

}

var dialogOpen = false;

function LoadGridWithData(gridData) {
jQuery("#list").jqGrid({
sortable: true,
data: gridData,
datatype: 'local',
mtype: 'GET',
colNames: ['First Name', 'Middle Name', 'Last Name', 'Agent', 'State', 'Zip', 'Number', 'Type', 'Status', 'Date'],
colModel: [
{ name: 'FirstName', index: 'FirstName', width: 30, sorttype: 'text' },
{ name: 'MiddleName', index: 'MiddleName', width: 15, sorttype: 'text', align: 'left' },
{ name: 'LastName', index: 'LastName', width: 40, sorttype: 'text', align: 'left' },
{ name: 'Agent', index: 'Agent', width: 30, sorttype: 'int', align: 'left' },
{ name: 'State', index: 'State', width: 15, sorttype: 'text' },
{ name: 'Zip', index: 'Zip', width: 20, sorttype: 'int', align: 'left' },
{ name: 'Number', index: 'Number', width: 50, sorttype: 'int', align: 'left' },
{ name: 'Type', index: 'Type', width: 50, sorttype: 'text', align: 'left' },
{ name: 'Status', index: 'Status', width: 50, sorttype: 'text', align: 'left' },
{ name: 'Date', index: 'Date', width: 50, sorttype: 'date', resizable: false }
],
pager: '#pager',
rowNum: 20,
rowList: [5, 10, 20, 50],
gridview: true,
sortname: 'Number',
sortorder: "desc",
height: 400,
loadui: "enable",
loadtext: "Loading...",
autowidth: true,
rownumbers: true,
viewrecords: true,
caption: 'Quote Header Data',
ondblClickRow: function(id) {
$.blockUI({ message: "<h1>Retrieving Information. Please Wait...</h1>", timeout: 10000 });
var url = '<%= Url.Content("~/") %>' + "Search/Modal";
$.post(url, { Id: id }, function(response, status, xhr) {
if (status != "error") {
$.unblockUI();
$('#verificationedit-form').html(response).dialog("open");
}
else {
$.blockUI({ message: "<h1>Retrieving Failed.Please Try Again...</h1>" });
$('.blockOverlay').attr('title', 'Click to unblock').click($.unblockUI);
}
});
}
});
jQuery("#list").jqGrid('navGrid', '#pager', { del: false, add: false, edit: false, search: false });
return true;
}
}
</script>



<table id="list" cellpadding="0" cellspacing="0">
</table>
<div id="pager" style="text-align: center;">
</div>
<div id="verificationedit-form" title="Edit Verification Information">
</div>


//Controller


[HttpPost]
[EnableCompression]
public JsonResult Search(SearchModel searchModel)
{
LargeJsonResult result = new LargeJsonResult();

if (ModelState.IsValid)
{
List<GridModel> model = repository.Search(searchModel);
var jsonData =
(from pp in model
select new
{
id = pp.Id,
pp.FirstName,
pp.MiddleName,
pp.LastName,
pp.Agent,
pp.State,
pp.Zip,
pp.Number,
pp.Type,
pp.Status,
pp.Date
}).ToArray();

result.Data = jsonData;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
else
{
StringBuilder errorString = Utilities.BuildErrorMessageFromModelStateWithDelimiter(ModelState, ";");
Response.StatusCode = 500;
Response.Write(errorString.ToString());
return result;
}
}

Next time i will post the Jggrid code with inline editing.Happy Coding!!

No comments:

Post a Comment