Bind Telerik treeview to Telerik Grid - asp.net-mvc

How to bind Telerik MVC TreeView to a Telerik MVC Grid in RAZOR engine. I got a dashboard which has a Telerik MVC Grid bound with single column data ie only one column in a Grid. And I need to bind Telerik MVC TreeView to each Item in the Grid ie each cell. ie each cell in the Telerik Grid should be shown in TreeView, just as shown below :

It is not possible out of the box. But you can use templates:
http://demos.telerik.com/aspnet-mvc/treeview/templates
You can use ClientTemplate for column and load treeview to it by ajax from another child view. Downloading is started on RowDataBound event.
Example:
GridView
<script type="text/javascript">
function onRowDataBound(e) {
var grid = $(this).data('tGrid');
var dataItem = e.dataItem;
var replacement = $('div.e-marker-detailarea', e.detailRow);
$.ajax(
{
url: '#Url.Action("GetTreeView", "SomeController")',
data: {value: dataItem.TreeViewValue},
type: 'POST',
error: function() {
alert("Error!!!")
},
success: function (data, textStatus, XMLHttpRequest) { replacement.html(data); }
}
);
}
}
#(
Html.Telerik().Grid<GridModel>()
.Name("GridModel")
.DataBinding(b=>b.Ajax().Select("GridBind", "SomeController"))
.Columns(columns=>
{
columns.Bound(b => b.TreeViewValue).Title("Комментарий").ClientTemplate("<div class=\"e-marker-detailarea\"></div>");
})
.ClientEvents(c => c.OnRowDataBound("onRowDataBound"))
)
ChildTreeView:
#{
Html.Telerik().TreeView()
.Name("TreeView")
.Items(item =>
{
item.Add()
.Text("Mail")
.ImageUrl("~/Content/PanelBar/FirstLook/mail.gif")
.ImageHtmlAttributes(new { alt = "Mail Icon" })
.Items(subItem =>
{
subItem.Add()
.Text("Personal Folders")
.ImageUrl("~/Content/PanelBar/FirstLook/mailPersonalFolders.gif")
.ImageHtmlAttributes(new { alt = "Personal Folders Icon" });
});
item.Add()
.Text("Contacts")
.ImageUrl("~/Content/PanelBar/FirstLook/contacts.gif")
.ImageHtmlAttributes(new { alt = "Contacts Icon" })
.Items((subItem) =>
{
subItem.Add()
.Text("My Contacts")
.ImageUrl("~/Content/PanelBar/FirstLook/contactsItems.gif")
.ImageHtmlAttributes(new { alt = "Contact Icon" });
});
item.Add()
.Text("Tasks")
.ImageUrl("~/Content/PanelBar/FirstLook/tasks.gif")
.ImageHtmlAttributes(new { alt = "Tasks Icon" })
.Items((subItem) =>
{
subItem.Add()
.Text("My Tasks")
.ImageUrl("~/Content/PanelBar/FirstLook/tasksItems.gif")
.ImageHtmlAttributes(new { alt = "Task Icon" });
});
})
}
Controller:
ActionResult GridView()
{
return View();
}
[GridAction]
ActionResult GridBind()
{
//initialize IEnumerable<GridModel> gridModelList
return View(new GridModel(gridModelList));
}
ActionResult GetTreeView(TreeViewValue treeViewValue)
{
//some calculations to get model
return PartialView("ChildTreeView", model)
}

Related

Persist state, value and data of dropdown in Kendo Grid MVC

