How to generate a tree grid using jqgrid? - c#

I want to generate a tree node table using jqgrid.
For example the html table is like this.
Id Name ParentId UserId
1 xx null 1
2 yy null 1
3 yy null 2
There are two questions that I have not solved.
Question one is as follows:
I need to pass two parameter from the parent Row data to server for query child data. For example when I click the parentRow I need to pass the 'Id' and 'UserId' to server for querying child data.
For this I have no idea to get the UserId ,I can only get the 'Id' on each click
$('#mytable').jqGrid({
url: 'home/getdata',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
datatype: 'json',
mtype: 'GET',
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColumn: 'Name',
postData: postData,
colNames: ['ID', 'Name', 'ParentID','UserId'],
colModel: [
{ name: 'ID', index: 'ID', hidden: true, width: 1, key: true },
{ name: 'Name', index: 'Name', width: 200, fixed: true },
{ name: 'ParentID', index: 'ParentID', hidden: true, width: 1 },
{ name: 'UserId', index: 'UserId', width: 100 },
],
autowidth: true,
height: 'auto'
});
on the server side(C#) I can user Request["nodeid"] and Request["n_level"] to get 'Id' and level. But I want to get 'UserId' at the same time, so how could I do this?
Question two: 
I want to query differnt datasource according the condition the front choose. For example I put a datetime picker in my page,
and I want mytable(jqgrid) to reload after I change the datetime picker.
The question is that, I don't know how to pass the time value to server when I click the parent row each time and when I use $("mytable").triggle("reloadGrid"), it seems to not work. The grid table has no refresh.

Visit http://www.trirand.com/jqgridwiki/doku.php?id=wiki:treegrid
I believe this should be sufficient enough information if you haven't already checked this out.

Related

How can i bind a javascript object to a Kendo treelist?

I am making a call to my MVC controller and return a list of objects to angular (javascript)
I want to bind it to a Kendo Treelist with arrows on the left such that when the user expands i can get the value of the parent , get the children associated with the parent and bind below the parent.
Here is what i have tried
HTML Code:
<div kendo-tree-list id="treeView" k-options="sourceOptions"></div>
Javascript:
This is defined in the beginning of the javascript file:
$("#treeView").kendoTreeList({
dataSource: $scope.userdetails,
toolbar: ["create"],
editable: "popup",
height: 540,
columns: [
{ field: "Id", expandable: true, title: "Id", width: 250 },
{ field: "FirstName", title: "FirstName", width: 250 },
{ field: "LastName", title: "LastName", width: 250 },
{ command: [{ name: "createchild", text: "Add child" }, "edit", "destroy"], width: 300 }
]
});
This bit of javascript is called only when a value in a dropdown is selected.
if ($scope.company!= undefined && $scope.company!= null && $scope.company.length > 0) {
myService.getAllUsers({
Name: $scope.company
}).then(function (result) {
if (result.data != null && result.data.userdetails) {
var treelist = $("#treeView").data().kendoTreeList;
var newDs = new kendo.data.TreeListDataSource({
data: result.data.userdetails,
schema: {
model: {
id: "Id",
fields: {
Id: { type: "string"},
FirstName: { type: "string" },
LastName: { type: "string" }
},
expanded: false
}
}
});
treelist.setDataSource(newDs);
}
});
}
};
So there is a dropdownlist that is populated with a number of companies. When the user selects a company from the list , it will call getAllUsers and retrieve all users in a company from MVC and return a javascript object, I want to bind that to the treeview.
When its bound , each parent should have a arrow on the left which will allow it to be expanded and only when they expand , i want to call another MVC actionresult that will retrieve the child data for that selected value. The child result will have checkboxes allowing the user to select and child fields on the parent.
If they select a different company from the main list , then the treeview will be cleared and repopulated
It doesnt seem to be binding at all, any ideas with this ?

Binding child of band Infragistics Hierarchical Data Grid to jsonResult

I have a hierarchical data grid that recieves data from a json call fine. But I have problems with the child band. I don't know if it is the code or how the data is presented within the list from the json call.
<table id="hierarchicalGrid"></table>
<script type="text/javascript">
var data = #MyData.AsRawJson()
$("#hierarchicalGrid").igHierarchicalGrid({
dataSource: data,
odata: true,
initialDataBindDepth: -1,
autoGenerateLayouts: true,
autoGenerateColumns: false,
primaryKey: "Username",
columns:
[{ key: "Username", headerText: "Username", dataType: "string" },
{key: "EmplID", headerText: "EmplID", dataType: "string" },
{key: "Comment", headerText: "Comment", dataType: "string" }],
features:
[{name: 'Paging',
type: "local",
pageSize: 50},
{ name: "Resizing"},
{ name: 'ColumnMoving' }],
columnLayouts: [
{
key: "GroupName",
primaryKey: "GroupName",
foreignKey: "GroupMembers",
autoGenerateColumns: false,
columns: [
{ key: "GroupName", headerText: "UserName", dataType: "string", width: "100px" },
{ key: "GroupDescription", headerText: "GroupDescription", dataType: "string", width: "100px" },
{ key: "GroupMembers", headerText: "GroupMembers", dataType: "string", width: "100px" }
],
features: [
{
name: "Sorting",
type: "local"
}]
}]
});
</script>
The data comes as follows
[username],[EmplID],[comment],[GroupName],[GroupDescription],[GroupMembers]
with UserName,EmplID, and Comment repeating with the same values per username while values for GroupName, and GroupDescription continue to be unique. GroupMembers has the same data as UserName. All of the data is coming from a view, which is a join from Users ([username],[EmplID],[comment]) and Groups ([GroupName],[GroupDescription],[GroupMembers]). I would like a single row for UserName,EmplID, and Comment as if it were a groupby then expanding the child band would show [GroupName] and [GroupDescription].
When the initial grid opens, I get repeating rows of [username],[EmplID],[comment] and when I try to expand the child band, it throws a errormessage displaying:
Unable to get value of the property '_injectGrid': object is null or undefined.
For what its worth, this is written on C# Razor pages using ServiceStack to Bootstrap. Any and all help is greatly appreciated.

