JQGrid is not working in ASP.net mvc 4? - model-view-controller

This is controller code:
using JQGird.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JQGird.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult EmployeeDetail()
{
Database1Entities db = new Database1Entities();
var employeedata = db.Empployees.Select(data => new
{
data.Id,
data.Name,
data.Designation,
data.Address,
data.Salary
});
var jsondat = new
{
total = 1,
page = 1,
records = db.Empployees.ToList().Count,
rows = employeedata
};
return Json(jsondat, JsonRequestBehavior.AllowGet);
}
}
}
and this is view of index action method
#{
ViewBag.Title = "Index";
}
<header>
<script>
$(document).ready(function () {
$('#grid').jqGrid({
url: '/Home/EmployeeDetails',
datatype: 'json',
myType: 'GET',
colNames: ['Id', 'Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' },
{ name: 'Designation', index: 'Designation' },
{ name: 'Address', index: 'Address' },
{ name: 'Salary', index: 'Salary' }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
reocords: 'records',
id: '0',
repeatitems: false
},
pager: $('#pager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
</header>
<h1>Records of employees</h1>
<div>
<table id="grid">
</table>
<div id="pager"></div>
</div>
When i run the application, i t only show data. I have also check that the Json data is coming successffully to the view but jqgrid is not working. What mistakes i am doing?
HTML of the page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.5.3.js"></script>
</head>
<body>
<h1>Records of employees</h1>
<div>
<table id="grid">
</table>
<div id="pager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#grid').jqGrid({
url: '/Home/EmployeeDetail',
datatype: 'json',
//myType: 'GET',
loadonce: true,
colNames: ['Id', 'Name', 'Designation', 'Address', 'Salary'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' },
{ name: 'Designation', index: 'Designation' },
{ name: 'Address', index: 'Address' },
{ name: 'Salary', index: 'Salary' }
],
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
reocords: 'records',
id: '0',
repeatitems: false
},
pager: $('#pager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<link href="/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/i18n/grid.locale-en.js"></script>
<script src="/Scripts/jquery.jqGrid.min.js"></script>
<script src="/Scripts/jquery.jqGrid.js"></script>
</body>
</html>

The HTML page have wrong order of JavaScripts which you includes.
It's important to understand that jqGrid is jQuery plugin. So one have to include first jQuery and only then one can includes jqGrid JavaScript files.
In the same way you use $(document).ready(function () {...}); which contains $ and .ready defined by jQuery, but you use the code before you included jQuery file jquery-1.9.1.min.js.
The next error: you included both non-minimized jqGrid jquery.jqGrid.js and then minimized version of the same file jquery.jqGrid.min.js. It's wrong. You should include only one from the files.
One more problem could exist in the order of the main jqGrid file (jquery.jqGrid.min.js, jquery.jqGrid.js or jquery.jqGrid.src.js) and the corresponding locale file grid.locale-en.js. There are different requirements for different versions of jqGrid and different forks, but the recommended order which works in all versions of jqGrid is: first include locale file (like grid.locale-en.js) and then the main jqGrid file (like jquery.jqGrid.min.js).
you skipped <body>...</body> after </header>.
The code of EmployeeDetail action don't uses any parameters which jqGrid send. You don't implemented any paging and sorting in the server code. Instead of that you just return all data at once. You should use loadonce: true options in the case. jqGrid will load all the data and then it will use sorting, paging and filtering on the client side. I hope that you use jqGrid in version higher as 3.7 which implemented support of loadonce: true. If you use loadonce: true option then the total, page and records properties of the server response will be ignored. Thus you can reduce the code of the server side and use return Json(employeedata, JsonRequestBehavior.AllowGet); instead of return Json(jsondat, JsonRequestBehavior.AllowGet);.
There are no myType option, but there are exist mtype option which default value is 'GET'. So you should remove myType: 'GET' option which will be ignored by jqGrid.
Some options of jqGrid can depend from the version of jqGrid which you use. I would recommend you to use gridview: true, autoencode: true, height: "auto". I would recommend you to remove unneeded index properties from all columns defined in colModel. Instead of that you can add key: true option for Id column. It will inform jqGrid to use the values from the columns as the values of id attribute of the rows (id of <td> elements). The jsonReader can be removed or you can use jsonReader: { repeatitems: false } or jsonReader: { repeatitems: false, root: function (obj) { return obj; } }. If you use recent version of jqGrid then no jsonReader will be required.
I mentioned above multiple times about versions which you use. I would recommend you to update jQuery 1.9.1 which you use currently to jQuery 1.11.3 or 2.1.4. Moreover I would recommend you to use the latest version of free jqGrid which you can get either from NuGet (see here), used URLs from CDN (see the wiki article) or to download the latest sources from GitHub directly.

Related

uncaught exception: jqGrid - No such method: GridUnload

THE PLAN
I have a page with a jqGrid on it - this grid should be able to load one of three json payloads that are of the same type - just different filters. The data that loads is based on the button one clicks (In Planning, Approved, Completed).
THE PROBLEM
The problem I am having is when I reference $("#jobGrid").jqGrid('GridUnload'); I get an "uncaught exception: jqGrid - No such method: GridUnload".
THE CODE
The following libraries are loaded - basically I grabbed them all trying to get $("#jobGrid").jqGrid('GridUnload'); to fire
<!-- jqGrid Resources-->
<script type="text/ecmascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/js/i18n/grid.locale-en.js"></script>
<script type="text/ecmascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/src/grid.base.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/src/grid.common.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/src/grid.formedit.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/src/jquery.fmatter.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/src/grid.jqueryui.js"></script>
<script type="text/javascript" src="http://cdn.cov.com/jqGrid_JS_5.0.0/plugins/grid.addons.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://cdn.cov.com/jqGrid_JS_5.0.0/css/ui.jqgrid-bootstrap.css" />
JavaScript function where exception occurs. Note: When this method is fired, data already exists in the grid
// Approved Filter
var approvedFilter = function () {
// Ready Up Defaults
$.jgrid.defaults.width = $("#jobGridContainer").width();
$.jgrid.defaults.responsive = true;
// Reset Data (Grid has data in it already
$("#jobGrid").jqGrid('GridUnload');
$("#jobGrid").jqGrid({
url: RestService.GetApprovedJobsService(),
mtype: "GET",
styleUI: 'Bootstrap',
datatype: "json",
colModel: [
{ label: 'JobNumber', name: 'JobNumber', key: true, width: 75 },
{ label: 'Job Name', name: 'JobName', width: 150 },
{ label: 'Request State', name: 'JobState', width: 150 },
{ label: 'Status', name: 'JobStatus', width: 150 },
{ label: 'Request By', name: 'JobRequestor', width: 150 },
{ label: 'Last Modified', name: 'LastModifiedDate' }
],
viewrecords: true,
height: 375,
rowNum: 10,
loadonce: true,
pager: "#jqGridPager",
caption: "Showing Approved Requests. Click row to view details",
onSelectRow: function (rowid, selected) {
if (rowid != null) {
document.location.href = getAppRootUrl() + "/Service/Job/" + rowid;
}
}
});
}
Any suggestions or help would be greatly appreciated
You use Guriddo jqGrid JS which have some incompatibility with previous versions of jqGrid (see the release notes of Guriddo jqGrid JS 4.8 for more information). Another fork of jqGrid - free jqGrid don't have the problem with GridUnload method.
If you need to use GridUnload or GridDestroy in Guriddo jqGrid JS then you can't use more $("#jobGrid").jqGrid('GridUnload');. Instead of that you should use
$.jgrid.gridUnload("jobGrid"); // id of grid as parameter
Another common remark to your code. You included first jquery.jqGrid.min.js and then grid.base.js, grid.common.js and other. It's wrong. jquery.jqGrid.min.js includes all the modules in minimized form. It's wrong to include the same modules multiple times.
For whatever reason Guriddo decided remove $("#gridid").jqGrid("GridUnload") from the new grid. For us it created an upward compatibility issue, especially since the jQuery element is passed as a parameter. We have elected to just put it back using the following code on startup.
if ($.fn.jqGrid["GridUnload"] === undefined) {
$.fn.jqGrid["GridUnload"] = $.jgrid.gridUnload;
}

jqGrid load in MVC

I'm new in jqgrid. I try to use jqgrid in my mvc project. I'm using the following code for mapping the data to grid. But its not working. The function GetJqGridData is loading first in my MVC project.
Below is code for Controler.
public ActionResult GetJqGridData()
{
var jqGridData = new JqGridObject()
{
Data = GetSomeSampleData(),
Page = "1",
PageSize = 3, // u can change this !
SortColumn = "1",
SortOrder = "asc"
};
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
Below is code for VIEW.
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<link href="../../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#myGrid").jqGrid({
url: '#Url.Action("GetJqGridData")',
datatype: 'json',
myType: 'POST',
colNames: ['Id', 'Name'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' }
],
jsonReader: {
root: 'Data',
id: 'id',
repeatitems: false
},
pager: $('#myPager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<table id="myGrid"></table>
<div id="myPager"></div>
This is result i'm getting
Thanks
Bobbin
Try using the following json format:
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
for more informations about the format, take a look in this link : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data

Implementing DoJo enhanced Grid with Json

I have been trying to implement DoJo Enhanced Grid with Json and I have not been successful thus far.
This is what I have done so far;
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:util="urn:jsptagdir:/WEB-INF/tags/util" xmlns:spring="http://www.springframework.org/tags" version="2.0">
<jsp:output omit-xml-declaration="yes"/>
<spring:url value="/students/listdata" var="mydatasource"/>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.grid.enhanced.plugins.IndirectSelection");
dojo.require("dijit.form.Button");
dojo.require("dojo.data.ItemFileReadStore");
dojo.addOnLoad(function() {
dojo.parser.parse();
loadGrid(dataGrid);
});
function loadGrid(dataGrid) {
dojo.xhrGet({
url: "${mydatasource}",
load: function(data, ioArgs) {
dataGrid.setStore(
new dojo.data.ItemFileReadStore(
{data: {items : data}})
);
},
error: function(error) {
console.log("loading of grid data failed. Exception...", error);
}
});
}
</script>
<util:panel id="titlePane" title="Course List">
<div id="addButton" dojoType="dijit.form.Button">
Add
</div>
<div id="deleteButton" dojoType="dijit.form.Button">
Delete
</div>
<div id="grid" jsId="dataGrid" dojoType="dojox.grid.EnhancedGrid"
structure ="[
{ field: 'id', name: 'ID', width: '55px' },
{ field: 'firstName', name: 'First Name', width: '230px' },
{ field: 'lastName', name: 'Last Name', width: '50px' },
{ field: 'gender', name: 'Gender', width: '145px'}
]"
autoWidth="true"
autoHeight="true"
plugins="{indirectSelection: true}"
selectionMode="single">
</div>
</util:panel>
As you can see, I am getting the Json String via the AJAX call by DOJO. The grid is generating however, it is not being populated with data. Only two check boxes comes up in the grid...
Is there anything that I'm doing wrongly?
I have never used the EnhancedGrid, but for a regular grid I did this by creating the store declaratively, attaching its ID to the grid (via store=... attribute in the HTML), and then when I wanted to refresh the grid with new store info, called:
grid.setStore(...,null,null);
found out the problem to the grid not loading data.
Actually I needed to handle the data as a Json String.
below is copy of the code that works:
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.grid.enhanced.plugins.IndirectSelection");
dojo.require("dijit.form.Button");
dojo.require("dojo.data.ItemFileReadStore");
dojo.addOnLoad(function() {
dojo.parser.parse();
loadGrid(dataGrid);
});
function loadGrid(dataGrid) {
dojo.xhrGet({
url: "${mydatasource}",
handleAs: "json",
load: function(data, ioArgs) {
dataGrid.setStore(
new dojo.data.ItemFileReadStore(
{data: {items : data}})
);
},
error: function(error) {
console.log("loading of grid data failed. Exception...", error);
}
});
}
</script>

Trouble With Ext.Load Not Finding Required Files

I'm trying to learn the new MVC architecture that ExtJS 4 is using and I'm having some serious issues. Here's what I get when I load the page (Chrome JS console):
ext-all-debug.js:3713[Ext.Loader] Synchronously loading 'Exercise.controller.Users'; consider adding Ext.require('Exercise.controller.Users') above Ext.onReady
ext-all-debug.js:4757An uncaught error was raised with the following data:
ext-all-debug.js:4758
Object
ext-all-debug.js:4764Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. Missing required class: Exercise.controller.Users
ext-all-debug.js:4771Uncaught Error
And here's a breakdown of my code:
index.php
<html>
<head>
<title></title>
<style>
#import url('libraries/extjs/resources/css/ext-all.css');
</style>
<script src = "libraries/extjs/bootstrap.js"></script>
<!--
<script src = "public/app/controller/Users.js"></script>
-->
<script src = "public/app/app.js"></script>
<script>
</script>
</head>
<body>
</body>
</html>
Now, I know that the included controller script is commented out. When I explicitly include the controller this message goes away. The reason I am asking about this is because I thought Ext.loader was supposed to take care of loading the required files for me.
The Users Controller
Ext.define('Exercise.controller.Users', {
extend: 'Ext.app.Controller',
init: function() {
console.log('Initialized Users! This happens before the Application launch function is called');
}
});
The Users Model
Ext.define('Exercise.model.User', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'int'
}, {
name: 'created_at',
type: 'date',
dateFormat: 'Y-m-d H:i:s'
}, {
name: 'member_id',
type: 'int'
}, {
name: 'first_name',
type: 'string'
}, {
name: 'last_name',
type: 'string'
}, {
name: 'password',
type: 'string'
}, {
name: 'dob',
type: 'date',
dateFormat: 'Y-m-d'
}, {
name: 'email_address',
type: 'string'
}, {
name: 'is_active',
type: 'int'
}],
proxy: {
type: 'ajax',
format: 'json',
url: '../../_dev/json_fixtures/users.json',
reader: {
type: 'json',
root: 'users'
},
root: 'users'
}
});
The User View
Exercise.views.user.list = Ext.extend(Ext.grid.Panel, {
store: Exercise.stores.users,
renderTo: Ext.getBody(),
columns:[{
header: 'Member ID',
dataIndex: 'member_id'
}, {
header: 'First Name',
dataIndex: 'first_name'
}, {
header: 'Last Name',
dataIndex: 'last_name'
}],
initComponent: function() {
Exercise.stores.users.load();
Exercise.views.UsersList.superclass.initComponent.apply(this, arguments);
}
});
The app.js File
Ext.application({
name: 'Exercise',
autoCreateViewport: true,
appFolder: 'app',
controllers: [
'Users'
],
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [
{
xtype: 'panel',
title: 'Users',
html : 'List of users will go here'
}
]
});
}
});
Side note: I've tried the solution found here to no avail and I've tried setting my apps appFolder property to both ../app and just app.
Thanks for the help with this.
have you read my question ?? how to make a "MVC Application" with extjs 4.0 beta 3?.. (it should works with final release )
it's because Ext.Loader is disabled by default...
Ext.Loader.setConfig({enabled:true});
I got that error, too. The Ext 4.0 MVC system doesn't use bootstrap.js -- instead, use ext-debug.js. When you're ready to go to production you'll replace ext-debug.js during the compilation phase.
Your HTML file should look like this:
<html>
<head>
<title></title>
<style>
#import url('libraries/extjs/resources/css/ext-all.css');
</style>
<!-- The MVC system needs ext-debug.js, not bootstrap.js -->
<script src = "libraries/extjs/ext-debug.js"></script>
<script src = "public/app/app.js"></script>
<script>
</script>
</head>
<body>
</body>
</html>

