fill the filter values of a column by it's own values in kendo - kendo-grid

I have a kendo grid which is filled with some JSON data,
in the filter window in the grid, you can select a condition Type and then fill the condition value text box and then filter the grid based on your selection.
now I have a column that is filled with just four or five different value.
I want to make the condition value field of the filter section to become a drop-down list and instead of writing those values to select them, I want to choose them from the list. ( I mean in the filter section of the grid column, not in the column itself.)
I read an article which was like what I wanted, but it had added those values in the code,
I should notify you that those fields are not the same each time, so I can't write those value in the filter by hard coding.
even something like this one is very similar to what I wanted ( Filter Condition Created For 'City' Field ), but it's using a different source for getting the condition drop-down values, not grid column itself.
in addition, I can't use JSON data, I must use the information from the kendo grid.
thanks in advance.

I found the solution to my problem at last...
after binding the grid to the data source, by setting a loop on the data source of the grid, I take data of one column of the grid and push it to an array, then I set the filter on that column to the array.
<script type="text/javascript">
var arrayName = [];
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "api/products",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "Data",
total: "Total",
model: {
fields: {
"Id": { type: "number" },
"Name": { type: "string" },
"IsAvailable": { type: "boolean" },
"Price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown);
},
sort: { field: "Id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
productsDataSource.read();
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
dataBound:
function (e) {
var data = $("#report-grid").data("kendoGrid").dataSource._data;
for (i = 0; i < data.length; i++) {
arrayName.push(data[i].Name);
}
},
autoBind: false,
scrollable: false,
pageable: true,
sortable: true,
filterable: { extra: false },
reorderable: true,
columnMenu: true,
columns: [
{ field: "Id", title: "No", width: "130px" },
{ field: "Name", title: "ProductName", filterable: { ui: SystemFilter } },
{
field: "IsAvailable", title: "Available",
template: '<input type="checkbox" #= IsAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "Price", title: "Price", format: "{0:c}" }
]
});
function SystemFilter(element) {
element.kendoDropDownList({
dataSource: arrayName,
optionLabel: "--Select Name--"
})
};
});

One way that I like to do this is to create a list of my values and add that list to ViewData, which then gets passed to the View.
public IEnumerable<ModelName> GetTypes()
{
//Get data from the table you store your values in.
return dbContext.TypesTable.OrderBy(f => f.Name);
}
public ActionResult YourView()
{
IEnumerable<ModelName> types = GetTypes();
ViewData["MyTypes"] = types;
return View();
}
Then in your grid add a ForeignKey column and set it to look at the ViewData you set earlier.
#(Html.Kendo().Grid<ViewModelName>()
.Name("GridName")
.Columns(columns =>
{
columns.ForeignKey(c => c.RecipientType, (System.Collections.IEnumerable)ViewData["MyTypes"], "TypeId", "Name");
})
)
This column will now display the Name of your value for the current records. Then when you go to edit or add a record, this field will display as a dropdown with all of the possible values.

Related

default sorting in kendo grid must be descending

I have created a kendo grid and load its datasource using ajax call. The grid is loading correctly and its working fine. Now i want to sort the data in grid based upon only one column. The grid definition is as follows :
$("#grid").kendoGrid({
scrollable: true,
resizable:true,
filterable: {
extra:false,
operators: {
string:{ contains: "Contains"}
}
},
dataSource: {
transport: {
read: {
url: urlStr + dataPrm,
dataType: "json",
async:true
},
parameterMap: function(data, type) {
if (type == "read") {
return {
$start_rows: data.skip,
$page_size: data.pageSize
}
}
}
},
pageSize: 20,
serverPaging : true,
schema : {
model: {
fields: {
a_id : { type: "string" },
a_percentage: { type: "number" },
emp_last_name: { type: "string" },
emp_first_name : { type: "string" }
}
},
data: function(response) {
return response.GridResult;
},
total: function(response) {
$("#totalRows").text(response.total);
return response.total;
}
},
}
pageable: {
pageSizes: true,
},
columns: [
{ field: "a_id",width:"17%",title: "A ID",headerTemplate: '<span title="A ID" style="font-weight: 300; color:#333">A ID</span>',template:"<a class='link' style='cursor:pointer'>#=a_id#</a>" },
{ field: "emp_last_name",width:"15%",title: "Last Name",template:"<span>#=emp_last_name#</span>",headerTemplate: '<span title="Employee" style="font-weight: 300; color:#333">Last Name</span>'},
{ field: "emp_first_name",width:"15%",title: "First Name",template:"<span>#=emp_first_name#</span>",headerTemplate: '<span title="Employee" style="font-weight: 300; color:#333">First Name</span>'},
{ field: "a_percentage", title: "percentage value",width:"15%",template: "#=getPercentage(a,a_percentage)#" }
]
});
As you can see that I have created the grid using ajax call in it.
when the grid loads, it must be in sorted form based upon the column named as "a_percentage". The value of "a_percentage" column is evaluated using a method named as "getPercentage".
I have implemented the sorting logic in this grid but it restrict the user to click on the sortable column i.e. a_percentage.
I don't want to sort the data by clicking on this column.
whenever the grid loads, it must be sorted in descending order based upon the "a_percentage" column.
please help me that how can i achieve this functionality.
It is possible to configure the Grid's DataSource to sort the data initially:
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-sort
dataSource: {
// ...
sort: { field: "a_percentage", dir: "desc" }
// ...
serverPaging: true,
serverSorting: true
}
Note that all data operations must be performed either on the client, or on the server. Since you are using server paging, also set serverSorting and serverFiltering to true
http://docs.telerik.com/kendo-ui/framework/datasource/overview#mixed-data-operations-mode

JQgrid not showing data while rows are generating

