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);
...
Related
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!
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")",
}
}
});
I have got a Telerik MVC grid and I would like to export it as a pdf and hide the column "Test2". I am not able to achieve the desired behavior.
#(Html.Kendo().Grid<Lagerbase.Models.Artikel>()
.Name("ArtikelGrid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
.AvoidLinks()
.PaperSize("A4")
.Scale(0.8)
.Margin("2cm", "1cm", "1cm", "1cm")
.Landscape()
.RepeatHeaders()
.TemplateId("page-template")
.FileName("Artikel.pdf")
.ProxyURL(Url.Action("Pdf_Export_Save", "Grid"))
)
.Columns(columns =>
{
columns.Bound(o => o.Id).Hidden();
columns.Bound(o => o.Test1);
columns.Bound(o => o.Test2);
})
}
This is what I found for an Excel export. So I adjusted the bind to "pdfExport".
Unfortunately it doesn't work for the function e.sender.saveAsExcel();.
<script type="text/javascript">
$(document).ready(function () {
var exportFlag = false;
$("#ArtikelGrid").data("kendoGrid").bind("pdfExport", function (e) {
if (!exportFlag) {
e.sender.hideColumn(1);
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.showColumn(1);
exportFlag = false;
}
});
});
</script>
Does someone know a solution to this?
View this Demo : FUll demo
Source
I need to change the backgroundcolor of a kendo grid.
My code looks as follows :
#(Html.Kendo().Grid<TegelCheckerModel>()
.Name("Grid")
.CellAction(cell =>
{
if (cell.Column.Title.Equals("TegelZones"))
{
if (cell.DataItem.TegelZones.Contains("Extern"))
{
cell.HtmlAttributes["style"] = "background-color: red";
}
}
})
.Columns(columns =>
{
columns.Bound(p => p.TegelNaam);
columns.Bound(p => p.TegelActief).HeaderHtmlAttributes(new { style = "background: #800000;" }).ClientTemplate("#if(TegelActief){# ja #}else{# nee #}#");
columns.Bound(p => p.TegelZones).HeaderHtmlAttributes(new { style = "background: #800000;" }); })
.AutoBind(true)
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax() //Or .Server()
.Read(read => read.Action("GetTegels", "TegelChecker")
.Data("getAlvNummerAndVoorWie"))
)
)
This code doesn't change the background-color of the cell.
What am I missing?
I succeeded partly. This means I was able to color some part of the cell using the following code :
if (tegelTitel == "TegelActie") {
if ($("#tegelcheckeroverzicht_klantControl_Klantddl").klantenControl().getKlant().alvNummer == "") {
html = kendo.format("<span>" + data.TegelActie + "</span>");
}
else {
if (data.TegelActieAllowed) {
if (data.TegelActie == null) {
html = kendo.format("<span></span>");
}
else {
html = kendo.format("<span>" + data.TegelActie + "</span>");
}
}
else {
html = kendo.format("<span STYLE='background: red; color: white;font-weight:bold'>" + data.TegelActie + "</span>");
}
}
}
But that means that only the background of the span is colored and not the entire cell.
Ok I found a solution :
function gridDataBound() {
var data = this._data;
for (var x = 0; x < data.length; x++) {
var dataItem = data[x];
var tr = $("#Grid").find("[data-uid='" + dataItem.uid + "']");
if (dataItem.Selected) {
$("input:first", tr).attr("checked", "checked");
}
var alvNummer = $("#tegelcheckeroverzicht_klantControl_Klantddl").klantenControl().getKlant().alvNummer;
if (alvNummer == "")
{ }
else
{
var cell = $("td:nth-child(6)", tr); // Zone
if (dataItem.HasCorrectZone) {
}
else {
cell.addClass("myerror");
}
cell = $("td:nth-child(7)", tr); //Actie
if (!dataItem.TegelActieAllowed) {
cell.addClass("myerror");
}
cell = $("td:nth-child(8)", tr); //Rollen
if (!dataItem.RolcodeVoldaan) {
cell.addClass("myerror");
}
}
}
}
And in the grid I added :
.Events(e => e.DataBound("gridDataBound "))
Here's my View, in which I have a Sortable that's integrated with a Grid. This works fine, but the problem is that the Grid is grouped. And, I want each group to have its own Sortable functionality, meaning that the user should not be able to drag and drop rows from one group to another. How do I do that? Do I have to have separate Sortables for each group?
#(Html.Kendo().Grid<QRMT.ViewModels.SubsystemViewModel>()
.Name("subsystems")
.ToolBar(toolbar => toolbar.Create().Text("Add new Subsystem"))
.Columns(columns =>
{
columns.ForeignKey(c => c.SystemId, new SelectList(ViewBag.Systems, "Value", "Text")).Hidden();
columns.Bound(c => c.SubsystemCode);
columns.Bound(c => c.SubsystemDesc);
columns.Command(c => { c.Edit(); c.Destroy(); }).Width(200);
})
.Editable(e => e.Mode(GridEditMode.PopUp).Window(window => window.Width(500)))
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Sync("onSync").Error("onError"))
.Model(model =>
{
model.Id(m => m.SubsystemId);
})
.Group(group => group.Add(m => m.SystemId))
.Create(create => create.Action("Add", "Subsystems"))
.Read(read => read.Action("Read", "Subsystems"))
.Update(update => update.Action("Update", "Subsystems"))
.Destroy(destroy => destroy.Action("Delete", "Subsystems"))
)
.Events(events => events.Edit("onEdit"))
)
#(Html.Kendo().Sortable()
.For("#subsystems")
.Filter("table > tbody > tr:not(.k-grouping-row)")
.Cursor("move")
.HintHandler("noHint")
.PlaceholderHandler("placeholder")
.ContainerSelector("#subsystems tbody")
.Events(events => events.Change("onChange"))
)
<script type="text/javascript">
var noHint = $.noop;
function placeholder(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
}
function onEdit(e) {
if (e.model.isNew()) {
$('.k-window-title').text("Add");
}
}
function onSync(e) {
this.read();
}
function onError(e) {
alert(e.errors);
}
function onChange(e) {
var grid = $("#subsystems").data("kendoGrid"),
skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
</script>
<style>
.k-grid tbody tr:not(.k-grouping-row) {
cursor: move;
}
</style>
Kendo Sortable widget does not work with grouped Grid.
This is written in the known limitations section of Sortable-Grid integration help topic.
Kendo says using KendoSortable is impossible on grouped grids, I did however find a possible solution! in your question you limit yourself to only being able to drag within the same group. If you have a field to store the order and sort correctly, this does not matter.
My solution posted below, was made for an angular implementation, but the onchange event is both javascript so I think this can be reworked.
(tr filter [data-uid] will ensure no grouping-row is 'selected')
first number all rows correctly, possibly needed to initiate the SortOrder value
then set the new index on the moved row
then change where needed
then resort the grid. Possibly hardcoded fieldname is needed here instead of 'primarySortField'
$scope.initMySortOrderGrouped = function(grid, myDatasource, primarySortField) {
grid.table.kendoSortable({
filter: ">tbody>tr[data-uid]",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#" + grid.element[0].id + " tbody",
change: function(e) {
/*Needed on grid for sorting to work conditionally*/
if (grid.canWrite) {
var skip = 0,
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
view = myDatasource.view(),
dataItem = myDatasource.getByUid(e.item.data("uid"));
/*retrieve the moved dataItem*/
/*set initial values where needed*/
var countRows = 0;
for (var i = 0; i < view.length; i++) {
for (var j = 0; j < view[i].items.length; j++) {
if (view[i].items[j].SortOrder != countRows + j) {
view[i].items[j].SortOrder = countRows + j;
view[i].items[j].dirty = true;
}
}
countRows += view[i].items.length
}
dataItem.SortOrder = newIndex; /*update the order*/
dataItem.dirty = true;
countRows = 0;
/*shift the order of the records*/
for (var i = 0; i < view.length; i++) {
for (var j = 0; j < view[i].items.length; j++) {
if (oldIndex < newIndex) {
if (countRows + j > oldIndex && countRows + j <= newIndex) {
view[i].items[j].SortOrder--;
view[i].items[j].dirty = true;
}
} else {
if (countRows + j >= newIndex && countRows + j < oldIndex) {
view[i].items[j].SortOrder++;
view[i].items[j].dirty = true;
}
}
}
countRows += view[i].items.length
}
myDatasource.sync();
/*submit the changes through the update transport and refresh the Grid*/
}
myDatasource.sort([{
field: primarySortField,
dir: "asc"
}, {
field: "SortOrder",
dir: "asc"
}]);
}
});
};
This will allow you to drag items over it's group, the number will be far higher or lower than it could be in the group, but the resulting sort will show correctly!
I hate it when programmers say something is impossible...