Kendo Server Side Grid: Custom Buttons - kendo-ui

What is the correct way to bind custom buttons (class glyphicons) to Kendo columns / toolbars?
.ToolBar(tb =>
{
tb.Template("<button type=button id=gridTrainerAdd><span class='glyphicon glyphicon-plus-sign'></span></button>");
})
works but icon looks quite differen than expected (probalby nested css problem).
How do I use buttons in columns? During researches I only found quite different solutions for client side grids...
What would this (compare columns button "View details") be in server side (fluent) notation?:
$(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
sortable: true,
columnMenu: true,
pageable: true,
height: 430,
columns: [
{ field: "FirstName", title: "First Name", width: "140px" },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" },
{ command: {
text: " View Details",
click: showDetails,
className: "fa fa-map-marker"
},
title: " ",
width: "140px"
}],
dataBound: function (e) {
e.sender.tbody.find(".k-button.fa").each(function(idx, element){
$(element).removeClass("fa fa-map-marker").find("span").addClass("fa fa-map-marker");
});
}
}).data("kendoGrid");
I'd expect somthing like:
columns.Command(com => com.Custom());

Try adding k-button and k-button-icontext classes to your button. It will give the button the kendo theme styling.
tb.Template("<div class='toolbar'><a class='k-button k-button-icontext k-grid-add' href=''><span class='glyphicon glyphicon-plus-sign'></span>add</a></div>");
Update:
You can add custom css to the button in MVC with the HtmlAttributes method.
columns.Command(command =>
{
command.Edit();
command.Destroy();
command.Custom("Copy").Click("CopyPOLine").HtmlAttributes(new { #class = "k-copy-icon"});
}).Width(175);
Update2:
Also you should check out the custom command demo on the kendo ui website. Here is part of the example copied below.
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("Grid")
.Columns(columns => {
columns.Bound(e => e.FirstName).Width(140);
columns.Bound(e => e.LastName).Width(140);
columns.Bound(e => e.Title);
columns.Command(command => command.Custom("ViewDetails").Click("showDetails")).Width(180);
})
.HtmlAttributes(new { style = "height: 400px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("CustomCommand_Read", "Grid"))
)
)
<script type="text/javascript">
var detailsTemplate = kendo.template($("#template").html());
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var wnd = $("#Details").data("kendoWindow");
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
</script>

Related

Kendo Grid doesn't send all checked items

I have a Kendo Grid that has checked box items. I want to check all items and send them to the controller, for export checked data to PDF. But, when I have checked all items, Kendo Grid sends only checked items from the first page of grid, and my report in PDF has only one page. How to get all checked items from Kendo Grid? My code is here:
<div style="text-align:right; font-size: 0.9em;height:28px;position: relative;">
<span style="float:left;text-align:left;">
Check All
Uncheck All
<a class="k-button k-button-icontext k-grid-Patient" id="hrefCheckedPatients" href="#" onclick="getChecked();">Export to PDF</a>
Download Generated PDF
<label id="checkedMsg" style="color:red;display:none;"></label>
</span>
(Html.Kendo().Grid<RunSummary>()
.Name("CheckedPatients")
.DataSource(datasource => datasource
.Ajax().PageSize(25)
.Sort(sort => sort.Add("UniqueId").Ascending())
.Read(read => read.Action("GetRunSummaries", "PatientReport")))
.Columns(columns =>
{
columns.Bound(c => c.UniqueId).Title(ELSORegistry.Resources.Views.Home.HomeStrings.UniqueId)
.ClientTemplate("<input type='checkbox' class='primaryBox' id='#= UniqueId #'>#= UniqueId #</input>");
columns.Bound(c => c.RunNo).Title(SharedStrings.Run);
columns.Bound(c => c.Birthdate).Title(SharedStrings.Birthdate).Format("{0:g}").Filterable(true);
columns.Bound(c => c.customAge).Title(SharedStrings.Age)
.Filterable(
filterable => filterable
.UI("AgeFilter")
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear().IsEqualTo("Is equal to"))
)
);
columns.Bound(c => c.TimeOn).Title(PatientStrings.DateOn)
.Format("{0:g}")
.Filterable(true);
columns.Bound(c => c.TimeOff).Title(PatientStrings.DateOff)
.Format("{0:g}")
.Filterable(true);
columns.Bound(c => c.DischargedAlive).Title(PatientStrings.DischargedAlive).Filterable(true).ClientTemplate("#= DischargedAlive ? 'Yes' : 'No' #");
columns.Bound(c => c.ShowSubmitted).Title(PatientStrings.Submitted).Filterable(true).ClientTemplate("#= ShowSubmitted ? 'Yes' : 'No' #");
columns.Bound(c => c.SupportTypeEnum).Title(PatientStrings.SupportType).Filterable(true);//.ClientTemplate("#= SupportType ? 'Yes' : 'No' #");
}
)
.Pageable(p => p.PageSizes(new[] {10, 25, 50, 100}))
.Sortable()
.Filterable( )
.Events( e => e.FilterMenuInit("FilterMenuFuncWithAge") ) // apply x [closing box] on pop up filter box
)
function getChecked() {
$('#checkedMsg').text('');
var ids = new Array();
$('.primaryBox:checked').map(function (index) {
ids.push(this.id);
});
if (ids.length == 0) {
$('#checkedMsg').text('#ELSORegistry.Resources.Views.Patient.PatientStrings.NoPatientsSelected').show();
$('#hrefCheckedPatients').blur();
return;
} else {
$('#checkedMsg').text('').hide();
$('#hrefCheckedPatients').blur();
}
$.ajax({
type: "POST",
url: "/PatientReport/ExportToPDF",
dataType: "json",
traditional: true,
data: { uniqueIds: ids },
success: function (data) {
if (data.success) {
$('#lnkPdfDownload').show();
$('#lnkPdfDownload').attr('href', '/PatientReport/DownloadFile' + '?fName=' + data.fName);
} else {
$('#lnkPdfDownload').hide();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#checkedMsg').text('#ELSORegistry.Resources.Views.Patient.PatientStrings.CheckedError').show();
$('#hrefCheckedPatients').blur();
}
});
}
</script>
Thank you in advance for any help.
We can't get directly all Ids from the kendo grid from all pages. So we have to manually get it from all the pages.
Please try with the below code snippet.
<script>
var ids = [];
function checkAll() {
var dataSource = $("#CheckedPatients").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var totalRowCount = parseInt(dataSource.total().toString());
var totalPages = Math.ceil(totalRowCount / dataSource.pageSize());
var currentPageSize = $("#CheckedPatients").data("kendoGrid").dataSource.page();
PageTraverser(dataSource, 1, totalPages,filters, function () {
$("#CheckedPatients").data("kendoGrid").dataSource.page(currentPageSize);
alert("You have slected this Ids:- " + ids.join(','));
});
}
function PageTraverser(dataSource, targetPage, totalPages,filters, completionFunction) {
dataSource.query({
page: targetPage,
filter: filters
pageSize: 1,
}).then(function () {
var view = dataSource.view();
for (var viewItemId = 0; viewItemId < view.length; viewItemId++) {
var viewItem = view[viewItemId];
ids.push(viewItem.UniqueId); //Please change your field name here
}
targetPage++;
if (targetPage <= totalPages) {
PageTraverser(dataSource, targetPage, totalPages, filters, completionFunction);
} else {
completionFunction();
}
});
}
</script>
Let me know if any concern.

Option of Dropdown is not display in kendo grid popup template

I try to create dropdown into kendo grid edit popup tempate.but i unable to get value of dropdown into popup tempate.how to get it using kendo grid popup?
kendo field detail is describe below
{ field: "PaymentMode", title: "Payment Mode", width: 150, editor: paymentModeDropDownEditor, template: "#:AvailablePaymentMode#", hidden: true },
At Edit Event code is written below
edit: function (e) {
var formTypeData = new kendo.data.DataSource({
data: [
{ Text: "Cheque", Value: "0" },
{ Text: "Cash", Value: "1" },
]
});
function paymentModeDropDownEditor(container, options) {
$('<input required data-text-field="Text" id="paymentMode" data-value-field="Value" data-bind="value:PaymentMode"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
dataSource: formTypeData,
change: onChange,
});
}
function onChange(e) {
var dataItem = this.dataItem(e.item);
if (dataItem.Text == "Cash") {
$("input[name='ChequeReferenceNo']").hide();
$("label[for='ChequeReferenceNo']").hide();
$("input[name='BankName']").hide();
$("label[for='BankName']").hide();
}
else {
$("input[name='ChequeReferenceNo']").show();
$("label[for='ChequeReferenceNo']").show();
$("input[name='BankName']").show();
$("label[for='BankName']").show();
}
};
Kendo grid popup template script is written below
<script id="InvoiceUpdatePopup_editor" type="text/x-kendo-template">
<input name="paymentMode" data-bind="value:AvailablePaymentMode" data-value-field="value" data-text-field="text" data-role="dropdownlist" />
<script>
I know its not as per your query but have implemented using editable template as below:
Grid --
Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
Grid Model :-
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.Role).DefaultValue(ViewData["defaultCategory"] as UserRole);
}
PopupEditView-
#(Html.Kendo().DropDownListFor(model => model.Role)
.DataValueField("Id")
.DataTextField("RoleName")
.SelectedIndex(Model.Role.Id)
//.Value(Model.Role.RoleName)
//.Events(e => e.("onDataBound"))
.BindTo(ViewData["Category"] as IEnumerable<UserRole>)
.HtmlAttributes(new { style = "width: 280px;" })
)
Controller--
ViewData["Category"] = list;
ViewData["defaultCategory"] = list.FirstOrDefault();
let me know how it worked for you.

