ASP.NET MVC 3 jqGrid : grid renders json data in browser - json

I have problem with rendering jqGrid in ASP.net MVC 3.
Responsibility of ProductInfo action is to display list of product along with other latest product information (in ProductInfo view). When user click on any product link, ProductModelList action fetch all modellist of selected product & pass it to ProductModelList view where all jqGrid codes is written. But It renders row json data in browser as given bellow
{"total":null,"page":null,"records":9,"rows":[{"id":4,"cell":["3","Hyundai Accent"]},{"id":5,"cell":["3","Hyundai Santro"]},{"id":6,"cell":["3","Hyundai Santa Fe"]},{"id":7,"cell":["3","Hyundai i10"]},{"id":8,"cell":["3","Hyundai i20"]},{"id":9,"cell":["3","Hyundai Tucson"]},{"id":10,"cell":["3","Hyundai Verna Fluidic"]},{"id":11,"cell":["3","Hyundai EON"]},{"id":12,"cell":["3","New Hyundai Sonata"]}]}
following are controller and view:
public class Product : Controller
{
**//used to view product list**
public ActionResult ProductInfo()
{
ViewBag.ModelNameList = ModelRepository.GetModelName();
ViewBag.ModelVersionNameList = ModelVersionRepository.GetModelVersionName();
return View(new NewCarSearchContainer());
}
**//used to view modellist using jgGrid**
public JsonResult ProductModelList(int brandId, string sidx, string sord, int? page, int? rows)
{
var result = new
{
total = (ModelRepository.GetModelByBrandId(brandId).Count() + rows - 1) / rows,
page = page,
records = ModelRepository.GetModelByBrandId(brandId).Count(),
rows = (from model in ModelRepository.GetModelByBrandId(brandId)
select new
{
id = model.ModelId,
cell = new string[] { model.BrandId.ToString(), model.ModelName }
}).ToList()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
}
ProductModelList View:
=====================
<table id="jqgProducts">
</table>
<div id="jqgpProducts">
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#jqgProducts').jqGrid({
//url from wich data should be requested
url: '/Product/ProductModelList',
//type of data
datatype: 'json',
//url access method type
mtype: 'GET',
//columns names
colNames: ['id', 'ModelId', 'BrandName'],
//columns model
colModel: [
{ name: 'id', index: 'id', width: 40, align: 'left' },
{ name: 'ModelId', index: 'ModelId', width: 40, align: 'left' },
{ name: 'BrandName', index: 'BrandName', width: 40, align: 'left' },
],
//pager for grid
pager: $('#jqgpProducts'),
//number of rows per page
rowNum: 10,
//initial sorting column
sortname: 'ModelId',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
});
</script>
Please guide me?
Thanks,
Paul

The 'id' from the JSON data will be used to assign id attribute of the rows of the grid (id of <tr> elements). The ids must be unique on the page. All your current data contains the same id (id=3).
I would recommend you to download some working example (see the answer or this one) and modify it corresponds to your requirements.

Related

Unable to populate JSON Data in ExtJS grid (4.2.1) in Grails 2.1

