How do I show the row number in a Kendo UI Grid? The code I have is not working. The page displays the column but it's empty.
#{int counter = 1;}
#(Html.Kendo().Grid<QueueViewModel>()
.Name("Queue")
.Columns(columns =>
{
columns.Template(#<text><span>#counter #{ counter++; }</span></text>).Title("#");
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("GetOpenQueue", "DataSource", new { GeneralQueue = true })
))
Do this:
#{
int counter = 1;
}
#(Html.Kendo().Grid<QueueViewModel>()
.Name("Queue")
.Columns(columns =>
{
columns.Template(#<text><span>#(counter++)</span></text>).Title("#");
})
Or, if your DataSource is set to Ajax (client-side), do this:
<script>
var counter = 1;
function onDataBound(e) {
counter = 1;
}
function renderNumber(data) {
return counter++;
}
</script>
#(Html.Kendo().Grid()
.Name("Queue")
.Columns(columns => {
columns.Template(t => { }).ClientTemplate("#= renderNumber(data) #").Title("#");
})
.Events(ev => ev.DataBound("onDataBound"))
)
Column ClientTemplate is client-side functionality. You cannot use server-side variables in it. You should define Javascript variable:
<script>
var i = 1;
</script>
Then, inside the grid use this:
columns.Template(t => { }).ClientTemplate(#=i++#).Title("#");
Updated: it should be ClientTemplate instead of Template
Try this way In javascript, the code will support the paging also
<script type="text/javascript">
var CountIt = 0
function GetCountIt() {
var page = $("#YourGrid").data("kendoGrid").dataSource.page();
var pageSize = $("#YourGrid").data("kendoGrid").dataSource.pageSize();
CountIt++;
return (page * pageSize) - pageSize + CountIt
}
function YourGrid_DataBound() {
CountIt = 0; $('#YourGrid').data('kendoGrid').pager.unbind("change").bind('change', function (e) {
CountIt = 0
})
}
</script>
then add to your kindo grid
.Events(events =>
{
events.DataBound("YourGrid_DataBound");
})
.Columns(columns =>
{
columns.Bound("").ClientTemplate("#=GetCountIt()#").Title("Sr.").Width(50);
...
I have one requirement for asp.net MVC application and for that inside Kendo UI grid, I have customized one column with combo box and two buttons for performing adding or deletion of any user selected value or manual typed value from combo box control.
But I am not able to get how I can get button click information for any specific row of that column.
Kindly guide how I can achieve such kind of behavior.
Sample Code for Grid is below and I want to get clickable for Category Column.
#(Html.Kendo().Grid<GridHeaderTemplate.Models.ProductModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName);
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName")
.Title("Category").HtmlAttributes(new
{
#class = "templateCell"
}).ClientTemplate("<table cellspacing='0' class='data-row data-personal'><tr>" +
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton'>Add</button> <span></span> <button id='customButton1'>Delete</button></td>" +
"</tr></table>")
.HeaderTemplate(
#<text>
<table cellspacing="0" class="data-header">
<tr>
<td colspan="2"><strong>Category</strong></td>
</tr>
<tr>
<td>Category Name</td>
<td>Settings</td>
</tr>
</table>
</text>
)
.Width(300);//.ClientTemplate("#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span>"); ;
columns.Bound(p => p.UnitPrice).Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(false);
model.Field(p => p.CategoryID).DefaultValue(1);
})
Enter some code to help us helping you..
You need to have in your object the Id that you want to add or delete,
If you created a client template adding the two specific buttons and calling a javascript function, then you have acess to the properties of the row
for instance:
column.Bound(c=>c.Id).hidden(true);
column.Bound(c=>c.Name).ClientTemplate("<span onclick='AddToThisId(#=Id#)'>add</span>");
Edited:
CONTROLLER:
public ActionResult Delete(int id)
{
try
{
//Delete....
}
catch (Exception ex)
{
result.SetInsucess("Erro a apagar registo: " + ex.Message + ".");
}
return Json(true, JsonRequestBehavior.AllowGet);
}
VIEW
<script>
function AddSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/AddAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
function DeleteSomethingBaseOnId(id){
$.ajax({
cache: false,
type: 'GET',
data: { Id: Id },
contentType: "application/json",
url: "Controller/DeleteAction",
success: function (data) {
alert("sucess");
},
fail: function (jqXHR, textStatus) {
alert("Ocorreu um erro: " + textStatus);
$("#" + uid).hide();
}
});
}
</script>
in your client template:
"<td>#=data.Category.CategoryName# <span class='custom-arrow k-icon k-i-arrow-s'></span></td>" +
"<td><button id='customButton' onclick="AddSomethingBaseOnId(#=data.Id#)">Add</button> <span></span> <button id='customButton1' onclick="DeleteSomethingBaseOnId(#=data.Id#)">Delete</button></td>" +
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;
}
});
I have kendo grid MVC like this:
#(Html.NFSGrid<dynamic>("PortfolioGrid")
.Name("PortfolioGrid")
.EnableCustomBinding(true)
//.Selectable()
.BindTo(Model)
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(countpaging)
.Model(m =>
{
foreach (var Allcoulms in (List<HtmlHelperGridBuilder.GridCol>)ViewData["ViewDataGridfildes"])
{
if (Allcoulms.ColumnName == "Id")
{
m.Id(Allcoulms.ColumnName);
}
else
{
m.Field(Allcoulms.ColumnName, Type.GetType("System.String")).Editable(true);
}
}
})
.ServerOperation(true)
.Read(read => read.Action("Read", "Portfolio").Data("portFolioNameSpace.additionalInfo")
)
)
.HtmlAttributes(new { style = "width:2000;" })
.Columns(columns =>
{
columns.Template(p => { }).ClientTemplate("<input name='selectedIds' type='checkbox' value=\"#=Id#\" class='check_row' onchange='portFolioNameSpace.changeChk(event,this.checked,this);'/>")
.HeaderTemplate("<div style='background=#C7CA21 ;width= 40%'><input type='checkbox' style='outline: 2px solid #cfbe62' class='selectAll' onclick='portFolioNameSpace.buttonclick(event)'/></div>")
.HeaderHtmlAttributes(new { style = "text-align:center;" })
.Width(30);
columns.Template(#<text></text>).Title(T("روند").ToString()).Width(30).ClientTemplate("<a onclick='portFolioNameSpace.onclickFlowFPortfolio(event)'><i class='iconmain-showall'></i></a>");
columns.Template(#<text></text>).Title(T("اصل سند").ToString()).Width(50).ClientTemplate("<a onclick='portFolioNameSpace.GetFormData(event)'><i class='iconmain-Accepted'></i></a>");
foreach (var Allcoulms in (List<HtmlHelperGridBuilder.GridCol>)ViewData["ViewDataGridfildes"])
{
if (Allcoulms.ColumnName == "Id")
{
columns.Bound(Allcoulms.ColumnName).Visible(false);
}
else if (Allcoulms.ColumnName == "Subject")
{
columns.Bound(Allcoulms.ColumnName).Width(Allcoulms.ColumnWidth).Title(T(Allcoulms.ColumnTitle).ToString()).HtmlAttributes(new { style = "text-align:center;" });
}
else if (Allcoulms.ColumnName == "Comment")
{
columns.Bound(Allcoulms.ColumnName).Width(200).Title(T(Allcoulms.ColumnTitle).ToString()).HtmlAttributes(new { style = "text-align:center;" }).ClientTemplate("<input type=\"text\" id=\"#=Id#\" value=\"#=Comment#\"/>");
}
else if (Allcoulms.ColumnName == "notViewdRows")
{
}
else
{
columns.Bound(Allcoulms.ColumnName).Width(Allcoulms.ColumnWidth).Title(T(Allcoulms.ColumnTitle).ToString()).HtmlAttributes(new { style = "text-align:center;" }).HeaderHtmlAttributes(new { style = "text-align:center;" });
}
}
})
.Pageable(pager => pager.Enabled(true))
.Scrollable()
.Filterable()
.Resizable(resize => resize.Columns((true)))
.Reorderable(reorder => reorder.Columns(true))
.Events(e => e
.DataBound("portFolioNameSpace.gridDataBound")
)
)
so the problem is when the lengh of a coulmn is more than what i set in width it makes 2line like this picture so how can i make it 1ine without set specific width?
Add the CSS attributes overflow: hidden; white-space: nowrap; to the column definition, something like this:
columns.Bound(Allcoulms.ColumnName).Width(Allcoulms.ColumnWidth).Title(T(Allcoulms.ColumnTitle).ToString()).HtmlAttributes(new { style = "text-align:center; overflow: hidden; white-space: nowrap;" }).HeaderHtmlAttributes(new { style = "text-align:center;" });
I tested and it works, see if it works for you too.
EDIT
Since you're using column templates, you also have the option of adding the CSS properties directly in your CSS file or even inline (although the latter isn't a good practice)
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)
}