Extjs Grid Grouping - setting default header/value

On the following grid grouping example. How can I display The first group as (0 Countries), if no data is returned for the first record.
Currently, if there are no records, the first group does not appear
What I need to do is, show the first group with (0) count and not just make it disappear. Is there way to still show up the group header, even if there is no data, like a default header or something? Any ideas? I need to do this for all the 4 headers
Update
Ext.require(['Ext.data.*', 'Ext.grid.*']);
Ext.onReady(function() {
Ext.define('Country', {
extend: 'Ext.data.Model',
fields: ['name']
});
var Country = Ext.create('Ext.data.Store', {
storeId: 'country',
model: 'Country',
groupField: 'countryName',
proxy: {
type: 'ajax',
scope: this,
url: 'myExtjsApp/ExtjsGetRecord',
reader: {
type: 'json',
root: 'data'
}
}
});
var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
groupHeaderTpl: '{name} ({rows.length} Item{[values.rows.length > 1 ? "s" : ""]})'
});
var grid = Ext.create('Ext.grid.Panel', {
renderTo: Ext.getBody(),
collapsible: true,
iconCls: 'icon-grid',
frame: true,
store: Country,
width: 600,
height: 400,
title: 'Country',
features: [groupingFeature],
columns: [{
text: 'Country',
flex: 1,
dataIndex: 'name'
}]
});
});
side topic:
for your header template you can also use plural format function instead of just adding 's': (which ironically this does if you don't pass singular and plural arguments)... just a thought.
http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.util.Format-method-plural

hyperlink in JQuery

I have created a grid using JQuery in MVC3, the grid displays data from the model, but now am intending to place a hyperlink to one of the column in the grid so tat when user clicks on the link he should be able to look up on the data pertaining to the row value..below is the code to display my grid.
<script type="text/javascript">
$(document).ready((function () {
$("#list").jqGrid({
url: '/list/GetDet/',
datatype: 'json',
mtype: 'GET',
colNames: ['Code', 'Name', 'Location'], //column name
colModel: [
{ name: 'Code', index: 'Code', width: 100, align: 'right' },
{ name: 'Name', index: 'Name', width: 100, align: 'left' },
{ name: 'location', index: 'location', width: 100, align: 'left'}],
pager: $('#pager'),
rowNum: 5,
rowList: [5, 10, 20, 50],
sortname: 'Code',
sortorder: "desc",
viewrecords: true,
caption: 'Details'
});
}));
</script>
if i intend to create a link to the name column how do i provid
I think you have a problem with the sending of the URL .
Here is the Link to solve that issue.
You could use the getCell method (as mentioned in the jqGrid docs). Once you have this value in your javascript, you could handle it any way you like.
In your getData action where you are putting the actual link or ID which you want to link use full html string just where you create the cell. Server can send View to the client and it would appear as a link. This would not affect any search or sorting as they have been done on the actual index and not hyperlink.
I usually prepare my actions serverside but if you want to do it client side you can use specify a custom function as a formatter and format the value in anyway you want.
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options
Have a look at formater option
Use camelcase for column name and index, don't use capital letter on declaration of starting word of columns. If you use the grids are not loaded.
Example:
{ name: 'code', index: 'code', width: 100, align: 'right' },
{ name: 'name', index: 'name', width: 100, align: 'left' },
{ name: 'location', index: 'location', width: 100, align: 'left'}],
Your problem is related on off previously asked question Retrieve value of cells, when in edit mode in JqGrid is answered How to return row values using hyperlink in jqgrid
In editLink function use column index name for get the row values.
function editLink(cellValue, options, rowdata, action)
{
alert('Name: '+ rowdata.name);//alerts row value of column
//return "<a href='/Admin/editProvider/" + rowdata.providerId + "' class='ui-icon ui-icon-pencil' ></a>";
}

Jqgrid Master Detail don't send the appropriate info

