Kendo: How do I create a recursive hieiarchy in the TreeView? - javascript

I am using Kendo UI and trying to figure out how to get the TreeView to display a recursive hierarchy. Firstly, here is my model (I am retrieving a list of these objects by OData):
public class PageTreeItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool IsEnabled { get; set; }
public PageTreeItem[] SubPages { get; set; }
}
And here is my JavaScript:
var PagesDS = new kendo.data.HierarchicalDataSource({
type: "odata",
transport: {
read: {
url: "/odata/cms/PageTree",
dataType: "json"
}
},
schema: {
data: function (response) {
return response.value;
},
total: function (response) {
return response.value.length;
},
model: {
id: "Id",
children: "SubPages"
}
}
});
PagesDS.read();
$("#treeview").kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: PagesDS,
dataTextField: ["Name"]
});
And finally, the markup:
<div id="treeview"></div>
<script id="treeview-template" type="text/kendo-ui-template">
#= item.Name #
</script>
I can only ever get the top-level items to display. Obviously, setting the "children" property in schema-> model is not working. How do I achieve what I want?

OK, ignore.. my problem was with the SubPages not actually being returned in the first place... oops! I simply assumed they were automatically serialized with everything else. I needed to provide the $expand option in my OData query, as follows:
read: {
url: "/odata/cms/PageTree?$expand=SubPages",
dataType: "json"
}

Related

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

Data model is not getting deserialised in controller

Here is my model class
public class ProductModel
{
public Product {set;set;} // Product is one more class
}
I am using below javascript code to get partial view but 'model' is not getting deserialised in controller...What I am missing?
Storing data in a HTML attribute as shown below
JavaScriptSerializer serializer = new JavaScriptSerializer();
var jsonObject = serializer.Serialize(obj)
<span data-singleproduct="#jsonObject" id="#mprodid" class="ShowProductModal">Find out more..</span>
Used jQuery to call partial page and popup
$('.ShowProductModal').on('click', function () {
var model = $(this).data('singleproduct');
//I can see data of variable model here in developer tool
$("#ProductModal").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: '',
modal: true,
open: function () {
$(this).load('ShowProductModal', model );
},
buttons: {
}
});
return false;
});
Here is my controller code
public PartialViewResult ShowProductModal(ProductModel product)
{
return PartialView("ProductModal", product);
}
product always comes as null!!!
If I change ProductModel to Product , then it will work... ! CAN SOMEONE HELP ME?
public PartialViewResult ShowProductModal(Product product)
{
return PartialView("ProductModal", product);
}
You should try
$(this).load('ShowProductModal', { product: model });
And declare your method like this:
[HttpPost]
public PartialViewResult ShowProductModal([FromBody] JObject data)
{
var product = data["product"].ToObject<ProductModel>();
return PartialView("_SC5ProductModal", product);
}

Filtering in Telerik Kendo Multiselect

Hi I have a simple select in my mvc view....
<select id="msProducts" multiple style="width:100%;"></select>
which is converted to a Kendo Multiselect using Javascript/JQuery
$(document).ready(function () {
//products multi-select
$("#msProducts").kendoMultiSelect({
placeholder: "Select Product(s)",
dataTextField: "ProductNameText",
dataValueField: "ProductNameValue",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: {
url: "Home/Products"
}
}
}
});
});
My Contoller has:
'GET: Home/Products
<HttpGet>
Function Products() As JsonResult
Dim DiaryProductList As List(Of ProductsModel) = ProductsModel.GetProducts
Return Json(DiaryProductList , JsonRequestBehavior.AllowGet)
End Function
My ProductsModel Class is:
Public Class ProductsModel
Public Property ProductNameText As String
Public Property ProductNameValue As String
Public Shared Function GetProducts() As List(Of ProductsModel)
Dim ProductList = New List(Of ProductsModel)
Dim dc As New DBDataContext
Try
Dim ProductsQuery = (From pIn dc.Products
Where p.ProductStatus <> "discontinued"
Select New With {.ProductNameValue = p.ProductName,
.ProductNameText = p.ProductName}).OrderBy(Function(lst) lst.ProductNameValue)
For Each r In ProductsQuery
ProductList.Add(New ProductsModel() With {.ProductNameValue = r.ProductNameValue,
.ProductNameText = r.ProductNameText})
Next
Catch ex As Exception
ProductList.Add(New ProductsModel() With {.ProductNameValue = "",
.ProductNameText = ex.Message})
Finally
dc.Connection.Close()
End Try
Return ProductList
End Function
End Class
My problem is that although the muti-select gets populated (with some 5000+ products) the dropdown is not filtering as a user types. For example if I beging typing the word CAKE. As soon as I type C the I-beam disappears and after a second or two the dropdown drops for a brief moment and then disappears clearing the multi-select completely. The only way I can populate at the moment is type the letter A, wait and then scroll through the complete list and select what I need, repeating for each item I need. Have I missed something? Should I introduce paging in order to limit the data?
Thanks
Based on the links provided by Ademar I've changed my code so that I have the following which works....
//products multi-select
// ms datasource
var ms_dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/Products",
type: "GET",
dataType: "json"
}
},
schema: {
model: {
fields: {
"ProductName": {
type: "string"
}
}
}
}
});
// ms widget options
var ms_options = {
autoBind: false,
minLength: 4,
maxSelectedItems: 25,
dataTextField: "ProductName",
dataValueField: "ProductName",
filter: "contains",
placeholder: "Select Product(s)",
dataSource: ms_dataSource
};
// create ms widget
$("#msProducts").kendoMultiSelect(ms_options);
I have also amended my Product Class so that it give just a list of product names that I use as both the tag text and value in the multiselect.