The JSON data is in Correct Format ! yet i am unable to bind the JSON data with the Grid . I dont even get an Empty Grid ! The problem lies with my extjs code,I am a new to Extjs! i am using 4.2.1
I am Trying to Render the Grid in the upload.gsp div by using
renderTo: 'csvGrid' in the extjs Panel .
It simply Renders the JSON data but not inside the grid ! Please help !
Grails Contoller Actions Contoller Code
def index() {
render (view:"upload")
}
def upload() {
def uploadedCSVFile = request.getFile('file')
// def csvMap = [:]
// def listOfCsvMap = []
def materialCode
def serialNumber
def label
String [] row ;
char separator = ';';
CSVReader reader = new CSVReader(new InputStreamReader(uploadedCSVFile.getInputStream()),separator);
String [] header = reader.readNext()
// String [] temp;
if (header[0].equalsIgnoreCase("Material_Code") && header[1].equalsIgnoreCase("Serial_Number") && header[2].equalsIgnoreCase("#Labels") )
{
List <String []> fileData = reader.readAll()
Iterator<String[]> rowIterator = fileData.iterator()
def listOfCsvMap = []
while (rowIterator.hasNext())
{
def csvMap = [:]
row = rowIterator.next()
materialCode = row.collect().get(0)
serialNumber = row.collect().get(1)
label = row.collect().get(2)
csvMap.put('Material_Code', materialCode)
csvMap.put('Serial_Number', serialNumber)
csvMap.put('Labels', label)
listOfCsvMap.add(csvMap)
}
render([items:listOfCsvMap] as JSON)
upload.gsp
<body>
<div class="body">
<g:uploadForm action="upload" enctype="multipart/form-data">
<input type="file" name="file">
<g:submitButton name="upload" value="Upload"/>
</g:uploadForm>
<g:javascript src="grid.js" />
<div id="csvGrid"> </div>
and in the grid.js
var store1;
Ext.onReady(function() {
store1 = new Ext.data.JsonStore({
storeId: 'myStore1',
pageSize: 20,
proxy: {
type: 'ajax',
url:'upload',
reader: {
type: 'json',
root: 'items'
}
},
fields: ['Material_Code','Serial_Number','Labels']
});
var grid = Ext.create('Ext.grid.Panel', {
store: store1,
stateful: false,
layout:'fit',
enableColumnMove: true,
enableColumnResize:true,
emptyText:'<b style="font-size:14px;color: #F49000;">'+'Please fill all the mandatory fields!!!'+'</b>',
columns: [
{
text : 'Material Code',
width:175,
sortable : true,
dataIndex: 'Material_Code',
},
{
text : 'Serial Number',
width :275,
sortable : true,
dataIndex: 'Serial_Number'
},
{
text : '#Labels',
width :275,
sortable : true,
dataIndex: 'Labels'
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: store1,
pageSize: 20,
displayInfo: true,
displayMsg: 'Displaying rows {0} - {1} of {2}',
emptyMsg: "No rows to display"
}),
height: 350,
width: 850,
renderTo: 'csvGrid',
viewConfig: {
stripeRows: true,
enableTextSelection:true
}
});
store1.reload();
});
The error that is causing the issue directly is this :
<g:uploadForm action="upload" enctype="multipart/form-data">
The action is upload, which is the url that returns the JSON.
A solution would be to create a separate page, define it as action and load the JavaScript on that page.
Alternatively, instead of submitting the form you can send the values as parameters when you load the store (pass them in the options object of store1.load({params: {...}}). In this case it would be a better design to create the whole page with extjs, including the form.
There are other problems with the code, like you have store1.reload();, but you never called load() before.

ExtJS 4 MVC, Get Checkbox value integer instead of bool

I'm using a form to edit Model. I receive data in JSON. Here's my problem:
I receive data for Checkbox only in INT: 1 or 0, I cannot change it. JSON:
{ "checkboxValue": 1 }
This field in ExtJS model is defined as INT type. Model:
{name: "checkboxValue", type: Ext.data.Types.INT},
then I set values to form this way:
formCmp.loadRecord(loadedStore.getAt(0));
and my checkbox is set correctly: when I receive 1 it's checked, 0 - unchecked.
But when I try to save record and send data to server this way:
form.updateRecord(form.getRecord());
record.save();
I need Checkbox to have also INT value - 1 or 0. But it has only BOOL value - true or false so when JSON is sent that value is NaN.
{
"checkboxValue": NaN
}
I think, that function .updateRecord(..) go through all elements and when it gets to checkbox it tries to get value, and the value is BOOL
Does anybody know how to make checkbox' output value INT?
Ext.form.Basic.updateForm uses getFieldValues method to retrieve new data for the updated record, while getFieldValues method returns only boolean values for checkboxes regardless of such properties as inputValue or uncheckedValue. So I would use convert function for the model's field to transform provided boolean value into an integer in a way like that:
Ext.define('MyModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'flag',
type: 'int',
convert: function (v, record) {
return typeof v === 'boolean' ? (v === true ? 1 : 0) : v;
}
}
],
...
});
Here is a complete jsfiddle
I think it can be done with some simple overrides
Ext.create('Ext.form.Panel', {
bodyPadding: 10,
width: 300,
title: 'Pizza Order',
items: [
{
xtype: 'fieldcontainer',
fieldLabel: 'Toppings',
defaultType: 'checkboxfield',
items: [
{
boxLabel : 'Topping?',
name : 'topping',
id : 'checkbox1',
// include these two properties in your checkbox config
uncheckedValue: 0,
setValue: function(checked) {
var me = this;
arguments[0] = checked ? 1 : me.uncheckedValue;
me.callParent(arguments);
return me;
}
}
]
}
],
renderTo: Ext.getBody()
});