I have a dropdown by which I select the category of my data in a Kendo grid in my MVC app.
#(Html.Kendo().DropDownList()
.Name("kind")
.HtmlAttributes(new { style = "width:18%" })
.OptionLabel("Select Category")
.DataTextField("Cat_Title")
.DataValueField("Cat_ID")
.Events(e => e.Change("onChange"))
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Overview_Get_Categories", "Announcements");
});
})
)
I need to save my selected value so if the user return back can load his search. I have the following code for my grid
<div class="box-col">
Save State
Load State
and in js
<script>
$(document).ready( function () {
var grid = $("#grid").data("kendoGrid");
$("#save").click(function (e) {
e.preventDefault();
localStorage["kendo-grid-options"] = kendo.stringify(grid.getOptions());
});
$("#load").click(function (e) {
e.preventDefault();
var options = localStorage["kendo-grid-options"];
if (options) {
grid.setOptions(JSON.parse(options));
}
});
});
How can I save the value from the dropdown? and then reload it?
any idea? Thank you!

#Html.EnumDropDownListFor searchable, how to do it?

I am trying to make the helper #Html.EnumDropDownListFor searchable with an input tag on it. That way I can type to search for an item in the huge list. I preferably want to make this hard coded without other plugins. Can someone help me?
Here is the code:
<div>Escolha aqui o banco de sua preferência:</div>
#Html.EnumDropDownListFor(model => model.BankPaymentMethods, " ", htmlAttributes: new {#class = "form-control"})
The EnumDropDownListFor helper only generates <select> elements. The closest you can get without a plugin would be an input with a datalist and the list attribute.
Assuming your enum is called BankPaymentMethod and BankPaymentMethods is an IEnumerable of some sort, and your model has a PaymentMethod property:
#Html.TextBoxFor(m => m.PaymentMethod, new { #class = "form-control", list = "payment-methods" })
<datalist id="payment-methods">
#foreach(var method in Model.BankPaymentMethods)
{
<option value="#method">#method</option>
}
</datalist>
For reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist.
Typically its done inside a text box, I guess you can do it inside a Select by appending the value and name also you need to paste your VM or selectList VMModel. I have made some assumptions, code is not tested, but with a couple change and hopefully it will help you.
#Html.TextBoxFor(model => model.BankPaymentID)
#section scripts{
// you can update to the latest version of Jquery-ui, I put in the most compatible version for you
<script src="~/Scripts/jquery-ui-1.15.1.js">script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.15.1/themes/base/jquery-ui.css">
<script>
$(function () {
$("#BankPaymentID").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Searchable")', // server action
datatype: "json",
data: {
term: request.term // this what you are searching
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
BankPaymentID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$.get("/Home/GetBankPaymentMethods", { BankPaymentID: ui.item.BankPaymentID }, function (data) {
$("#PaymentID").empty();
$.each(data, function (index, row) {
$("#PaymentID").append("<option value='" + row.PaymentID + "'>" + row.PaymentName + "option>")
});
});
}
})
})
script>
}
Controller Searchable Action
public ActionResult Searchable(string term)
{
if (!String.IsNullOrEmpty(term))
{
var list = db.banks.Where(c=>c.PaymentName.ToUpper().Contains(term.ToUpper())).Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
else
{
var list = db.banks.Select(c => new { Name = c.PaymentName, ID = c.BankPaymentID })
.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
}

how to implement kendo autocomplete dropdown in MVC kendo treelist editor

Screen
Code
In this screen, we have used kendo treelist. I need to implement autocomplete dropdown in CODE column. How can i do that?
Try this
var ac = Html.Kendo()
.AutoComplete()
.Name("CodeAutoComplete")
.DataSource(ds =>
{
ds.Read(read =>
{
read.Url("youraction");
});
ds.ServerFiltering(true);
});
var treeGrid = Html.Kendo()
.TreeList<YourModel>()
.Name("SomeTreeList")
.Columns(columns =>
{
columns.Add().Field(t => t.YourProperty).Editor(ac.ToHtmlString());
});
I solve my above problem as per given below jquery code.
var input2 = jQuery('<input id="WEIGHT_UOM" value="' + e.model.WEIGHT_UOM + '">');
input2.appendTo($(".k-grid-edit-row").find("[data-container-for='WEIGHT_UOM']"))
//create AutoComplete UI component
$("#WEIGHT_UOM").kendoAutoComplete({
dataTextField: "ProjectDesc",
// template: '${ data.ProjectDesc }' + '<span style="display:none;> ${ data.ProjectDesc }</span>',
select: function (org1) {
var dataItem1 = this.dataItem(org1.item.index());
// model.set("field1", dataItem.field1);
e.model.set("WEIGHT_UOM", dataItem1.ProjectID);
},
dataSource: {
type: "jsonp",
serverFiltering: true,
transport: {
read: "#Url.Action("GetISOUnitAutoComp",
"DashBoard")",
}
}
});

Cannot export hidden columns in Kendo Grid

I want to hide some columns on Kendo Grid and export them to the excel as the visible columns. However, using Hidden(true) or Visible(false) does not make any sense and these fields are not exported. The workarounds on this page is not working. Any idea?
View:
#(Html.Kendo().Grid<ContactViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Visible(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Controller"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Controller"))
.ServerOperation(false)
.PageSize(12)
)
)
)
See this solution Plunker, suggested solution on Telerik website.
To show column in your export functionality, bind this 'excelExport' event of that grid.
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
// e.sender.showColumn(0); for demo
// for your case show column that you want to see in export file
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
});
Demo: Hide First column and show in export file
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/excel-export">
<style>
html {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/jszip.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid" style="width: 900px"></div>
<script>
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "Kendo UI Grid Export.xlsx",
proxyURL: "http://demos.telerik.com/kendo-ui/service/export",
filterable: true
},
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
},
schema: {
model: {
fields: {
UnitsInStock: {
type: "number"
},
ProductName: {
type: "string"
},
UnitPrice: {
type: "number"
},
UnitsOnOrder: {
type: "number"
},
UnitsInStock: {
type: "number"
}
}
}
},
pageSize: 7
},
sortable: true,
pageable: true,
columns: [{
width: "10%",
field: "ProductName",
title: "Product Name",
hidden: true
}, {
width: "10%",
field: "UnitPrice",
title: "Unit Price"
}, {
width: "10%",
field: "UnitsOnOrder",
title: "Units On Order"
}, {
width: "10%",
field: "UnitsInStock",
title: "Units In Stock"
}]
});
var exportFlag = false;
$("#grid").data("kendoGrid").bind("excelExport", function (e) {
if (!exportFlag) {
e.sender.showColumn(0);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(0);
exportFlag = false;
}
});
</script>
</div>
</body>
</html>
I try with this example also, it is same as my previous answer just jQuery binding event will be different.
You just need to do changes in code by adding grid event Events(x => x.ExcelExport("excelExport")) and jQuery function excelExport(e) {}.
Also use only Hidden(true) to hide grid column.
ViewModel is something like this :
public class ContactViewModel
{
public string NameSurname { get; set; }
public string InstituteName { get; set; }
public string CityName { get; set; }
public string RegionName { get; set; }
public string ContactMobile { get; set; }
public string ContactAddress { get; set; }
}
Controller will be:
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Index_Read([DataSourceRequest]DataSourceRequest request)
{
var listOfContactViewModel = new List<ContactViewModel>() {
new ContactViewModel(){ NameSurname = "N1", InstituteName = "I1", CityName ="C1",RegionName = "R1",ContactMobile = "M1", ContactAddress = "C1" },
new ContactViewModel(){ NameSurname = "N2", InstituteName = "I2", CityName ="C2",RegionName = "R2",ContactMobile = "M2", ContactAddress = "C2" },
new ContactViewModel(){ NameSurname = "N3", InstituteName = "I3", CityName ="C3",RegionName = "R3",ContactMobile = "M3", ContactAddress = "C3" },
new ContactViewModel(){ NameSurname = "N4", InstituteName = "I4", CityName ="C4",RegionName = "R4",ContactMobile = "M4", ContactAddress = "C4" },
new ContactViewModel(){ NameSurname = "N5", InstituteName = "I5", CityName ="C5",RegionName = "R5",ContactMobile = "M5", ContactAddress = "C5" }
};
return Json(listOfContactViewModel.ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
}
And View for this:
<h2>Index</h2>
#(Html.Kendo().Grid<KendoUIMVC5.Models.ContactViewModel>()
.Name("Grid")
.Events(x => x.ExcelExport("excelExport"))
.Columns(columns =>
{
columns.Bound(m => m.NameSurname).Title("Name Surname").Width("%100");
columns.Bound(m => m.InstituteName).Title("Institute Name").Width("250px");
columns.Bound(m => m.CityName).Title("City").Width("145px");
columns.Bound(m => m.RegionName).Title("Region").Width("145px");
columns.Bound(m => m.ContactMobile).Title("Mobile").Width("125px");
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(true); //I want to export these fields
columns.Bound(m => m.ContactAddress).Title("Address").Hidden(false); //I want to export these fields
})
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<button class="btn btn-primary btn-xs pull-right k-button k-button-icontext k-grid-excel">
<span class="k-icon k-excel"></span>
Liste (xls)
</button>
</div>
</text>);
})
.Excel(excel => excel
.FileName("List.xlsx")
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("Excel_Export_Save", "Test"))
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Index_Read", "Test"))
.ServerOperation(false)
.PageSize(12)
)
)
<script type="text/javascript">
var exportFlag = false;
function excelExport(e)
{
if (!exportFlag) {
e.sender.showColumn(5);
e.sender.showColumn(6);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn(5);
e.sender.hideColumn(6);
exportFlag = false;
}
}
</script>
...
columns.Bound(x => x.Id).Visible(false);
columns.Bound(x => x.Siege).Width(150);
columns.Bound(x => x.Societe).Width(150);
columns.Bound(x => x.Matricule).Width(100).Hidden(true);
columns.Bound(x => x.Civilite).Width(80);
...
var exportFlag = false;
$("#myGrid").data("kendoGrid").bind("excelExport", function (e) {
var grid = e.sender;
var columns = grid.columns;
if (!exportFlag) {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == true) {
col.hidden = false;
}
});
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
}
else {
$.each(columns, function (index, value) {
var col = this;
if (col.hidden == false) {
col.hidden = true;
}
});
exportFlag = false;
}
});

