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
Related
I have have the following JSON data that i'm retrieving from a database. How do I go about getting the value of the label property?
{
elementAttributes: {
"layout": "row"
},
fieldGroup: [
{
type: "select",
key: "title",
className: "flex-100 layout-column",
templateOptions: {
label: "Title *",
multiple: false,
required: true,
disabled: false,
labelProp: "desc",
valueProp: "id",
options: [
{ desc: "Mr", id: 1 },
{ desc: "Mrs", id: 2 },
{ desc: "Ms", id: 3 },
{ desc: "Miss", id: 4 },
{ desc: "Dr", id: 5 }
],
description: ""
}
}
]
}
Just use Newtonsoft.Json, there is very good example:
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
To generate class, u can use:
http://json2csharp.com/
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 have posted on the Infragistics forums to no avail so I thought I would ask the community who may use their product.
I am implementing a Hierarchical Grid with IgniteUI and cannot seem to get my JsonResult to bind to the grid. The grid will render with the correct number of rows but none of the columns populated.
I have the following Grid:
$("#grid").igHierarchicalGrid({
dataSourceType: "json",
dataSource: "/Products/GetProducts/",
odata: "false",
autoGenerateColumns: "false",
primaryKey: "Id",
initialDataBindDepth: 1,
columns: [
{ headerText: "Id", key: "Id", dataType: "number" },
{ headerText: "SKU", key: "SKU", dataType: "string" },
{ headerText: "UPC", key: "UPC", dataType: "string" },
{ headerText: "Name", key: "Name", dataType: "string" },
{ headerText: "ManufacturerId", key: "ManufacturerId", dataType: "number" },
{ headerText: "ManufacturerSKU", key: "ManufacturerSKU", dataType: "string" },
{ headerText: "Inventory", key: "Inventory", dataType: "number" },
{ headerText: "Weight", key: "Weight", dataType: "number" },
{ headerText: "Price", key: "Price", dataType: "number" },
{ headerText: "MSRP", key: "MSRP", dataType: "number" },
{ headerText: "CategoryId", key: "CategoryId", dataType: "number" },
{ headerText: "Active", key: "Active", dataType: "string" },
{ headerText: "CreateDate", key: "CreateDate", dataType: "date", format: "MM-d-yyyy, h:mm tt" },
{ headerText: "UpdateDate", key: "UpdateDate", dataType: "date", format: "MM-d-yyyy, h:mm tt" }
],
features: [
{
name: "Sorting",
type: "local"
},
{
filterExprUrlKey: 'filter',
filterLogicUrlKey: 'filterLogic',
name: "Filtering",
type: "remote",
columnSettings: [
{
columnKey: 'Id',
condition: "equals"
}
]
},
{
name: 'Paging',
type: "local",
pageSize: 10
}
],
columnLayouts: [
{
key: "VendorProducts",
primaryKey: "Id",
foreignKey: "Id",
autoGenerateColumns: "false",
responseDataKey: 'results',
columns: [
{ headerText: "Id", key: "Id", dataType: "number" },
{ headerText: "ProductId", key: "ProductId", dataType: "number" },
{ headerText: "PartnerName", key: "PartnerName", dataType: "string" },
{ headerText: "VendorSKU", key: "VendorSKU", dataType: "string" },
{ headerText: "Cost", key: "Cost", dataType: "number" },
{ headerText: "Inventory", key: "Inventory", dataType: "number" },
{ headerText: "Active", key: "Active", dataType: "number" }
],
features: [
{
name: "Sorting",
type: "local"
}]
}
]
});
The Json returned from the server is as follows
var data = [{ "Id": 1032, "SKU": "5_113990", "UPC": "10000001", "Name": "NVG7-3P", "ManufacturerId": 1015, "ManufacturerSKU": "NVGONVG73P", "Inventory": 0, "Weight": 3, "Price": 3026.6, "MSRP": 3799, "CategoryId": 1018, "Active": true, "CreateDate": "\/Date(1398794923467)\/", "UpdateDate": "\/Date(1400000587250)\/", "VendorProducts": [{ "Id": 1046, "ProductId": 1032, "PartnerName": "Direct Buy", "VendorSKU": "113990", "Cost": 0, "Inventory": 0, "Active": true }] }];
Which when plugged into dataSource will render the grid just fine, however when the grid calls out to the method:
[HttpGet]
public JsonResult GetProducts()
{
var model = Query.....
return Json(model, JsonRequestBehavior.AllowGet);
}
The following error is thrown:
**Uncaught Error: There was an error parsing the JSON data and applying the defined data schema: The input data doesn't match the schema, the following field couldn't be mapped: VendorProducts**
I have tried a number of things but cannot seem to get the grid to load on demand.
Is a current known issue of the igGrid, see: http://www.infragistics.com/community/forums/p/91530/452561.aspx
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
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..!!