Unable to sort Dgrid

var CustomGrid = declare([Grid, Keyboard, Selection]);
var questionGrid = new CustomGrid({
store: questionCacheStore,
columns: [
editor({
label: "Questions",
field: "question",
editor: "text",
editOn: "dblclick",
sortable:true})
],
selectionMode: "single",
cellNavigation: false
}, "questions");
I am new to Dgrid. So, please do bear with me .
i was able to populate the dgrid with a JsonStore content. But when i click on the column 'Questions', it doesn't get sorted as in local data store.instead it shows an error Uncaught TypeError: Object [object Object] has no method 'sort'. Is it required to define such a method . If so, how and where should i define it ?
I am not the person to answer your J2EE question. I asked that question recently. The solution that I found was to inject the HttpServletRequest directly. This allowed me access to the query string parameters. From there I was able to get the sort direction (ascending, descending) and column to sort. Hopefully the snippets below will help.
Example Grid Setup
require(["dojo/store/JsonRest", "dojo/store/Memory", "dojo/store/Cache",
"dojo/store/Observable", "dgrid/OnDemandGrid", "dojo/_base/declare", "dgrid/Keyboard",
"dgrid/Selection", "dojo/domReady!"],
function(JsonRest, Memory, Cache, Observable, Grid, declare, Keyboard, Selection) {
var rest = new JsonRest({target:"/POC_Admin/rest/Subcategory/", idProperty: "subcatId"});
var cache = new Cache(rest, new Memory({ idProperty: "subcatId" }));
var store = new Observable(cache);
var CustomGrid = declare([ Grid, Keyboard, Selection ]);
var grid = new CustomGrid({
columns: {
subcatId: "ID",
name: "Name"
},
store: store
}, "grid");
grid.on("dgrid-select", function(event){
// Report the item from the selected row to the console.
console.log("Row selected: ", event.rows[0].data);
});
grid.startup();
});
Example Rest GET
#Context private HttpServletRequest servletRequest;
#GET
#Path("")
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public String getSubcategories(#QueryParam("name") String name) throws IOException {
//Respond to a QueryString value.
if (servletRequest.getQueryString() != null && servletRequest.getQueryString().length() > 0) {
String querystringKey = servletRequest.getQueryString();
System.out.println("QSKey = " + querystringKey);
System.out.println("Substr: " + querystringKey.substring(0, 4));
if (querystringKey.length()>4) {
if (querystringKey.substring(0, 4).contains("sort")) {
//We have the sort request.
}
}
}
//Return all results otherwise from your DAO at this point
}

I cannot get my jqGrid to populate