popup kendo window when clicked on grid data

I have created a kendo grid for 10 number of products in my project. I want the kendo window containing the details of the product to popup when I click on the productname displayed in the kendo grid.
I have looked into the demos of the kendo grid but I don't want the details of the product selected to be edited and also I don't want to use a separate column for details button as shown in the examples and demo.
I also looked into the music store demo of kendo ui but I couldn't understand its code as its in jQuery and I am using asp.net mvc with razor syntax for my project
Note:
I want window to appear only when I click on the name of the product and display its details.
You can use:
$('#grid').on("click", "tr.k-state-selected", function (e) {
// open window here
// you have i.e. Id here $('#grid').dataItem($('#grid').select()).Id
});
For this you must set option selectable: "row" in grid configuration.
Otherwise you can use just:
$('#grid').on("click", "tr", function (e) { ... }
You can make use of the detailTemplate for achieving it.
<script>
var wnd,
detailsTemplate;
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
pageable: true,
height: 550,
columns: [
{ field: "FirstName", title: "First Name", width: "140px" },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" },
{ command: { text: "View Details", click: showDetails }, title: " ", width: "180px" }]
}).data("kendoGrid");
wnd = $("#details")
.kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
});
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName # #= LastName #</h2>
<em>#= Title #</em>
<dl>
<dt>City: #= City #</dt>
<dt>Birth Date: #= kendo.toString(BirthDate, "MM/dd/yyyy") #</dt>
</dl>
</div>
</script>
Go to this fiddle for a working demo
[UPDATE]
Here's the code snippet for showing the window while clicking on the Product Name
<script>
var wnd,
detailsTemplate;
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
pageSize: 20,
data: createRandomData(50)
},
pageable: true,
height: 550,
columns: [
{ field: "FirstName", title: "First Name", width: "140px",attributes: { "class": "FirstName"} },
{ field: "LastName", title: "Last Name", width: "140px" },
{ field: "Title" }]
}).data("kendoGrid");
wnd = $("#details")
.kendoWindow({
title: "Customer Details",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
detailsTemplate = kendo.template($("#template").html());
$('#grid').on("click", ".FirstName", function (e) {
e.preventDefault();
var dataItem = $("#grid").getKendoGrid().dataItem($(e.currentTarget).closest("tr"));
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
});
});
</script>
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h2>#= FirstName # #= LastName #</h2>
<em>#= Title #</em>
<dl>
<dt>City: #= City #</dt>
<dt>Birth Date: #= kendo.toString(BirthDate, "MM/dd/yyyy") #</dt>
</dl>
</div>
</script>
Working demo is here