I'm searching about my problem here and find some tips, but doesn't work anyway, my problem is this:
In the jqgrid Javascrip, I send as setGridParam this: {url:'myurl/myfunction/'+ id, page:1, datatype:"json"} but, the Jgqgrid still doesn't sending to my controller the Id for make a selection of the details, It´s always null..... I tried everyting and the problem persist, please help me.
Here's my Javascript:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#list").jqGrid({
url: '/Master/GridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Descripción'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Descripcion', index: 'Descripcion', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} }
],
pager: jQuery('#pager'),
autowidth: true,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "asc",
viewrecords: true,
caption: '<b>Listado de Masters</b>',
onSelectRow: function(ids) {
if (ids != null) {
var data = $("#list").getRowData(ids);
jQuery("#DetailList").setGridParam({ url: "/Master/DetailGridData/" + data.Id, page: 1, datatype: 'json' })
.setCaption("<b>Details of Master : " + data.Descripcion+"</b>")
.trigger('reloadGrid');
}
}
}).navGrid(pager, { edit: false, add: false, del: false, refresh: true, search: false });
jQuery("#DetailList").jqGrid
({
height: 100,
datatype: "json",
colNames: ['Id', 'Descripción', 'Modelo'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Descripcion', index: 'Descripcion', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} },
{ name: 'Modelo', index: 'Modelo', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} }
],
rowNum: 5,
rowList: [5, 10, 20],
pager: jQuery('#DetailPager'),
sortname: 'Id',
viewrecords: true,
sortorder: "desc"
}).navGrid('#DetailPager', { add: false, edit: false, del: false, search: false });
});
</script>
And here's my Controller Code:
public ActionResult GridData(string sidx, string sord, int? page, int? rows)
{
List<Master> ms = new List<Master>();
ms = MasterRepository.GetAll().ToList<Master>();
int pageIndex = Convert.ToInt32(page) - 1;
int totalrecords = ms.Count();
int totalpages = (int)Math.Ceiling((decimal)totalrecords / (decimal)rows);
var jsonData = new
{
sidx = "Id",
sord = "asc",
page = 1,
records = 25,
rows = (
from ch in ms
select new
{
id = ch.Id,
cell = new string[]
{
ch.Id.ToString(),
ch.Descripcion,
}
}).ToArray(),
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult DetailGridData(string IdMaster, string sidx, string sord, int? page, int? rows)
{
int IdCh = Convert.ToInt32(IdMaster);
IList<Detail> det = new List<Detail>();
det = DetailRepository.GetByMaster(IdCh).ToList<Detail>();
int pageIndex = Convert.ToInt32(page) - 1;
int totalrecords = det.Count();
var jsonData = new
{
sidx = "Id",
sord = "asc",
page = 1,
records = 25,
rows = (
from bah in det
select new
{
id = bah.Id,
cell = new string[]
{
bah.Id.ToString(),
bah.Descripcion,
bah.Modelo
}
}).ToArray(),
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
}
I think you should verify routes.MapRoute which you added to the route table. Do you really use IdMaster parameter or you should rename it to Id? It can be that you just forget to add the custom rule.
Another problem which I could see is the syntax error: you use
.navGrid(pager, {...
instead of
.navGrid('#pager', {...
(the variable pager in undefined).
Another possible problem is possible id duplicates. Be sure that ids of the detail grid has another values as the ids from the master grid. Because ids are strings you can for example use prefixes for the ids: like 'm_'+ch.Id for the master grid and 'd_'+bah.Id for details grid.
Some more remarks:
sidx and sord should not be included in the JSON response of the server. Instead of that total should be included. See here for more information.
I recommend you to use datatype: "local" instead of datatype: "json" for the details grid definition. It will prevent attempt to load data at the grid initialization.
I recommend you to use pager: '#pager' instead of pager: jQuery('#pager').
I recommend you to use key: true in the 'Id' column. In the case you will don't need to send Id values twice. If you would use additionally jsonReader: {cell:''} you can remove cell property like id property from the rows data. So you can use about the following from ch in ms select new { new string[] { ch.Id.ToString(), ch.Descripcion }}).ToList(). See here or here for example.
I recommend you to use error handling on the jqGrid at the beginning of your code. See the UPDATED part of the answer with the demo project. Displaying of error messages can save many time of your debugging. The demo could be interesting for you as a ASP.NET MVC code example which use jqGrid.
i think there is a issue in url string format. it should be like
jQuery("#DetailList").setGridParam({ url: "/Master/DetailGridData/?id=" + data.Id, page: 1, datatype: 'json' })
I have finally found the solution, thanks for the suggestion aamir and Oleg.
I had to do was the following:
First change the name Id in the MasterGrid by IdMaster, so there is no confusion with the Id of the Detail Grid, then correct the line where setGridParam is sent by the following:
jQuery("#DetailList").setGridParam({ datatype: 'json', url: "/Master/DetailGridData?IdMaster=" + data.IdMaster, page: 1 })
That was it and now everything works fine...!! ;)
Thanks again aamir and Oleg... you save my day..!!

Categories

Resources