jgGrid not showing data using asp.Net MVC 3.0

I am having a problem showing json data returned from my view in jgGrid 4.0
in the head section I have
<script src="/Scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.lazyload.min.js" type="text/javascript"></script>
<script src="/Scripts/global.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
the body
$(document).ready(function () {
jQuery("#grid").jqGrid({
url: '#Url.Action("getusers", "dashboard",new {area="Security"})',
datatype: "json",
mtype: "GET",
colNames: ['Id', 'UserName'],
colModel: [
{ name: 'Id', index: 'Id',width: 200, align: 'left'},
{ name: 'UserName', index: 'UserName', width: 200, align: 'right' }
],
rowList: null,
pgbuttons: false,
pgtext: null,
viewrecords: false,
page:false,
caption: "Users"
});
});
here the Action code returning a json
public JsonResult GetUsers()
{
var repo = ObjectFactory.GetInstance<IRepository<User>>();
var result = (from x in repo.Query(x => x.ApplicationName == "DBM") select new {Id=x.Id, UserName=x.UserName}).ToArray();
return this.Json(result, JsonRequestBehavior.AllowGet);
}
}
I tested in both firefox and IE 9 the grid renders empty, no errors in firebug and data looks OK.
any hints would be appreciated.
jqGrid requires a specifc json format:
try this
var jsonData = new
{
total = (rowcount + paging.Size - 1) / paging.Size
page = paging.Page,
records = rowcount,
rows = (
from x in repo.Query(x => x.ApplicationName == "DBM")
select new
{
id=x.Id,
cell = new string[]
{
// the order of the columns here must match
x.Id,
x.UserName
}
})
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
See using jquery grid with asp.net mvc

Resources