Jqgrid Master Detail don't send the appropriate info - c#

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..!!

Related

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.

Default value for combobox in kendo grid

I added combobox to the Kendo Grid, as in the following example:
http://demos.telerik.com/kendo-ui/grid/editing-custom
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
CityId: {
editable: true,
type: "number",
validation: { required: true }
}, ...
columns: [{
field: "CityId",
title: "City",
editor: cityDropDownEditor,
template: "#=City.Name#",
width: 200,
} ...
function cityDropDownEditor(container, options) {
$('<input required data-text-field="CityName" data-value-field="CityId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoComboBox({
autoBind: true,
dataTextField: "CityName",
dataValueField: "CityId",
filter: "contains",
index: 1,
autocomplete: true,
dataSource: {
transport: {
read:
{
url: "/Contact/GetCities",
type: "POST",
dataType: "json"
}
}
}});
}
And if I clicked to Add button, combobox is shown prefilled value 0. If i remove line type: "number" in schema - combobox shows prefilled value with CityName, index of which is set in the combobox initialization
.kendoComboBox({
index: 1...
But when I click Submit, this value isn't got to the back-end and I see exception. How I can add correct default value for combobox?
First as note you have dataTextField: "CityName", dataValueField: "CityId" twice initiated, and think you've missed something on your example which is this part in the schema
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
Category: { defaultValue: { CategoryID: 3, CategoryName: "Confections"} },
UnitPrice: { type: "number", validation: { required: true, min: 1} }
}
On the category field they set the default value to { CategoryID: 1, CategoryName: "Beverages"} , now i changed it to { CategoryID: 3, CategoryName: "Confections"}. It is working good here
DEMO

Pass a url stored in model to jquery var (for KendoGrid)

I have an issue which seems ridiculous. I'm trying to set the WebApi base service url from my controller and pass it to the front end / jquery for use in the KendoGrid. I can't seem to pass a URL in a string variable from within a model to my jquery var without getting an error, such as:
ReferenceError: invalid assignment left-hand side
var crudServiceBaseUrl = "http://localhost:55607/api/StockSelectorWebApi?" + sea...
and if I UrlEncode it:
SyntaxError: identifier starts immediately after numeric literal
var crudServiceBaseUrl = http%3a%2f%2flocalhost%3a55607%2fapi%2fStockSelectorWeb...
my query is as follows:
var crudServiceBaseUrl = #Model.CrudBaseServiceUrl;
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "WedNo",
fields: {
WedNo: { editable: false, nullable: true, type: "number" },
MillNo: { editable: false, nullable: true, type: "string" },
Location: { editable: false, nullable: true, type: "string" },
Stockholder: { editable: false, nullable: true, type: "string" },
Auths: { editable: false, nullable: true, type: "string" }
}
}
}
});
and my model:
model.CrudBaseServiceUrl = Server.UrlEncode("http://localhost:55607/api/StockSelectorWebApi?searchType=Arrival&parameterOne=" + model.Arrival);
EDIT: Oddly enough I also had tried
model.CrudBaseServiceUrl = "'URLHERE'";
and
model.CrudBaseServiceUrl = "'" + "URLHERE" + "'";
But neither worked, but as was pointed out below (in the accepted answer) just do:
model.CrudBaseServiceUrl = "URLHERE";
and then
var crudServiceBaseUrl = '#Model.CrudBaseServiceUrl';
pffttt
var crudServiceBaseUrl = '#Model.CrudBaseServiceUrl'
basically, if you use string variables coming from the server within javascript you should use quotes around them. no need to encode or anything.

Extjs Paging Toolbar in Grid does not work