Edited with working code as per Mark's answer below.
I'm really starting to loath MVC. I have been trying all day to get a simple grid to work, but I'm having more luck banging a hole in my desk with my head.
I'm trying to implement a search page that displays the results in a grid. There are 3 drop-down lists that the user can use to select search criteria. They must select at least one.
After they have searched, the user will be able to select which records they want to export. So I will need to include checkboxes in the resulting grid. That's a future headache.
Using JqGrid and Search form - ASP.NET MVC as a reference I have been able to get the grid to appear on the page (a major achievement). But I can't get the data to populate.
BTW, jqGrid 4.4.4 - jQuery Grid
here is my view:
#model Models.ExportDatex
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (e) {
var selectedSchool = $('#ddlSchool').children('option').filter(':selected').text();
var selectedStudent = $('#ddlStudent').children('option').filter(':selected').text();
var selectedYear = $('#ddlYear').children('option').filter(':selected').text();
var selectedOption = $('#exportOption_1').is(':checked');
if (selectedSchool == '' && selectedStudent == '' && selectedYear == '') {
alert('Please specify your export criteria.');
return false;
}
selectedSchool = (selectedSchool == '') ? ' ' : selectedSchool;
selectedStudent = (selectedStudent == '') ? ' ' : selectedStudent;
selectedYear = (selectedYear == '') ? ' ' : selectedYear;
var extraQueryParameters = {
school: selectedSchool,
student: selectedStudent,
year: selectedYear,
option: selectedOption
};
$('#searchResults').jqGrid({
datatype: 'json',
viewrecords: true,
url: '#Url.Action("GridData")?' + $.param(extraQueryParameters),
pager: '#searchResultPager',
colNames: ['SchoolID', 'Student Name', 'Student ID', 'Apprenticeship', 'Result'],
colModel: [
{ name: 'SchoolID' },
{ name: 'Student Name' },
{ name: 'StudentID' },
{ name: 'Apprenticeship' },
{ name: 'Result' }]
}).trigger('reloadGrid', [{ page: 1 }]);
});
});
</script>
#using (Html.BeginForm("Index", "Datex", FormMethod.Post))
{
<h2>Export to Datex</h2>
<div class="exportOption">
<span>
#Html.RadioButtonFor(model => model.ExportOption, "true", new { id = "exportOption_1" })
<label for="exportOption_1">VET Results</label>
</span>
<span>
#Html.RadioButtonFor(model => model.ExportOption, "false", new { id = "exportOption_0" })
<label for="exportOption_0">VET Qualifications</label>
</span>
</div>
<div class="exportSelectionCriteria">
<p>Please specify the criteria you want to export data for:</p>
<table>
<tr>
<td>School:</td>
<td>#Html.DropDownListFor(model => model.SchoolID, Model.Schools, new { id = "ddlSchool" })</td>
</tr>
<tr>
<td>Student: </td>
<td>#Html.DropDownListFor(model => model.StudentID, Model.Students, new { id = "ddlStudent" })</td>
</tr>
<tr>
<td>Year Completed:
</td>
<td>
#Html.DropDownListFor(model => model.YearCompleted, Model.Years, new { id = "ddlYear" })
</td>
</tr>
</table>
<table id="searchResults"></table>
<div id="searchResultPager"></div>
</div>
<div class="exportSearch">
<input type="button" value="Search" id="btnSearch" />
<input type="submit" value="Export" id="btnExport" />
</div>
}
Here is my Controller. As we don't have a database yet, I am just hardcoding some results while using an existing table from a different DB to provide record IDs.
[HttpGet]
public JsonResult GridData(string sidx, string sord, int? page, int? rows, string school, string student, string year, string option)
{
using (SMIDbContainer db = new SMIDbContainer())
{
var ds = (from sch in db.SCHOOLs
where sch.Active.HasValue
&& !sch.Active.Value
&& sch.LEVEL_9_ORGANISATION_ID > 0
select sch).ToList();
var jsonData = new
{
total = 1,
page = 1,
records = ds.Count.ToString(),
rows = (
from tempItem in ds
select new
{
cell = new string[]{
tempItem.LEVEL_9_ORGANISATION_ID.ToString(),
tempItem.SCHOOL_PRINCIPAL,
"40161",
"No",
"Passed (20)"
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
Is the JSON you are passing back to the grid valid? Are you passing back the information that the jqGrid needs? Why setup your jqGrid inside of an ajax call instead of inside your $(document).ready(function () { ?
Here is an example of the portion of code I use to format my json for jqGrid:
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
rows = (
from tempItem in pagedQuery
select new
{
cell = new string[] {
tempItem.value1,
tempItem.value2, ........
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
If you want to make your user search first, you can on the client side, set the jqgrid datatype: local and leave out the url. Then after your user does whatever you want them to do you can have the jqGrid go out and fetch the data, via something like:
$('#gridName').jqGrid('setGridParam', { datatype: 'json', url: '/Controller/getGridDataAction' }).trigger('reloadGrid', [{ page: 1}]);
If you want to pass in the search data, or other values to the controller/action that is providing the data to the jqGrid you can pass it via the postData: option in the jqGrid. To set that before going out you can set it via the setGridParam option as shown above via postData: { keyName: pairData}.
MVC and jqGrid work great...there are a ton of examples on stackoverflow and Oleg's answers are a vast resource on exactly what you are trying to do. No hole in desk via head banging required!

Sencha Touch searchable list -- new view with data proxy

Two quick questions here... How can I use this example
http://try.sencha.com/touch/2.0.0/examples/list-search/
of a searchable list, but opened in a NEW view? The example has it defined as the main application in app.js, but I would like to use it in "FirstApp.view.searchlist"
I know the answer is pretty easy but I am still a young grasshoppa and need a push in the right direction.
Also, rather than pulling the data from the embedded store like the example, I would like to modify it to pull my data from my external/proxy JSON store, which is defined as follows:
Store:
Ext.define('FirstApp.store.StudentStore',{
extend:'Ext.data.Store',
config:{
autoLoad:true,
model:'FirstApp.model.people',
sorters: 'lastName',
proxy:{
type:'ajax',
url:'http://xxxyyyzzz.com/data/dummy_data.json',
reader:{
type:'json',
rootProperty:'results'
}
}
}
});
Model:
Ext.define('FirstApp.model.people', {
extend: 'Ext.data.Model',
config: {
fields: ['firstName', 'lastName' , 'image','status', 'phone','rank','attendance', 'discipline','recent']
}
});
So, how can I turn that example into a "view" inside my application, with my data store and model?
Any help is greatly appreciated! Thank you!
Jake
-----------UPDATE-------------
Ok fantastic. I was able to implement the search feature (stoked) by combining your methods with another tutorial I found. Now one more question...Seems so easy but it is tough! How can I open my new 'Details' view once an item is selected/clicked ??
Search list:
Ext.define('FirstApp.view.MainPanel', {
extend: 'Ext.dataview.List',
alias : 'widget.mainPanel',
config: {
store : 'Students',
itemTpl:
'<h1>{firstName:ellipsis(45} {lastName:ellipsis(45)}</h1>' ,
itemCls:'place-entry',
items: [
{
xtype: 'toolbar',
docked: 'top',
items: [
{
xtype: 'searchfield',
placeHolder: 'Search People...',
itemId: 'searchBox'
}
]
}
]
}
});
Details view (that I want to open when name is clicked from Search list/Mainpanel view):
Ext.define('FirstApp.view.Details',{
extend:'Ext.Panel',
xtype:'details',
config:{
layout:'fit',
tpl:'<div class="image_container"><img src="{image}"></div>' +
'<h1>{firstName:ellipsis(25)} {lastName:ellipsis(25)}</h1>'+
'<div class="status_container">{status:ellipsis(25)}</div> '+
'<div class="glance_container"> <div class="value_box"><div class="value_number"> {rank:ellipsis(25)}</div> <p class="box_name">Rank</p> </div> <div class="value_box"><div class="value_number"> {attendance:ellipsis(25)}</div> <p class="box_name" style="margin-left: -10px;">Attendance</p> </div> <div class="value_box"><div class="value_number">{discipline:ellipsis(25)}</div> <p class="box_name" style="margin-left: -4px;">Discipline</p> </div> <div class="value_box"><div class="value_number"> {recent:ellipsis(25)}</div> <p class="box_name">Recent</p> </div> </div> '+
'<h2>Phone:</h2> <div class="phone_num"><p>{phone:ellipsis(25)}</p></div>'+
'<h3>Some info:</h3><p>Round all corners by a specific amount, defaults to value of $default-border-radius. When two values are passed, the first is the horizontal radius and the second is the vertical radius.</p>',
scrollable:true,
styleHtmlContent:true,
styleHtmlCls:'details'
}
})
Search Controller:
Ext.define('FirstApp.controller.SearchController', {
extend : 'Ext.app.Controller',
config: {
profile: Ext.os.deviceType.toLowerCase(),
stores : ['StudentStore'],
models : ['people'],
refs: {
myContainer: 'MainPanel',
placesContainer:'placesContainer'
},
control: {
'mainPanel': {
activate: 'onActivate'
},
'mainPanel searchfield[itemId=searchBox]' : {
clearicontap : 'onClearSearch',
keyup: 'onSearchKeyUp'
},
'placesContainer places list':{
itemtap:'onItemTap'
}
}
},
onActivate: function() {
console.log('Main container is active');
},
onSearchKeyUp: function(searchField) {
queryString = searchField.getValue();
console.log(this,'Please search by: ' + queryString);
var store = Ext.getStore('Students');
store.clearFilter();
if(queryString){
var thisRegEx = new RegExp(queryString, "i");
store.filterBy(function(record) {
if (thisRegEx.test(record.get('firstName')) ||
thisRegEx.test(record.get('lastName'))) {
return true;
};
return false;
});
}
},
onClearSearch: function() {
console.log('Clear icon is tapped');
var store = Ext.getStore('Students');
store.clearFilter();
},
init: function() {
console.log('Controller initialized');
},
onItemTap:function(list,index,target,record){ // <-----NOT WORKING
this.getPlacesContainer().push({
xtype:'details',
store:'Students',
title:record.data.name,
data:record.data
})
}
});
Good question. I assume you are trying to build a List or dataview. The key here is to give your store a 'storeId'. I have modified your store below:
Ext.define('FirstApp.store.StudentStore',{
extend:'Ext.data.Store',
config:{
storeId: 'Students', // Important for view binding and global ref
autoLoad:true,
model:'FirstApp.model.people',
sorters: 'lastName',
proxy:{
type:'ajax',
url:'http://xxxyyyzzz.com/data/dummy_data.json',
reader:{
type:'json',
rootProperty:'results'
}
}
}
});
Then inside your view, you reference the store to bind to. Here is an example List view from one of my applications. Notice the config object has 'store' which references our above store:
Ext.define('app.view.careplan.CarePlanTasks', {
extend: 'Ext.dataview.List',
xtype: 'careplanTasks',
requires: [
'app.view.template.CarePlan'
],
config: {
store: 'Students', // Important! Binds this view to your store
emptyText: 'No tasks to display',
itemTpl: Ext.create('app.view.template.CarePlan'),
},
constructor : function(config) {
console.log('CarePlan List');
this.callParent([config]);
}
});
Now that you have a storeId, you can access this store anywhere in your application by doing the following:
Ext.getStore('Students')
You can load records from your server by calling the load method as well:
Ext.getStore('Students').load();
You can do this anywhere in your application, but typically it's best to do in your controllers.
Hope this helps.
======= Updates to your updates ======
So looking at your code I think you need to modify your List view and the controller. Give 'FirstApp.view.MainPanel' an xtype: 'MainPanel'. Next modify your controller config as follows:
config: {
profile: Ext.os.deviceType.toLowerCase(),
stores : ['StudentStore'],
models : ['people'],
refs: {
mainPanel: 'MainPanel', // set the object KEY to the name you want to use in the control object and set the VALUE to the xtype of the view
placesContainer:'placesContainer'
},
control: {
'mainPanel': { // this matches the key above, which points to your view's xtype
activate: 'onActivate',
itemtap: 'onItemTap' // listen for the item tap event on this List
},
'mainPanel searchfield[itemId=searchBox]' : {
clearicontap : 'onClearSearch',
keyup: 'onSearchKeyUp'
},
'placesContainer places list':{
itemtap:'onItemTap'
}
}
},