Auto-complete doesn't work as expected

I tried to implement this in MVC 5 with jquery ui 1.10.2
#{
ViewBag.Title = "Home Page";
Layout = null;
}
<p>
Enter country name #Html.TextBox("Country")
<input type="submit" id="GetCustomers" value="Submit" />
</p>
<span id="rData"></span>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/AutoCompleteCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item.Country, value: item.Country };
}));
}
});
}
});
})
</script>
the server side is
...
[HttpPost]
public JsonResult AutoCompleteCountry(string term)
{
// just something to return..
var list = new List<string>() { "option1", "option2", "option3"};
var result = (from r in list
select r);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
I have two issues
1. it open up drop down autocomplete with 3 dots but without the actual strings.
2. It has this annoying message of "3 results were found" - I'd like to eliminate it..
DO you have any idea how to face those two issues or neater way to implement it in MVC5?
The 3 bullet points and "3 results were found" is because you are missing the jQuery UI css file. That file will format a drop down that will look a lot better. You can customize how the dropdown looks with additional css.
Also, you are seeing 3 empty results because your JS is referencing item.Country ...
return { label: item.Country, value: item.Country };
But your server code is just sending 3 strings.
new List<string>() { "option1", "option2", "option3"};
To fix, change your JS to just reference the item (the string) ...
return { label: item, value: item};
OR, change your server code to send more complex objects
new List<Object>() { new { Country = "option1" }, new { Country = "option2" }, new { Country = "option3" } };
use return data in place of return { label: item.Country, value: item.Country };

Resources