I have searched high and low for this problem... and I found a lot of people have the same problem but none have a definite solution...
Basically I have a grid on extjs... it gets data from sqldb. It loads fine using json. "But"... when trying to implement paging, this is where it gets messy...
pagesize is set to 5... which means first page should only show 5 records, but my grid shows the entire records
Even though the "next" button exists, it does not work technically because the entire record is already there on the first page
I set page.loadPage(2)... and the message says "Displaying Second Page", but it's actually displaying the entire records
The page number in "Page _ of 6" is always blank. see below image...
Below is my store...
var store = Ext.create('Ext.data.Store', {
storeId: 'myData',
pageSize: 5,
autoLoad: true,
method: "POST",
remoteSort: true,
fields: [
{ name: 'Q1', type: 'int' },
{ name: 'Q2', type: 'int' },
{ name: 'Q3', type: 'int' },
{ name: 'Q4', type: 'int' },
{ name: 'Q5', type: 'int' },
{ name: 'Improvements', type: 'string' },
{ name: 'Comments', type: 'string' }
],
sorters: [
{
property: 'Q1',
direct: 'ASC'
}
],
proxy: {
type: 'ajax',
url: 'GridView/writeRecord',
reader: {
type: 'json',
totalProperty: "count",
root: "myTable"
}
},
autoLoad: { params: { start: 0, limit: 5} }
});
this.grid = Ext.create('Ext.grid.Panel', {
title: ' ',
trackMouseOver: true,
disableSelection: true,
autoHeight: true,
store: store,
loadMask: true,
height: 500,
width: 800,
renderTo: Ext.getBody(),
columns: [
{ header: 'Q1',
sortable: true, dataIndex: 'Q1'
},
{ header: 'Q2',
sortable: true, dataIndex: 'Q2'
},
{ header: 'Q3',
sortable: true, dataIndex: 'Q3'
},
{ header: 'Q4',
sortable: true, dataIndex: 'Q4'
},
{ header: 'Improvements', flex: 1,
sortable: true, dataIndex: 'Improvements'
},
{ header: 'Comments', flex: 1,
sortable: true, dataIndex: 'Comments'
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: store,
displayInfo: true,
preprendButtons: true,
displayMsg: 'Displaying Surveys {0} - {1} of {2}',
emptyMsg: "No Surveys to display"
})
});
and this is my JSON... it has actually 30 records but I trimmed it down...
{
"count": 30,
"myTable": [
{
"Q1": "1",
"Q2": "1",
"Q3": "1",
"Q4": "1",
"Improvements": "",
"Comments": "1"
},
{
"Q1": "3",
"Q2": "2",
"Q3": "2",
"Q4": "2",
"Improvements": "This is A very long comment. What do you think?",
"Comments": "Agreed"
},
{
"Q1": "4",
"Q2": "2",
"Q3": "4",
"Q4": "3",
"Improvements": "Hello2",
"Comments": "Hello2"
},
{
"Q1": "3",
"Q2": "2",
"Q3": "2",
"Q4": "1",
"Improvements": "Hello4",
"Comments": "Hello4"
}
]
}
Also if it helps this is how I get my Json
string sqlquery = "SELECT Q1, Q2, Q3, Q4, Improvements, Comments FROM ITable";
conn.Open();
SqlDataAdapter cmd = new SqlDataAdapter(sqlquery, conn);
SqlCommand comd = new SqlCommand(sqlquery, conn);
DataSet myData = new DataSet();
cmd.Fill(myData, "myTable");
comd.CommandText = "SELECT COUNT(*) FROM ITable";
Int32 count = (Int32)comd.ExecuteScalar();
comd.ExecuteNonQuery();
conn.Close();
var results = (new
{
TotalNumber = count,
myTable = myData
});
return JsonConvert.SerializeObject(new { count=count, myTable = myData.Tables[0] }, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
I know my Json is right... and it reads 30 records because is says "Displaying _ of 30"... I just have no clue what I am doing wrong... It cannot be a browser issue... why is it throwing up all in one page? anybody?
When using the paging toolbar, the server is supposed to page the data for you. You don't feed it all of the records at once.
The paging toolbar will send requests asking for each page, and the server is supposed to return just the records for that page.
If you want to page with in memory data (fetching them all at once, you have to implement your own, or use one of the extensions.
See the section titled "Paging with Local Data" at http://docs.sencha.com/ext-js/4-1/#!/api/Ext.toolbar.Paging
Therefore, to use it as intended, you have to change your server code to account for the start and limit HTTP parameters

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>";
}

Categories

Resources