How does the model structure look like for Kendo TreeView, to bind remote data? - model-view-controller

How does the model structure look like for Kendo TreeView, to bind remote data

We have a tree displaying system locations which have hierarchical structure. We use the following code:
C# code:
[HttpPost]
public async Task<ActionResult> GetChildrenAsync(long? parentId)
{
//retrieving location's children by parentId
//DTO has ChildrenCount field that shows how many children has any particular location
return new JsonResult
{
Data = locations.Select(x => new
{
LocationId = x.Id,
Name = x.Name,
HasChildren = x.ChildrenCount > 0
}),
MaxJsonLength = Int32.MaxValue
};
}
JS code:
var locationDataSource = new kendo.data.HierarchicalDataSource({
transport: {
type: "json",
read: {
url: "#Url.Action("GetChildren", "Location")",
type: "POST"
},
parameterMap: function (data) {
return { parentId: data.LocationId };
}
},
schema: {
model: {
id: "LocationId",
hasChildren: "HasChildren"
}
}
});
var kendoTree = $("#location-tree").kendoTreeView({
dataSource: locationDataSource,
dataTextField: "Name"
});

Related

Kndo TreeView LoadOnDemand not hitting the server

for my kendo treeview, i set load on demand to true but it is not hitting the server to load childs, because the 'children' property is set for the datasource model, even its empty.
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
type: 'POST',
contentType: "application/json; charset=utf-8",
url: obj.DataSourcesURL,
dataType: "json"
},
parameterMap: function (options) {
if (!options.Id) {
options.Id = null;
}
if (options.filter) {
options.Search = options.filter.filters[0].name;
}
else {
options.Search = '';
}
return JSON.stringify(options);
}
},
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: "hasChild",
children:'items',
id: "Id"
}
}
});
And treeView code is
$treeView.kendoTreeView({
dataTextField: 'Description',
checkboxes: {
checkChildren: true
},
dataSource: homogeneous,
loadOnDemand: loadOnDemand,
check: function () {
var checkedNodes = [];
var treeView = $treeView.data("kendoTreeView");
getCheckedNodes(treeView.dataSource.view(), checkedNodes);
setMessage(checkedNodes.length);
},
dataBound: function (e) {
if (e !== undefined)
resetCheckedNodes(e.sender.dataItems());
},
messages: {
loading: "Laden..."
},
expand: function (e) {
var dataItem = this.dataItem(e.node);
}
});
Try to set hasChildren like this in your schema:
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: function(e) {
return e.items && e.items.length;
},
children:'items',
id: "Id"
}
}
And also from your question I am not sure do you even get any data or it is only Children data that is not returned. Maybe you could also show how your data structure look like.

Kendo treeview HierarchicalDataSource not showing child nodes

I have a kendo Treeview which is showing the parent nodes but the child nodes are not seen. Can anyone tell me where am i going wrong. I am new to this concept. I followed the below link but its not working.
http://demos.telerik.com/kendo-ui/treeview/remote-data-binding
function treeView() {
var treeM = new kendo.data.HierarchicalDataSource({
schema: {
data: function (response) {
console.log("response" + JSON.stringify(response));
var rdata = {};
if (response.d) {
rdata = JSON.parse(response.d);
}
else {
rdata = response;
}
return rdata; // ASMX services return JSON in the following format { "d": <result> }.
},
model: {
hasChildren: true,
id: "ID",
expanded: true,
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
},
},
transport: {
read: {
url: "/getParent",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap:');
return JSON.stringify({ "LinksJson": data });
console.log(JSON.stringify(data));
} else {
return data;
}
}
}
});
$("#treeview1").kendoTreeView({
dataSource: treeM,
dataValueField: "ID",
dataTextField: ["LINK","Name"]
});
}
$("#treeview").on("click", ".k-in", function (e) {
var tree = $("#treeview").data('kendoTreeView');
tree.toggle($(e.target).closest(".k-item"));
});
$(document).ready(function () {
treeView();
});
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getParent()
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in context.Links
where x.ParentID == 68
select x;
var newQry = dataQuery.AsEnumerable().Select(c => new
{
ID = c.ID,
Name = c.Name,
Children = HasChildren(231)
});
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(newQry);
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool HasChildren(int ID)
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in contextLinks
where x.ParentID == ID
select x;
return dataQuery.AsEnumerable().Any();
}
}
Even when you try to view the child nodes, it will try to call getLinks and not the getreports.
From what i have seen , you should have only one method for getting parent and children. Can be an array inside each parent node.
Can you combine the data from GetReports method inside getlinks itsself and give it a shot.
You should try and get this working here with hardcoded values and then do configure with services.
http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#configuration-dataSource

Pass parameter as query string to kendo datasource create method

Scenario : consider we have two view-models use same data source masterDataSource, and we want to add a detail entity to master entity.
Question : how would you pass masterId as query string to the create method of datasource from those view-models:
var masterDataSource = new kendo.data.DataSource({
transport: {
create: {
url: function() {
return "/api/master/addItem?masterId=" + masterId;//<-- How to pass masterId form view-models
},
dataType: "json",
type: "POST"
},
},
schema: {
model: {
id: "id"
}
}
}
I found this solution:
var dynamicUrl = "/api/master/addItem?masterId=" + masterId;
masterDataSource.transport.options.read.url = dynamicUrl;

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

how to bind the dropdownlist using ajax

I need to bind the ddl values from another dropdownlist(ddl) result using ajax and mvc3
Related: how to get the result from controller in ajax json
Better try the below approach for cascading dropdownlist.
[Script]
function SetdropDownData(sender, args) {
$('#ShipCountry').live('change', function () {
$.ajax({
type: 'POST',
url: 'Home/GetCities',
data: { Country: $('#ShipCountry').val() },
dataType: 'json',
success: function (data) {
$('#ShipCity option').remove();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ShipCity').append(optionTag);
});
}
});
});
}
[Controller]
public IEnumerable<SelectListItem> Cities(string Country) // ShipCity is filtered based on the ShipCountry value
{
var Cities = new NorthwindDataContext().Orders.Where(c=>c.ShipCountry == Country).Select(s => s.ShipCity).Distinct().ToList();
List<SelectListItem> type = new List<SelectListItem>();
foreach (var city in Cities)
{
if (city != null)
{
SelectListItem item = new SelectListItem() { Text = city.ToString(), Value = city.ToString() };
type.Add(item);
}
}
return type;
}
public ActionResult GetCities(string Country)
{
return Json(Cities(Country), JsonRequestBehavior.AllowGet);
}

Resources