Select2 limit number of tags

Is there a way to limit the number of tags a user can add to an input field using Select2?
I have:
$('#tags').select2({
containerCssClass: 'supplierTags',
placeholder: "Usual suppliers...",
minimumInputLength: 2,
multiple: true,
tokenSeparators: [",", " "],
placeholder: 'Usual suppliers...',
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {id: 0, name: term};
}
},
id: function(e) {
return e.id + ":" + e.name;
},
ajax: {
url: ROOT + 'Call',
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
call: 'Helpers->tagsHelper',
q: term
};
},
results: function(data, page) {
return {
results: data.tags
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
name: item[1]
});
});
callback(data);
}
});
It would be great if there could be/is a simple parameter like limit: 5 and a callback to fire when the limit is reached.
Sure, with maximumSelectionLength like so:
$("#tags").select2({
maximumSelectionLength: 3
});
Maximum Selection Length
Select2 allows the developer to limit the number of items that can be
selected in a multi-select control.
http://ivaynberg.github.io/select2/
It has no native callback, but you can pass a function to formatSelectionTooBig like this:
$(function () {
$("#tags").select2({
maximumSelectionLength: 3,
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
});
http://jsfiddle.net/U98V7/
Or you could extend formatSelectionTooBig like this:
$(function () {
$.extend($.fn.select2.defaults, {
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
$("#tags").select2({
maximumSelectionLength: 3
});
});
Edit
Replaced maximumSelectionSize with the updated maximumSelectionLength. Thanks #DrewKennedy!
method 1
$("#tags").select2({
maximumSelectionLength: 3
});
method 2
<select data-maximum-selection-length="3" ></select>
list of all available options https://select2.org/configuration/options-api
The accepted answer doesn't mention that the maximumSelectionLength statement should be inside the document.ready function. So for anyone who is having the same trouble I did, here is the code that worked for me.
$(document).ready(function() {
$("#id").select2({
maximumSelectionLength: 3
});
});
$("#keywords").select2({
tags : true,
width :'100%',
tokenSeparators: [','],
maximumSelectionLength: 5,
matcher : function(term,res){
return false;
},
"language": {
'noResults': function(){
return "Type keywords separated by commas";
}
}
}).on("change",function(e){
if($(this).val().length>5){
$(this).val($(this).val().slice(0,5));
}
});
Try like this. It'll short up to 5 keywords.
This is not working for me, I am getting query function not defined for Select2, so here is another workaround.
var onlyOne=false;
$("selector").select2({
maximumSelectionSize:function(){
if(onlyOne==true)
return 1;
else
return 5;
}
});
This setting can be defined as function and it's called every time you start searching something.
Important thing is that you have something defined outside this select2 closure so you can check it (access it). In this case you could somewhere in your program change value of onlyOne and of course this returned limit can also be dynamical.
This is working for me.
$("#category_ids").select2({ maximumSelectionLength: 3 });
Send the Get Request to action method and the Map the class properties to drop down id and text property
$("#DropDownId").select2({
minimumInputLength: 3,
maximumSelectionLength: 10,
tags: [],
ajax: {
url: "#Url.Action("ActionName", "ControllerName")",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
Title: params.term // search term
};
},
processResults: function (response) {
return {
results: $.map(response, function (item) {
return {
text: item.Title,
id: item.Id
}
})
};
}
}
});
Action Method
[HttpGet]
public JsonResult ActionName(string Title)
{
ClassName obj= new ClassName ();
obj.Title = "PMPAK";
obj.Id= -1;
obj.Add(nibafInstitute);
return Json(obj, JsonRequestBehavior.AllowGet);
}
public class ClassName
{
public int Id{ get; set; }
public string Title { get; set; }
}

Exporting all data from Kendo Grid datasource

I followed that tutorial about exporting Kendo Grid Data : http://www.kendoui.com/blogs/teamblog/posts/13-03-12/exporting_the_kendo_ui_grid_data_to_excel.aspx
Now I´m trying to export all data (not only the showed page) ... How can I do that?
I tried change the pagezise before get the data:
grid.dataSource.pageSize(grid.dataSource.total());
But with that my actual grid refresh with new pageSize. Is that a way to query kendo datasource without refresh the grid?
Thanks
A better solution is to generate an Excel file from the real data, not from the dataSource.
1]
In the html page, add
$('#export').click(function () {
var title = "EmployeeData";
var id = guid();
var filter = $("#grid").data("kendoGrid").dataSource._filter;
var data = {
filter: filter,
title: title,
guid: id
};
$.ajax({
url: '/Employee/Export',
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (result) {
window.location = kendo.format("{0}?title={1}&guid={2}", '/Employee/GetGeneratedExcel', title, id);
}
});
});
2]
Add a method "Export" to the controller:
[HttpPost]
public JsonResult Export(KendoGridFilter filter, string guid)
{
var gridRequest = new KendoGridRequest();
if (filter != null)
{
gridRequest.FilterObjectWrapper = filter.Filters != null ? filter.ToFilterObjectWrapper() : null;
gridRequest.Logic = filter.Logic;
}
var query = GetQueryable().AsNoTracking();
var results = query.FilterBy<Employee, EmployeeVM>(gridRequest);
using (var stream = new MemoryStream())
{
using (var excel = new ExcelPackage(stream))
{
excel.Workbook.Worksheets.Add("Employees");
var ws = excel.Workbook.Worksheets[1];
ws.Cells.LoadFromCollection(results);
ws.Cells.AutoFitColumns();
excel.Save();
Session[guid] = stream.ToArray();
return Json(new { success = true });
}
}
}
3]
Also add the method "GetGeneratedExcel" to the controller:
[HttpGet]
public FileResult GetGeneratedExcel(string title, string guid)
{
// Is there a spreadsheet stored in session?
if (Session[guid] == null)
{
throw new Exception(string.Format("{0} not found", title));
}
// Get the spreadsheet from session.
var file = Session[guid] as byte[];
string filename = string.Format("{0}.xlsx", title);
// Remove the spreadsheet from session.
Session.Remove(title);
// Return the spreadsheet.
Response.Buffer = true;
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename);
}
Also see this project on github.
See this live example project where you can export the Employees to Excel. (Although this returns filtered data, but you can modify the code to ignore the kendo grid filter and always return all data.
Really old question but:
To export all the pages use excel.allPages:
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
allPages: true
},
// ....
});
See Example
Grid toolbar
..
.ToolBar(toolbar =>
{
toolbar.Template(
#<text>
#Html.Kendo().Button().Name("grid-export").HtmlAttributes(new { type = "button", data_url = #Url.Action("Export") }).Content("Export").Events(ev => ev.Click("exportGrid"))
</text>);
})
..
Endpoint export function
public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
DemoEntities db = new DemoEntities();
byte[] bytes = WriteExcel(db.Table.ToDataSourceResult(request).Data, new string[] { "Id", "Name" });
return File(bytes,
"application/vnd.ms-excel",
"GridExcelExport.xls");
}
a javascript function to generate grid remote export url with all specified parameters
function exportGrid() {
var toolbar = $(this.element);
var gridSelector = toolbar.closest(".k-grid");
var grid = $(gridSelector).data("kendoGrid");
var url = toolbar.data("url");
var requestObject = (new kendo.data.transports["aspnetmvc-server"]({ prefix: "" }))
.options.parameterMap({
page: grid.dataSource.page(),
sort: grid.dataSource.sort(),
filter: grid.dataSource.filter()
});
url = url + "?" + $.param({
"page": requestObject.page || '~',
"sort": requestObject.sort || '~',
"pageSize": grid.dataSource.pageSize(),
"filter": requestObject.filter || '~',
});
window.open(url, '_blank');
}
For detailed solution see my sample project on Github
where u can export grid server side with current configuration (sorting, filtering, paging) using helper function

Categories

Resources