Jqgrid is not showing JSON data, however rows are generating
Server side code:
public JsonResult Denominations()
{
.
.
int counter = 0;
var jsonData = new
{
total = result.UserObject.Count,
page = 1,
rows = (
from p in result.UserObject
select new
{
id = ++counter,
cell = new string [] {
p.CurrencyID.ToString(),
p.DenominationID.ToString(),
p.DenominationName.ToString(),
p.DenominatorCount.ToString(),
p.Multiplier.ToString(),
p.TenderID.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Data from server side is like this:
{"total":1,"page":1,"rows":[{"id":1,"cell":["1","1","Penny","0","0.0100","1"]}]}
JavaScript code:
$("#denominators").jqGrid({
url: '/Denominations?tenderid=1&currencyid=1',
contentType: "application/json",
datatype: "json",
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
repeatitems: false,
cell: 'cell',
id: 'id',
userdata:'userdata'
},
mtype: "GET",
colNames: ["CurrencyID", "DenominationID", "TenderID", "Multiplier", "DenominationName", "DenominatorCount"],
colModel: [
{ name: "currencyid", width: 80, align: "center" },
{ name: "denominationid", width: 90, align: "center" },
{ name: "tenderid", width: 250 },
{ name: "multiplier", width: 250 },
{ name: "denominationname", width: 95 },
{ name: "denominatorcount", width: 95 },
],
height: 'auto',
loadonce: true,
sortname: "DenominationID",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true
});
View:
<table id="denominators" ></table>
View creates the grid with column header however rows are generated but rows did not any data int.
You use wrong jsonReader. To be exactly the property repeatitems: false is false. It means that the format of every item in rows array is
{
"currencyid": "1",
"denominationid": "1",
"tenderid": 1,
"denominationname": "Penny",
"denominatorcount": "0",
"multiplier": "0.0100"
}
You use
{
"id": 1,
"cell": [
"1",
"1",
"Penny",
"0",
"0.0100",
"1"
]
}
instead. So you should remove jsonReader because the format of input data corresponds the default jsonReader, but you need still reorder the columns of the grid or change the order of items which you place in cell array so that it corresponds the order of columns in colModel.
Additional remarks: you use wrong value for total. It should be the number of pages. By the way you use loadonce: true. In the case you can remove "total":1,"page":1 part from the response and just return array of named items. You should just choose the names of columns the same as the names of properties if the items.

Web API Odata not returning correct metadata

I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};

Kendo data grid - how to set column value from nested JSON object?

I have JSON with structure like this:
"id":1,
"user_role":"ADMIN",
"state":"ACTIVE",
"address":{
"street":"test 59",
"city":"City test",
"post_number":"25050"
},
How I should to pass values of address.street into column using setting in fields and model?
Many thanks for any advice.
If you want to show all values in a single column do what #RobinGiltner suggests.
If you want to show each member of address in a different column you can do:
var grid = $("#grid").kendoGrid({
dataSource: data,
editable: true,
columns : [
{ field: "id", title: "#" },
{ field: "user_role", title: "Role" },
{ field: "address.street", title: "Street" },
{ field: "address.city", title: "City" },
{ field: "address.post_number", title: "Post#" }
]
}).data("kendoGrid");
i.e.: use address.street as name of the field. This would allow you even to edit the field as in the example: http://jsfiddle.net/OnaBai/L6LwW/
#OnaBai Good and intuitive answer. Sadly Kendo doesn't always work to well with nested properties this way. For example formating doesn't work. Here is an example using data source shema to access nested properties. This way you can use formatting but you have to specify a schema model.
var grid = $("#grid").kendoGrid({
dataSource: {
data: data,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
user_role: { type: "string" },
address_street: { from: "address.street" },
address_city: { from: "address.city" },
address_post_number: {
type: "number",
from: "address.post_number"
}
}
}
}
},
columns: [{
field: "id",
title: "#"
}, {
field: "user_role",
title: "Role"
}, {
field: "address_street",
title: "Street"
}, {
field: "address_city",
title: "City"
}, {
field: "address_post_number",
title: "Post#",
format: "{0:0#######}"
}]
}).data("kendoGrid");
Jsfiddle: http://jsfiddle.net/wtj6mtz2
See also this Telerik example for accessing nested properties.
You could use a template on the grid column definition to display whichever pieces of the address you wanted.
{ field: 'address', title: 'Address', template: '#= address.street# #= address.city#, #= address.post_number# ' },
See documentation for kendo column template. http://docs.telerik.com/kendo-ui/api/web/grid#configuration-columns.template
See sample at http://jsbin.com/gizab/1/edit

Text box search and filter the values in grid view using Kendo UI HTML5

how can I filter Grid filtering based on values we entered in text box.
I have one text box out side the grid and i want to search the whole grid based on the values i entered in textbox.
step1:
<input id="btnSearch" type="button" value="search" />
<div id="grid">
step2:bing grid value from source
var gridResult = $("#grid").kendoGrid({
dataSource: { data: database },
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
{
field: "id",
title: "ID"
},
{
field: "x",
title: "x"
},
{
field: "y"
},
{
field: "z"
},
{
field: "p"
}
]
});
step3: script for text box .that is wat ever the values i have typed in text box if the values match in grid the result should show in grid.
$("#btnSearch").click(function () {
$filter = new Array();
$x = $("#txtSearch").val();
if ($x) {
$filter.push({ field:"x", operator:"contains", value:$x});
}
gridResult.datasource.filter($filter);
});
Where you have:
gridResult.datasource.filter($filter);
it should read:
gridResult.data("kendoGrid").dataSource.filter($filter);
the s in dataSource is uppercase
you have to add data("kendoGrid") either here or when you declare var gridResult.