Data and button in same column kendo grid

I am working on HTML5 and javascript.
Is it possible to add data and button in the same column in kendo grid.
Need help.
Also in view page, you can use ClientTemplate to achieve this:
#(Html.Kendo().Grid<ViewModel>().Name("grid")
.DataSource(src => src.Ajax().PageSize(10).Read(read => read.Action("Action", "Controller"))
.Columns(col =>
{
col.Bound(e => e.Name).ClientTemplate("<input type='button' value='CLICK' onclick='XYZ();'><label>#= (Name== null) ? ' ' : Name #</label>");
})
.Selectable()
.Scrollable()
)
Yes, it is! Simply use a template for it. Example:
Define the following template:
<script id="template" type="kendoui/template">
<button class="ob-click-me k-button">Click me</button>
<span>#= LastName #</span>
</script>
and the grid as:
var grid = $("#grid").kendoGrid({
dataSource: ds,
...
columns :
[
{ field: "FirstName", width: 90, title: "First Name" },
{
field: "LastName",
width: 200,
title: "Last Name",
template: $("#template").html()
}
]
}).data("kendoGrid");
You can see a running example even defining a handler for the button here: http://jsfiddle.net/OnaBai/qe3tf4tx/

How to code for Link button click event opens modal popup in mvc3.0 with Razor?

I have webgrid as follows
#grid.GetHtml(columns: grid.Columns(grid.Column(
"FirstName",format: #<text>#Html.ActionLink((string)item.FirstName, "Details", "product", new { id = item.FirstName }, null)</text>),
grid.Column("LastName","Last")
))
if i click the Firstname link the modal popup should open? How to do this in mvc3.0?
Recommend http://fancybox.net.
Add document.ready for fancybox. (look at examples and documentation)
$(document).ready(function ()
{
$('.fancybox').fancybox({
'autoScale': false,
'autoDimensions': true,
'transitionIn': 'none',
'transitionOut': 'none',
'hideOnOverlayClick': false,
'hideOnContentClick': true,
'showCloseButton': true,
'type': 'ajax'
});
});
Then you change your actionlink to have a class that fancybox can attach to.
#Html.ActionLink((string)item.FirstName, "Details", "product"
, new { id = item.FirstName }, new {Class = "fancybox"})

Resources