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>";
}
Related
I am new to tabulator and i wanted to know why this is isn't working my data response is like this
[{"UserId":2,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"4:37","Date":"2018-05-15T08:35:20"},
{"UserId":14,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"0:47","Date":"2018-05-15T08:36:10"},
{"UserId":8,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"1:20","Date":"2018-05-15T08:37:47"},
{"UserId":16,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"2:55 (Nuk ka Deklaruar Pauze)","Date":"2018-05-15T08:37:52"},
{"UserId":11,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"2:54 (Nuk ka Deklaruar Pauze)","Date":"2018-05-15T08:38:03"},
{"UserId":1,"Name":"John Doe","WorkingMinutes":0,"WorkingHours":"2:38 (Nuk ka Deklaruar Pauze)","Date":"2018-05-15T08:49:23"}]
(the names are all the same for purpose of privacy)
And this is my javascript
<script type="text/javascript">
var table = new Tabulator("#MyTable", {
ajaxURL: "#Url.Action("WorkingHours", "Dashboard")",
height: "292px",
layout: "fitColumns",
pagination: "local",
paginationSize: 20,
movableColumns: true,
columns: [
{ title: "UserId", field: "Id", formatter: "star", align: "center", width: 100 },
{ title: "Name", field: "name", width: 200 },
{ title: "Working Minutes", field: "progress", sorter: "number" },
{ title: "Working Hours", field: "progress" , sorter : "number" },
{ title: "Date", field: "dob", align: "center", sorter: "date" },
],
});
I checked the console and the response and it said this : Data Loading Error - Unable to process data due to invalid data type Expecting: array Received: string
and then the data that is in the begging of the question. And yes me method returns a string but it is json.
The data you are returning is in the format needed for an Un-Paginated Table
For paginated data it needs the following format:
{
"last_page":15, //the total number of available pages (this value must be greater than 0)
"data":[ // an array of row data objects
{id:1, name:"bob", age:"23"}, //example row data object
]
}
Full documentation on how to use remote pagination can be found on the Tabulator Website
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.
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.
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
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..!!