Telerik Ui For Aspnet Core 2020 1 219 PDF
Telerik Ui For Aspnet Core 2020 1 219 PDF
NET Core
DOCUMENTATION
Version: R1 2020
Copyright © 2020, Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
Telerik UI for ASP.NET Core
Telerik UI for ASP.NET Coreis a set of server-side wrappers (HTML and Tag helpers) that allow you to
use the Kendo UI widgets in .NET Core. From a client-side point of view, the vanilla HTML/JavaScript
Kendo UI widgets and their ASP.NET Core helpers represent the same functionalities and provide the
same capabilities.
Allow you to configure a Kendo UI widget through the C# or VB.NET code—for example, to
set its value, data source, and so on.
Render the HTML and JavaScript that are needed to initialize a Kendo UI widget whose
options propagate to the client-side through its initialization script.
Getting Started
More resources on getting started with UI for ASP.NET Core:
3
Telerik UI for ASP.NET Core
First Steps with UI for ASP.NET Core on Visual Studio for Windows
First Steps with UI for ASP.NET Core on Visual Studio for Mac
First Steps with UI for ASP.NET Core with CLI
Supported Environments
UI for ASP.NET Core targets the stable releases of the ASP.NET Core framework. The target runtime
is CoreCLR. The UI for ASP.NET Core suite also supports the full desktop CLR.
List of Helpers
Group HTML Helpers Tag Helpers
Data Source DataSource HtmlHelper Demos Data Source TagHelper Docs&
Demos
4
Telerik UI for ASP.NET Core
Docs& Demos
DateTimePicker HtmlHelper DateTimePicker TagHelper
Docs& Demos Docs& Demos
DropDownList HtmlHelper DropDownList TagHelper Docs
Docs& Demos & Demos
DropDownTree HtmlHelper DropDownTree TagHelper Docs
Docs& Demos & Demos
Editor HtmlHelper Docs& Editor TagHelper Docs& Demos
Demos
FlatColorPicker HtmlHelper N/A
Docs& Demos
5
Telerik UI for ASP.NET Core
Demos Demos
LinearGauge HtmlHelper Docs LinearGauge TagHelper Docs&
& Demos Demos
RadialGauge HtmlHelper Docs RadialGauge TagHelper Docs&
& Demos Demos
6
Telerik UI for ASP.NET Core
7
Telerik UI for ASP.NET Core
use it commercially, you need to purchase a license. Feel free to review the Telerik UI for ASP.NET
Core License Agreementto get acquainted with the full terms of use.
Support Options
For any issues you might encounter while working with UI for ASP.NET Core, use any of the available
support channels:
UI for ASP.NET Core license holders and active trialists can take advantage of the
outstanding customer support delivered by the developers building the library. To submit a
support ticket, use the UI for ASP.NET Core dedicated supportsystem.
UI for ASP.NET Core forumsare part of the free support you can get from the community and
from the UI for ASP.NET Core team on all kinds of general issues.
UI for ASP.NET Core feedback portaland UI for ASP.NET Core roadmapprovide information on
the features in discussion and also the planned ones for release.
You may still need a tailor-made solution for your project. In such cases, go straight to
Progress Services.
Learning Resources
Virtual Classroom
Knowledge Base
Support Resources Hub Page
Next Steps
First steps on Visual Studio for Windows (online guide)
First steps on Visual Studio for Mac (online guide)
First steps with CLI (online guide)
Including client-side resources
Integrating UI for ASP.NET Core in Visual Studio
Upgrading UI for ASP.NET Core in Visual Studio
8
Telerik UI for ASP.NET Core
HTML Helpers can be added and further configured through predefined strongly typed attributes and
also allow you to handle the events of the widgets in ASP.NET Core projects.
Known Issues
Currently, Telerik UI for ASP.NET Core does not support localization resources. For more
information and discussion on this issue, refer to dotnet/coreclr#2007and
aspnet/Home/issues/1124.
The current set of helpers is limited and next releases will add more helpers.
Deferred()can be invoked only as a last setting.
@(Html.Kendo().NumericTextBox()
.Name("age")
/* Other configuration. */
.Deferred()
)
Grid Specifics
The Grid does not support server-side rendering. The toolbar template, column header template, and
column template are no longer rendered on the server.
Chart Specifics
Previous Enum Now
ChartAreaStyle ChartSeriesLineStyle
ChartAreaMissingValues ChartSeriesMissingValues
ChartBarGradient ChartSeriesGradient
ChartBarLabelsPosition ChartSeriesLabelsPosition
ChartFunnelLabelsAlign ChartSeriesLabelsAlign
ChartFunnelLabelsPosition ChartSeriesLabelsPosition
ChartLineMissingValues ChartSeriesMissingValues
ChartLineStyle ChartSeriesStyle
ChartPieLabelsAlign ChartSeriesLabelsAlign
9
Telerik UI for ASP.NET Core
ChartPieLabelsPosition ChartSeriesLabelsPosition
ChartPointLabelsPosition ChartSeriesLabelsPosition
ChartPolarAreaStyle ChartSeriesLineStyle
ChartPolarLineStyle ChartSeriesLineStyle
ChartRadarAreaStyle ChartSeriesLineStyle
ChartRadarLineStyle ChartSeriesLineStyle
ChartRangeAreaLabelsPosition ChartSeriesLabelsPosition
ChartScatterLineMissingValues ChartSeriesMissingValues
ChartScatterLineStyle ChartSeriesStyle
Editor Specifics
The Thumbnails view of the ImageBrowser is not supported because the System.Drawing
namespace is not part of ASP.NET Core. However, you can process images on the server side by
using a third-party library.
See Also
Introduction to Telerik UI for ASP.NET Core
First Steps on Visual Studio for Windows (Online Guide)
First Steps on Visual Studio for Mac (Online Guide)
First Steps with CLI (Online Guide)
10
Telerik UI for ASP.NET Core
@(Html.Kendo().Barcode()
.Name("barcode") // The name of the Barcode is mandatory. It specifies the
"id" attribute of the widget.
.Value("2346722") // Set the value of the Barcode.
.Width(200)
.Height(100))
2. Select the appropriate encoding (symbology) from the available options. Specify it through
the encoding method which accepts an enum value.
@(Html.Kendo().Barcode()
.Name("mascarpone")
.Value("Mascarpone")
.Encoding(BarcodeSymbology.Code128)
.Width(200)
.Height(100))
// Place the following after the declaration of the Barcode for ASP.NET Core.
<script>
$(function() {
// The Name() of the Barcode is used to get its client-side instance.
var barcode = $("#barcode").data("kendoBarcode");
11
Telerik UI for ASP.NET Core
barcode.value("foo") // Supply a valid value for that encoding. Then, the
Barcode will redraw automatically.
});
</script>
See Also
Basic Usage of the Barcode HtmlHelper for ASP.NET Core (Demo)
Using the API of the Barcode HtmlHelper for ASP.NET Core (Demo)
Server-Side API
12
Telerik UI for ASP.NET Core
Encoding
Encoding (symbology) represents the mapping between messages and barcodes.
The symbology specification includes the encoding of the individual digits or characters of the
message, the start and stop markers in the bars and the space, the size of the quiet zone before and
after the Barcode, and the computation of a checksum.
The following table lists the available symbologies and their specifications supported by the Barcode
.
If the value for a particular encoding you provide does not meet the expected length or character set,
it will throw an error.
Symbology Character set Length Check digits
Code 39 (default) [A-Z]; [0-9]; [ - . $ / + % ] variable (avg. up to 20 optional (Mod. 43)
chars)
Code39Extended ASCII (128 characters) variable optional (Mod. 43)
Code 93 [0-9];[A-Z];[SPACE . + - / variable 2 check digits
% $]
Code93Extended ASCII(128 characters) variable 2 check digits
EAN-13 numeric [0..9] 12 usable digits 1 check digit
EAN-8 numeric [0..9] 7 usable digits 1 check digit
UPC-A numeric [0..9] 11 usable digits (first is 1 check digit
always 0)
UPC-E numeric [0..9] 6 usable digits (first is 1 check digit
always 0)
POSTNET numeric [0..9] variable 1 check digit
Code 11 [0-9]; [-] variable 1 or 2 based on length
Code128 LATIN-1 (ISO-8859-1) variable 1 check digit
Code128A ASCII 00 to 95 (0-9, A-Z variable 1 check digit
and control codes),
special characters
Code128B ASCII 32 to 127 (0-9, variable 1 check digit
A-Z, a-z), special
characters
Code128C ASCII 00-99 (encodes variable 1 check digit
each two digits with
one code)
GS1-128 depending on variable 1 check digit
Application Identifier
MSImod10 numeric [0..9] variable 1 check digit
13
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Barcode HtmlHelper for ASP.NET Core (Demo)
Server-Side API
14
Telerik UI for ASP.NET Core
The QRCode generates Canvasand Scalable Vector Graphics (SVG)images that represent Quick
Response (QR) codes.
QR codes take a piece of information from a transitory media, place it into the cell phone, and enable
the cell phone to quickly read these generated images. All graphics are rendered on the client by
using Canvas or SVG.
@(Html.Kendo().QRCode()
.Name("qrMail") // The name of the QRcode is mandatory. It specifies the
"id" attribute of the widget.
.Value("mailto:[email protected]") // Set the value of the
QRCode.
.Color("#e15613")
.Background("transparent")
.Size(120)
)
@(Html.Kendo().QRCode()
.Name("qrcode")
.ErrorCorrection(QRErrorCorrectionLevel.H)
.Encoding(QREncoding.ISO_8859_1)
.Value("foo")
)
15
Telerik UI for ASP.NET Core
// Place the following after the declaration of the QRCode for ASP.NET Core.
<script>
$(function() {
// The Name() of the QRCode is used to get its client-side instance.
var qrcode = $("#qrcode").data("kendoQRCode");
});
</script>
See Also
Basic Usage of the QRCode HtmlHelper for ASP.NET Core (Demo)
Using the API of the QRCode HtmlHelper for ASP.NET Core (Demo)
Server-Side API
16
Telerik UI for ASP.NET Core
Encoding
The different types of QRCde values support different conventions accordingly.
In many cases, the value of the QRCode is processed by the device in a special way. For example,
geolocations are displayed in the Global Positioning System (GPS) or Map application on the device,
URLs are opened by the browser, and so on.
URL
To encode the text of a URL, for example, http://www.telerik.com/, encode the
http://www.telerik.com/ URL text in the QRCode. Include the http:// protocol to ensure it is
recognized as a URL.
Email Addresses
To encode an email address, for example, [email protected], encode [email protected]. To
ensure the value is recognized as an email address, create a proper mailto Uniform Resource
Identifier (URI) from the address (mailto:[email protected]). As a result, readers can open a
blank email message to the specified email destination.
Telephone Numbers
To encode a telephone number, use a telephone URI to ensure that the digits are recognized as a
telephone number and include prefixes which make the number internationally accessible. For
example, to encode the 212-555-1212 US telephone number, encode tel:+1-212-555-1212. This
telephone URI contains a +1 prefix that makes it usable outside the United States. As a result, even
though readers cannot automatically initiate a call, they can invoke the device dialer (if applicable)
and pre-fill it with the specified number.
Contact Information
To encode contact information as text, use the vCardformat. This format is too verbose to use in 2D
QRCodes whose information capacity is limited. It is not clear whether vCard is or has to be used to
encode contact information. As a result, readers can open a new address book entry that is
populated with the provided data and prompt the user to add a new contact.
SMS
Similar to email addresses, to encode an SMS short code or number, create an SMS URI. For
example, to create a link to the 12345 number, encode sms:12345. You may use other URI forms,
such as sms:number:subject, and other prefixes, such as smsto:. As a result, readers can open a
new SMS message that is ready for users to compose and send it.
17
Telerik UI for ASP.NET Core
Geolocations
To encode a point on the earth, including altitude, use a geo URI. For example, to encode the
Progress office in Bulgaria, encode geo:42.65049,23.37925,100. As a result, readers can either
open a local mapping application to this location, such as Google Maps, and zoom accordingly, or a
link to this location on a mapping website such as Google Maps in the web browser of the device.
See Also
Basic Usage of the QRCode HtmlHelper for ASP.NET Core (Demo)
Server-Side API
18
Telerik UI for ASP.NET Core
The Chart uses modern browser technologies to render high-quality data visualizations. All graphics
are rendered on the client by using Scalable Vector Graphics (SVG)with a fallback to Canvas. The
Charts support a set of series typessuch as Bar, Line, Area, Bullet, Pie, Scatter, Bubble, Polar, and
other.
Title
Legend
Chart Area
Plot Area
Axes
Series
19
Telerik UI for ASP.NET Core
@(Html.Kendo().Chart(Model)
.Name("internetUsersChart") // The name of the Chart is mandatory. It specifies
the "id" attribute of the widget.
.Title("Internet Users")
.Series(series => {
series.Bar(model => model.Value) // Create a Bar Chart series bound to the
"Value" property.
.Name("United States");
})
.CategoryAxis(axis => axis
.Categories(model => model.Year)
)
)
public ActionResult Index()
{
return View(ChartDataRepository.InternetUsers());
20
Telerik UI for ASP.NET Core
}
Basic Configuration
The following example demonstrates the basic configuration for the Line Chart HtmlHelper.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Gross domestic product growth \n /GDP annual %/")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.ChartArea(chartArea => chartArea
.Background("transparent")
)
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Line().Style(ChartSeriesStyle.Smooth)
)
.Series(series => {
series.Line(new double[] { 3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890,
8.238, 9.552, 6.855 }).Name("India");
series.Line(new double[] { 1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333,
-2.245, 4.339, 2.727 }).Name("World");
series.Line(new double[] { 4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247,
-7.832, 4.3, 4.3 }).Name("Russian Federation");
series.Line(new double[] { -0.253, 0.362, -3.519, 1.799, 2.252, 3.343, 0.843,
2.877, -5.416, 5.590 }).Name("Haiti");
})
.CategoryAxis(axis => axis
.Categories("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
"2010", "2011")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric().Labels(labels => labels.Format("{0}%"))
.Line(line => line.Visible(false))
.AxisCrossingValue(-10)
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
You can also add a title to clearly indicate the role of the axis.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Average temperature and humidity")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series => {
series.Column(new double[] { 20, 25, 32
}).Name("Temperature").Axis("temperature");
series.Column(new double[] { 45, 50, 80 }).Name("Humidity").Axis("humidity");
})
21
Telerik UI for ASP.NET Core
.CategoryAxis(axis => axis
.Categories("Aug", "Sep", "Oct")
.AxisCrossingValue(0, 3)
)
.ValueAxis(axis => axis
.Numeric()
.Name("temperature")
.Title(t=>t.Text("Temperature, Celsius"))
)
.ValueAxis(axis => axis
.Numeric()
.Name("humidity")
.Title(t=>t.Text("Relative Humidity"))
)
)
The Chart enables you to configure each axis to display bands with different colors for predefined
value ranges. The category index (zero-based) is used as a value for the category axis.
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0:N0}"))
.MajorUnit(10000)
.Max(70000)
.Line(line => line.Visible(false))
.PlotBands(bands => {
bands.Add().From(10000).To(30000).Color("#c00").Opacity(0.3);
bands.Add().From(30000).To(30500).Color("#c00").Opacity(0.8);
})
)
22
Telerik UI for ASP.NET Core
You may also need to apply global settings that affect all axes. In such cases, use AxisDefaults.
.AxisDefaults(a=> a
.Labels(l=>l.Font("16px Verdana"))
)
Events
You can subscribe to all Chart events. For a complete example on basic Chart events, refer to the
demo on using the events of the Chart.
@(Html.Kendo().Chart<Kendo.Mvc.Examples.Models.ElectricityProduction>()
.Name("chart")
.Events(events => events
.SeriesClick("onSeriesClick")
23
Telerik UI for ASP.NET Core
.DataBound("onDataBound")
)
)
<script>
function onSeriesClick(e) {
// Handle the seriesClick event
}
function onDataBound(e) {
// Handle the dataBound event
}
</script>
@(Html.Kendo().Chart<Kendo.Mvc.Examples.Models.ElectricityProduction>()
.Name("chart")
.Events(events => events
.SeriesClick(@<text>
function() {
// Handle the seriesClick event
}
</text>)
.DataBound(@<text>
function() {
// Handle the dataBound event
}
</text>)
)
)
// Place the following after the Chart for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the Chart is used to get its client-side instance.
var chart = $("#internetUsersChart").data("kendoChart");
});
</script>
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Bar Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Line Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
24
Telerik UI for ASP.NET Core
Data Binding
You can populate the Telerik UI Chart for ASP.NET Core with data by binding it to inline data, binding it
to local data, or binding it to remote data.
Inline Data
You can specify the data points of the Charts as part of the series definitions. The type of the data
points depends on the type of the series.
To keep the Chart consistent, all series have to contain the same number of points in an order that
matches the order of the categories which are declared in CategoryAxis.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series.Line(new double[] { 3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890,
8.238, 9.552, 6.855 }).Name("India");
series.Line(new double[] { 1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333,
-2.245, 4.339, 2.727 }).Name("World");
series.Line(new double[] { 4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247,
-7.832, 4.3, 4.3 }).Name("Russian Federation");
series.Line(new double[] { -0.253, 0.362, -3.519, 1.799, 2.252, 3.343, 0.843,
2.877, -5.416, 5.590 }).Name("Haiti");
})
.CategoryAxis(axis => axis
.Categories("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
"2010", "2011")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric().Labels(labels => labels.Format("{0}%"))
.Line(line => line.Visible(false))
.AxisCrossingValue(-10)
)
)
25
Telerik UI for ASP.NET Core
@(Html.Kendo().Chart()
.Name("chart")
.Title("Rainfall - Wind Speed")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesDefaults(seriesDefaults => seriesDefaults
.Scatter().Labels(labels => labels
.Visible(false)
)
)
.Series(series =>
{
series.Scatter(new double[][] { new[] { 16.4, 5.4 }, new[] { 21.7, 2 }, new[] {
25.4, 3 }, new[] { 19.0, 2.0 }, new[] { 10.9, 1 } })
.Name("January 2008");
series.Scatter(new double[][] { new[] { 6.4, 13.4 }, new[] { 1.7, 11 }, new[] {
5.4, 8 }, new[] { 9.0, 17.0 }, new[] { 1.9, 4 } })
.Name("January 2009");
series.Scatter(new double[][] { new[] { 21.7, 3 }, new[] { 13.6, 3.5 }, new[] {
13.6, 3 }, new[] { 29.9, 3 }, new[] { 21.7, 20 } })
.Name("January 2010");
})
.XAxis(x => x
.Numeric()
.Title(title => title.Text("Wind Speed [km/h]"))
.Max(35)
)
.YAxis(y => y
.Numeric()
.Title(title => title.Text("Rainfall [mm]"))
.AxisCrossingValue(-5)
.Min(-5)
.Max(25)
)
)
@(Html.Kendo().Chart()
.Name("chart")
.Legend(legend => legend
.Visible(false)
)
.Series(series =>
{
series.Donut(new dynamic[] {
new {category = "Asia",value = 53.8,color = "#9de219"},
new {category = "Europe",value = 16.1,color = "#90cc38"},
new {category = "Latin America",value = 11.3,color = "#068c35"},
new {category = "Africa",value = 9.6,color = "#006634"},
26
Telerik UI for ASP.NET Core
new {category = "Middle East",value = 5.2,color = "#004d38"},
new {category = "North America",value = 3.6,color = "#033939"}
})
.Name("2012")
.Labels(labels => labels
.Visible(true)
.Position(ChartSeriesLabelsPosition.OutsideEnd)
.Template("#= category #: \n #= value#%")
.Background("transparent")
);
})
.Tooltip(tooltip => tooltip
.Visible(true)
.Template("#= category # (#= series.name #): #= value #%")
)
)
Local Data
You can bind the Chart to a data set in the view model or to items that are stored in
ViewBag/ViewData.
public IActionResult Local_Data_Binding()
{
var internetUsers = new InternetUsers[] {
new InternetUsers(2000,43.1,"United States"),
new InternetUsers(2001,49.2,"United States"),
new InternetUsers(2002,59.0,"United States"),
new InternetUsers(2003,61.9,"United States"),
new InternetUsers(2004,65,"United States"),
new InternetUsers(2005,68.3,"United States"),
new InternetUsers(2006,69.2,"United States"),
new InternetUsers(2007,75.3,"United States"),
new InternetUsers(2008,74.2,"United States"),
new InternetUsers(2009,71.2,"United States"),
new InternetUsers(2010,74.2,"United States"),
new InternetUsers(2011,78.2,"United States")
};
return View(internetUsers);
}
public class InternetUsers
{
public InternetUsers()
{
}
public InternetUsers(int year, double value, string country)
{
Year = year;
Value = value;
Country = country;
}
public int Year { get; set; }
public double Value { get; set; }
public string Country { get; set; }
}
27
Telerik UI for ASP.NET Core
@model IEnumerable<LocalBindingExample.Models.InternetUsers>
@(Html.Kendo().Chart(Model)
.Name("chart")
.Title("Internet Users in United States")
.Legend(legend => legend.Visible(false))
.Series(series => {
series.Line(model => model.Value)
.Name("United States").CategoryField("Year")
.Labels(labels => labels.Format("{0}%").Visible(true));
})
.CategoryAxis(axis => axis
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0}%"))
.Line(lines => lines.Visible(false))
)
)
Remote Data
The most flexible form of data binding is to use the DataSource component. You can easily
configure the component to request data from a controller method or a remote API endpoint by
using Ajax requests.
1. Add a new action method in your controller that returns the data set.
[HttpPost]
public IActionResult _SpainElectricityProduction()
{
// Data is usually read from a data context. Static data is used in this
example for clarity.
var result = new ElectricityProduction[] {
new ElectricityProduction("2000", 18, 31807, 4727, 62206),
new ElectricityProduction("2001", 24, 43864, 6759, 63708),
new ElectricityProduction("2002", 30, 26270, 9342, 63016),
new ElectricityProduction("2003", 41, 43897, 12075, 61875),
new ElectricityProduction("2004", 56, 34439, 15700, 63606),
new ElectricityProduction("2005", 41, 23025, 21176, 57539),
new ElectricityProduction("2006", 119, 29831, 23297, 60126),
new ElectricityProduction("2007", 508, 30522, 27568, 55103),
new ElectricityProduction("2008", 2578, 26112, 32203, 58973)
};
return Json(result);
}
public class ElectricityProduction
{
public ElectricityProduction()
28
Telerik UI for ASP.NET Core
{
}
public ElectricityProduction(string year, int solar, int hydro, int wind,
int nuclear)
{
Year = year;
Solar = solar;
Hydro = hydro;
Wind = wind;
Nuclear = nuclear;
}
public string Year { get; set; }
public int Solar { get; set; }
public int Nuclear { get; set; }
public int Hydro { get; set; }
public int Wind { get; set; }
}
2. In the view, configure the Chart to use the action method that you created.
```
@(Html.Kendo().Chart<RemoteBindingExample.Models.ElectricityProduction>()
.Name("chart")
.Title("Spain electricity production (GWh)")
.Legend(legend => legend
.Position(ChartLegendPosition.Top)
)
.DataSource(ds => ds.Read(read => read.Action("_SpainElectricityProduction",
"Line_Charts")))
.Series(series => {
series.Line(model =>
model.Nuclear).Name("Nuclear").CategoryField("Year");
series.Line(model => model.Hydro).Name("Hydro").CategoryField("Year");
series.Line(model => model.Wind).Name("Wind").CategoryField("Year");
})
.CategoryAxis(axis => axis
.Labels(labels => labels.Rotation(-90))
.Crosshair(c => c.Visible(true))
)
.ValueAxis(axis => axis.Numeric()
.Labels(labels => labels.Format("{0:N0}"))
.MajorUnit(10000)
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Shared(true)
.Format("{0:N0}")
)
)
```
Unlike the Grid, the Chart is configured to read a flat data response by default. If you have
29
Telerik UI for ASP.NET Core
custom logic that requires the usage of the ToDataSourceResult() extension method
when returning data for the Chart, configure a custom DataSource with a schema that can
correctly parse the response.
public IActionResult Products_Read([DataSourceRequest] DataSourceRequest
request)
{
return Json(productService.Read().ToDataSourceResult(request));
}
@(Html.Kendo().Chart<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("chart")
.Title("Product Prices")
.Legend(legend => legend
.Position(ChartLegendPosition.Top)
)
.DataSource(source =>
{
source.Custom()
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("Products_Read", "Chart");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Series(series =>
{
series.Column(model =>
model.UnitPrice).Name("Price").CategoryField("ProductName");
})
)
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
30
Telerik UI for ASP.NET Core
Appearance
Unlike other Telerik UI for ASP.NET Core components which use only CSS for styling, you can mainly
control the appearance of the Chart elements by using JavaScript style options.
For more information on the structure of the Chart, refer to the articles on the Chart building elements
.
Predefined Themes
The Charts come with a set of predefined themes. To select a theme, use the Theme option. The
theme name is case-insensitive.
@(Html.Kendo().Chart()
.Name("chart")
.Theme("blueOpal")
.Title("Site Visitors Stats /thousands/")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesDefaults(seriesDefaults => seriesDefaults
.Column().Stack(true)
)
.Series(series =>
{
series.Column(new double[] { 56000, 63000, 74000, 91000, 117000, 138000
}).Name("Total Visits");
series.Column(new double[] { 52000, 34000, 23000, 48000, 67000, 83000
}).Name("Unique visitors");
})
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric()
.Line(line => line.Visible(false))
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}")
)
)
Sass Themes
As of the R2 2017 SP1 release, the Chart provides styling options through Sass-based themes. When
the theme is set to inherit, the Chart reads colors and fonts from the theme variables.
@(Html.Kendo().Chart()
.Name("chart")
.Theme("inherit")
31
Telerik UI for ASP.NET Core
.Title("Site Visitors Stats /thousands/")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesDefaults(seriesDefaults => seriesDefaults
.Column().Stack(true)
)
.Series(series =>
{
series.Column(new double[] { 56000, 63000, 74000, 91000, 117000, 138000
}).Name("Total Visits");
series.Column(new double[] { 52000, 34000, 23000, 48000, 67000, 83000
}).Name("Unique visitors");
})
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric()
.Line(line => line.Visible(false))
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}")
)
)
Animated Transitions
Telerik UI for ASP.NET Core Charts use animated transitions to display new and updated data. To
disable these transitions, use the transitions option.
@(Html.Kendo().Chart()
.Name("chart")
.Transitions(false)
// Other options.
)
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
32
Telerik UI for ASP.NET Core
Categorical Charts
Categorical chartsprovide built-in support for displaying dates. The categories represent unique
values which are not mathematically related to each other.
Examples of categorical charts are Area, Bar, Box Plot, Bullet, and Line Charts.
Circular Charts
Circular charts are divided in slices representing statistical data, which proportionally corresponds to
the quantity input of each slice. Circular charts are widely used in the business world and the mass
media.
Freeform Charts
Freeform charts adopt different forms and use variously structured portions to display data.
Scatter Charts
Scatter chartsare suitable for displaying and comparing different sets of numerical values, for
showing the relationships between the values of the data sets, and for plotting two-dimensional data
as a series of XY coordinates.
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
33
Telerik UI for ASP.NET Core
Categorical Charts
Categorical charts use a single category axis and a single value axis.
The axis orientation (horizontal or vertical) is inferred from the series type. Categorical charts are the
Bar, Column, and Line Charts.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series.Bar(new double[] { 56000, 63000, 74000, 91000, 117000, 138000
}).Name("Total Visits");
})
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
)
)
You can also bind the category name to a field of the data item.
@(Html.Kendo().Chart<Kendo.Mvc.Examples.Models.ElectricityProduction>()
.Name("chart")
.DataSource(ds => ds.Read(read => read.Action("_SpainElectricityProduction",
"Bar_Charts")))
.Series(series => {
series.Column(model => model.Wind).Name("Wind");
})
.CategoryAxis(axis => axis
.Field("Year")
)
)
To change the label position, set the Positionoption of the axis labels which provides the following
available options:
34
Telerik UI for ASP.NET Core
end of the crossing axis. Typically, this configuration positions the labels at the top or right end
of the Chart unless the crossing axis was reversed.
When Position is set to "ChartAxisLabelsPosition.Start", the labels are placed at
the start of the crossing axis. Typically, this configuration positions the labels at the left or
bottom end of the Chart unless the crossing axis was reversed.
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
.Labels(l => l.Position(ChartAxisLabelsPosition.Start))
)
The following example demonstrates how to configure a numeric axis with a minimum value of 0
and a maximum value of 100.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series.Bar(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }).Name("Visits");
})
.ValueAxis(v => v
.Min(0)
.Max(100)
)
.CategoryAxis(axis => axis
.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun")
.Labels(l => l.Position(ChartAxisLabelsPosition.Start))
)
)
The following example demonstrates how to define the miles and km axes. To associate a series to
a value axis, specify its name.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series
.Column(new int[] { 20, 40, 45, 30, 50 })
.Name("on battery");
series
.Column(new int[] { 20, 30, 35, 35, 40 })
.Name("on gas");
35
Telerik UI for ASP.NET Core
})
.CategoryAxis(axis => axis
.Categories("Mon", "Tue", "Wed", "Thu", "Fri")
)
.ValueAxis(axis => axis
.Numeric()
.Title("miles")
.Min(0).Max(100)
)
.ValueAxis(axis => axis
.Numeric("km")
.Title("km")
.Min(0).Max(161).MajorUnit(32)
)
)
.CategoryAxis(axis => axis
.Categories("Mon", "Tue", "Wed")
.AxisCrossingValue(0, 3)
)
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Bar Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Line Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
36
Telerik UI for ASP.NET Core
Scatter Charts
Scatter charts display data as points that are defined by the values of their items.
Scatter Charts are useful for displaying the relation between different sets of data (for example,
scientific experimental results) and plotting two-dimensional data.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series => {
series.Scatter(new double[][] { new[] { 16.4, 5.4 }, new[] { 21.7, 2 }, new[] {
25.4, 3 }, new[] { 19.0, 2.0 } });
})
.XAxis(x => x
.Numeric()
.Max(35)
)
.YAxis(y => y
.Numeric()
.Min(-5)
.Max(25)
)
)
To change the label position, set the Positionoption of the axis labels which provides the following
available options:
@(Html.Kendo().Chart()
.Name("chart")
.Series(series => {
37
Telerik UI for ASP.NET Core
series.Scatter(new double[][] { new[] { 16.4, 5.4 }, new[] { 21.7, 2 }, new[] {
25.4, 3 }, new[] { 19.0, 2.0 } });
})
.XAxis(x => x
.Labels(s=>s.Position(ChartAxisLabelsPosition.Start))
)
)
series.ScatterLine(model => model.RPM, model => model.Torque)
.Name("Torque")
.YAxis("torque")
.Tooltip(tooltip => tooltip.Format("{1} lb-ft @ {0:N0} rpm"));
})
.XAxis(x => x
.Numeric()
.Title(title => title.Text("Engine rpm"))
// Align torque axis to the right by specifying
// a crossing value greater than or equal to the axis maximum.
.AxisCrossingValue(0, 10000)
.Labels(labels => labels.Format("{0:N0}"))
)
.YAxis(y => y
.Numeric()
.Title(title => title.Text("Power (bhp)"))
)
.YAxis(y => y
.Numeric("torque")
.Title(title => title.Text("Torque (lb-ft)"))
)
)
Because no axis is specified, the first series is associated with the default Y axis. The torque series
are plotted on the torque Y axis.
38
Telerik UI for ASP.NET Core
.XAxis(x => x
.Numeric()
.AxisCrossingValue(0, 2500)
)
The primary Y axis crosses the X axis at point 0 (leftmost). The second, torque Y axis crosses the X
axis at the 2500 mark or at its right end, whichever comes first.
39
Telerik UI for ASP.NET Core
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Bar Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Line Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
40
Telerik UI for ASP.NET Core
Area Charts
The Telerik UI Area Chart HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI
Area Chart widget.
Area Charts are suitable for displaying quantitative data by using continuous lines passing through
points defined by the values of their items.
Getting Started
The portion of the graph beneath the lines is filled with a particular color for each series. The
different colors in an Area Chart are useful for emphasizing changes in the values which come from
several sets of similar data.
To create an Area series in the Chart HtmlHelper, use Area and VerticalArea in the Series
configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Internet Users")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Area()
)
.Series(series =>
{
series.Area(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }).Name("World");
series.Area(new double[] { 67.96, 68.93, 75, 74, 78 }).Name("United States");
})
.CategoryAxis(axis => axis
.Categories(2005, 2006, 2007, 2008, 2009)
)
.ValueAxis(axis => axis
.Labels(labels => labels.Format("{0}%"))
)
)
41
Telerik UI for ASP.NET Core
The configuration from the previous example results in the following Area Chart.
42
Telerik UI for ASP.NET Core
43
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
44
Telerik UI for ASP.NET Core
Bar Charts
The Telerik UI Bar Chart HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI Bar
Chart widget.
Bar Charts display data through horizontal or vertical bars whose lengths vary according to their
value.
Getting Started
Bar Charts are suitable for displaying a comparison between sets of data—for example, a summary
of unique and total site visitors over a certain period of time.
The Telerik UI Bullet Chart HtmlHelper for ASP.NET Coreis a variation of a Telerik UI Bar Chart. You can
use it as a replacement for dashboard gauges and meters. The bullet graph compares a given
quantitative measure, such as temperature, against qualitative ranges, such as warm, hot, mild, cool,
chilly, cold, and so on, and a symbol marker that encodes the comparative measure, such as the max
temperature a year ago.
The Telerik UI Range Bar Chart HtmlHelper for ASP.NET Core is yet another variation of the Telerik UI
Bar Chart. It displays data as bars where each bar represents a value range that spans between its
minimum and maximum levels. A Range Bar type has floating bars unlike the standard Telerik UI Bar
Chart that has bars that are anchored to its x-axis.
To create a Bar series in the Chart HtmlHelper, use Column or Bar in the Series configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Kendo Chart Example")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series =>
{
series.Column(new double[] { 200, 450, 300, 125 }).Name("Example Series");
})
.CategoryAxis(axis => axis
.Categories(2000, 2001, 2002, 2003)
)
)
45
Telerik UI for ASP.NET Core
@(Html.Kendo().Chart()
.Name("chart")
.Title("Kendo Chart Example")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series =>
{
series.Bar(new double[] { 200, 450, 300, 125 }).Name("Example Series");
})
.CategoryAxis(axis => axis
.Categories(2000, 2001, 2002, 2003)
)
)
46
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Bar Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Range Bar Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
47
Telerik UI for ASP.NET Core
Box Plot Charts are useful for displaying variations in statistical samples of data and data details in
a small space.
Getting Started
The Box Plot Chart uses the following values:
To create a Box Plot series in the Chart HtmlHelper, use BoxPlot in the Series configuration.
All properties except for outliers have to point to numeric fields in the DataSource. outliers has
to point to a field that contains an array of numbers.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Monthly Mean Temperatures (°F)")
.Legend(legend => legend.Visible(false))
.Series(series => series
48
Telerik UI for ASP.NET Core
.BoxPlot(new System.Collections.ArrayList() {
new { lower= 26.2, q1= 38.3 , median= 51.0, q3= 61.45, upper= 68.9, mean= 49.0,
outliers= new [] {18.3, 20, 70, 72, 5}} ,
new { lower= 26.4, q1= 38.125, median= 46.8 , q3= 60.425, upper= 66.8, mean=
47.3, outliers= new [] {18, 69, 71.3, 71.5}},
new { lower= 31.6, q1= 41.725, median= 52.35, q3= 62.175, upper= 70.8, mean=
52.3, outliers= new [] {14, 16.4, 74}},
new { lower= 34.4, q1= 39.375, median= 49.9 , q3= 61.425, upper= 69.2, mean=
50.3, outliers= new [] {16, 18, 72, 72.5}} ,
new { lower= 29.9, q1= 38.35, median= 50.4, q3= 60.875, upper= 69.7, mean=
49.9, outliers= new [] {19, 20, 76, 78}},
new { lower= 22.3, q1= 36.875, median= 48.9 , q3= 62.65 , upper= 70.3, mean=
49.0, outliers= new [] {16.5, 17, 74, 75, 78}},
new { lower= 32.3, q1= 39.5, median= 54.1, q3= 61.175, upper= 67.3, mean= 50.8,
outliers= new [] {13, 14, 15, 74.3, 75.2, 76}},
new { lower= 28.5, q1= 36.075, median= 50.5 , q3= 64.2, upper= 70.4, mean=
49.6, outliers= new [] {18, 22, 73.4, 75}},
new { lower= 33.6, q1= 40.65, median= 49.55, q3= 62.8, upper= 69.2, mean= 51.1,
outliers= new [] {17, 73}},
new { lower= 33.6, q1= 38.6, median= 47.9, q3= 60.825, upper= 67.0, mean= 49.7,
outliers= new [] {12, 13.5, 16, 73, 74.6, 77}},
new { lower= 31.9, q1= 36.425, median= 49.3, q3= 61.825, upper= 69.7, mean=
49.4, outliers= new [] {17, 76}},
new { lower= 34.0, q1= 41.225, median= 51.15, q3= 62.4, upper= 68.8, mean=
51.6, outliers= new [] {14.6, 17.3, 72.3, 74}}
})
)
.CategoryAxis(categoryAxis => categoryAxis
.Categories(new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec" })
.MajorGridLines(majorGridLines => majorGridLines.Visible(false))
)
)
@(Html.Kendo().Chart()
.Name("chart")
.Title("Monthly Mean Temperatures (°F)")
.Legend(legend => legend.Visible(false))
.Series(series => series
.VerticalBoxPlot(new System.Collections.ArrayList() {
new { lower= 26.2, q1= 38.3 , median= 51.0, q3= 61.45, upper= 68.9, mean= 49.0,
outliers= new [] {18.3, 20, 70, 72, 5}},
new { lower= 26.4, q1= 38.125, median= 46.8 , q3= 60.425, upper= 66.8, mean=
47.3, outliers= new [] {18, 69, 71.3, 71.5}},
new { lower= 31.6, q1= 41.725, median= 52.35, q3= 62.175, upper= 70.8, mean=
52.3, outliers= new [] {14, 16.4, 74}},
new { lower= 34.4, q1= 39.375, median= 49.9 , q3= 61.425, upper= 69.2, mean=
50.3, outliers= new [] {16, 18, 72, 72.5}},
new { lower= 29.9, q1= 38.35, median= 50.4, q3= 60.875, upper= 69.7, mean=
49.9, outliers= new [] {19, 20, 76, 78}},
new { lower= 22.3, q1= 36.875, median= 48.9 , q3= 62.65 , upper= 70.3, mean=
49.0, outliers= new [] {16.5, 17, 74, 75, 78}},
new { lower= 32.3, q1= 39.5, median= 54.1, q3= 61.175, upper= 67.3, mean= 50.8,
outliers= new [] {13, 14, 15, 74.3, 75.2, 76}},
49
Telerik UI for ASP.NET Core
new { lower= 28.5, q1= 36.075, median= 50.5 , q3= 64.2, upper= 70.4, mean=
49.6, outliers= new [] {18, 22, 73.4, 75}},
new { lower= 33.6, q1= 40.65, median= 49.55, q3= 62.8, upper= 69.2, mean= 51.1,
outliers= new [] {17, 73}},
new { lower= 33.6, q1= 38.6, median= 47.9, q3= 60.825, upper= 67.0, mean= 49.7,
outliers= new [] {12, 13.5, 16, 73, 74.6, 77}},
new { lower= 31.9, q1= 36.425, median= 49.3, q3= 61.825, upper= 69.7, mean=
49.4, outliers= new [] {17, 76}},
new { lower= 34.0, q1= 41.225, median= 51.15, q3= 62.4, upper= 68.8, mean=
51.6, outliers= new [] {14.6, 17.3, 72.3, 74}}
})
)
.CategoryAxis(categoryAxis => categoryAxis
.Categories(new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec" })
.MajorGridLines(majorGridLines => majorGridLines.Visible(false))
)
)
You can configure the outliers separately and customize them by using:
See Also
Basic Usage of the Box Plot Chart HtmlHelper for ASP.NET Core (Demo)
Box Plot Charts on Wikipedia
Server-Side API
50
Telerik UI for ASP.NET Core
Bubble Charts
The Telerik UI Bubble Chart HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI
Bubble Chart widget.
Bubble Charts display data as points with coordinates and sizes defined by the value of their items.
Getting Started
The Bubble Chart HtmlHelper is similar to the Telerik UI Scatter Charts HtmlHelperin which the data
points are replaced with bubbles. In this way a Bubble Chart displays three-dimensional data—two
values for the coordinates of the items and one value for their size. A Bubble Chart is useful for
visualizing different scientific relationships—for example, economic or social. The X-axis of the
Bubble Charts is numerical and does not require items.
The Bubble Charts are well suited for displaying dozens to hundreds of values especially when you
wish to visualize size values which differ by several orders of magnitude. As the size value is
represented by a circle area, it is a best practice to plot positive values.
By default, negative values are not displayed. However, their area is going to be calculated as if their
value was positive. The point label displays their actual value and they will also have a different
color. To control this behavior, use the negativeValues.visible and negativeValues.color
options that are applicable to each series.
To create a Bubble series in the Chart HtmlHelper, use Bubble in the Series configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series.Bubble(new dynamic[] {
new {
x = 10,
y = 12000,
size = 0.1
}, new {
x = 24,
y = 62000,
size = 0.25
}
}).Name("Sales");
})
)
51
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Bubble Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
52
Telerik UI for ASP.NET Core
Bullet Charts
The Telerik UI Bullet HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI Bullet
Chart widget.
Getting Started
You can use the Bullet Chart HtmlHelper to visualize a comparison between an expected (target) and
actual (current) value—for example, company profit, employee performance, weather data, and so
on.
To create a Bullet series in the Chart HtmlHelper, use Bullet and VerticalBullet in the Series
configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Legend(legend => legend
.Visible(false)
)
.Series(series => {
series.Bullet(new double[][] { new double[] { 750, 762.5 }});
})
.ChartArea(chartArea => chartArea.Margin(0))
.CategoryAxis(axis => axis
.MajorGridLines(lines => lines.Visible(false))
.MajorTicks(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric()
.Min(715)
.Max(795)
.MinorTicks(lines => lines.Visible(true))
.MajorGridLines(lines => lines.Visible(false))
.PlotBands(bands => {
bands.Add().From(715).To(752).Color("#ccc").Opacity(0.6);
bands.Add().From(752).To(772).Color("#ccc").Opacity(0.3);
})
)
.Tooltip(tooltip => tooltip
53
Telerik UI for ASP.NET Core
.Visible(true)
.Shared(true)
.Template("Maximum: #= value.target # <br /> Average: #= value.current #")
)
)
The configuration from the previous example results in the following Bullet Chart.
The following example demonstrates how to use all three options to customize the target line.
.Series(series =>
{
series
.Bullet(new double[][] { new double[] { 780, 762.5 } })
.Color("darkblue")
.Target(target=>target
.Color("green")
.Border(b=>b
.Color("turquoise")
.Width(2)
)
.Line(l=>l.Width(6))
);
})
See Also
Basic Usage of the Bullet Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
54
Telerik UI for ASP.NET Core
Funnel Charts
The Telerik UI Funnel HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI Funnel
Chart widget.
Funnel Charts display a single series of data in progressively decreasing or increasing proportions,
organized in segments, where each segment represents the value for the particular item from the
series. The values of the items can also influence the height and the shape of the corresponding
segments.
Funnel Charts are suitable for representing stages in a sales process and for showing the amount of
the potential revenue from each stage. They are also useful when identifying potential problem areas
in the sales processes of an organization. Funnel Charts are similar to the Stacked Bar Chartsand are
well suited for displaying several values.
Concepts
The basic conceptual options of a Telerik UI Funnel Chart are:
55
Telerik UI for ASP.NET Core
Getting Started
The following example demonstrates how to base the widths of the bases for each segment on the
currentValue/nextValue ratio.
@(Html.Kendo().Chart().Name("chart-oct")
.Series(series =>
series.Funnel(new dynamic[]{
new {
value= 40
},
new {
value= 80
},
new {
value= 40,
},
new {
value= 10,
}
})
.DynamicHeight(false)
.DynamicSlope(true)
.Labels(l=>l.Visible(true))
)
)
56
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Funnel Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
57
Telerik UI for ASP.NET Core
Line Charts
The Telerik UI Line Chart HtmlHelper for ASP.NET Core extension is a server-side wrapper for the
Kendo UI Line Chart widget.
Line Charts are suitable for displaying quantitative data by using continuous lines passing through
points defined by the values of their items.
Getting Started
You can use the Line Chart HtmlHelper to render a trend over time and compare sets of similar data.
To create a Line series in the Chart HtmlHelper, use Line and VerticalLine in the Series
configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Internet Users")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series =>
{
series.Line(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }).Name("World");
series.Line(new double[] { 67.96, 68.93, 75, 74, 78 }).Name("United States");
})
.CategoryAxis(axis => axis
.Categories("2005", "2006", "2007", "2008", "2009")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric().Labels(labels => labels.Format("{0}%"))
)
)
The configuration from the previous example results in the following Line Chart.
58
Telerik UI for ASP.NET Core
Normal—This is the default style. It produces a straight line between data points.
Step—This style renders the connection between data points through vertical and horizontal
lines. It is suitable for indicating that the value is constant between the changes.
Smooth—This style causes the Line Chart to display a fitted curve through data points. It is
suitable when the data requires to be displayed with a curve, or when you wish to connect
the points with smooth instead of straight lines.
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Line().Style(ChartLineStyle.Smooth)
)
You can also set the line style for each Line series individually.
.Series(series =>
59
Telerik UI for ASP.NET Core
{
series.Line(new double[] { 15.7, 26.7, 20, 23.5, 26.6
}).Name("World").Style(ChartLineStyle.Smooth);
series.Line(new double[] { 67.96, 68.93, 75, 54, 78 }).Name("United
States").Style(ChartLineStyle.Smooth);
})
60
Telerik UI for ASP.NET Core
.Series(series =>
{
series.Line(new double[] { 15.7, 16.7, 20, 23.5, 26.6
}).Name("World").DashType(ChartDashType.Dot);
series.Line(new double[] { 67.96, 68.93, 75, 74, 78 }).Name("United States");
})
61
Telerik UI for ASP.NET Core
series.Line(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }).Name("World")
.Markers(m=>m
.Type(ChartMarkerShape.Square)
.Rotation(45)
.Background("yellow")
);
62
Telerik UI for ASP.NET Core
You can also completely draw custom markers for the Line series through the Visual setting as
shown in the Custom Visualsdemo.
See Also
Basic Usage of the Line Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
63
Telerik UI for ASP.NET Core
Pie Charts
The Telerik UI Pie Chart HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI Pie
Chart widget.
Pie Charts display data as single-series sectors from a two-dimensional circle which is useful for
rendering data as a part of the whole.
Getting Started
The Telerik UI Donut Chart HtmlHelper for ASP.NET Coreis a Pie Chart variation with the same ability to
display a single data series in a two-dimensional circle and is likewise useful for displaying data as a
part of the whole.
To create a Pie series in the Chart HtmlHelper, use Pie in the Series configuration.
@(Html.Kendo().Chart()
.Name("chart")
.Title("Break-up of Spain Electricity Production for 2008")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.SeriesColors(new string[] { "#03a9f4", "#ff9800", "#fad84a", "#4caf50" })
.Series(series =>
{
series.Pie(new dynamic[] {
new {category="Hydro",value=22,color="#9de219"},
new {category="Solar",value=2,color="#90cc38"},
new {category="Nuclear",value=49,color="#068c35"},
new {category="Wind",value=27,color="#006634"}})
.Overlay(o => o.Gradient(ChartSeriesGradient.RoundedBevel));
})
.Tooltip(tooltip => tooltip.
Template("${ category } - ${ value }%").Visible(true)
)
)
64
Telerik UI for ASP.NET Core
.Series(series =>
{
series.Pie(new dynamic[] {})
.Overlay(o => o.Gradient(ChartSeriesGradient.None));
})
(Default) RoundedBevel

65
Telerik UI for ASP.NET Core
SharpBevel

None

See Also
Basic Usage of the Pie Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
66
Telerik UI for ASP.NET Core
Data Series
You can plot one or more data series of a specified type in the Telerik UI Chart for ASP.NET Core.
Getting Started
To define the data series, add them to the series array.
The following example demonstrates how to define two Bar series that are bound to inline data.
@(Html.Kendo().Chart()
.Name("chart")
.Series(series =>
{
series.Bar(new double[] { 56000, 63000, 74000, 91000, 117000, 138000
}).Name("Total Visits");
series.Bar(new double[] { 52000, 34000, 23000, 48000, 67000, 83000
}).Name("Unique visitors");
})
)
Options for individual series take precedence over the options that are specified in
seriesDefaults.
@(Html.Kendo().Chart()
.Name("chart")
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Bar().Border(b=>b.Color("purple")))
.Series(series =>
{
series.Bar(new double[] { 56000, 63000, 74000, 91000, 117000, 138000
}).Name("Total Visits");
series.Bar(new double[] { 52000, 34000, 23000, 48000, 67000, 83000
}).Name("Unique visitors");
})
)
@(Html.Kendo().Chart()
.Name("chart")
67
Telerik UI for ASP.NET Core
.Series(series =>
{
series.Column(new int[] { 20, 40, 45, 30, 50 });
series.Line(new double[] { 30, 38, 40, 32, 42 });
})
)
Known Limitations
The Telerik UI Chart for ASP.NET Core can contain either Bar or Column series but not both
of them.
A Pie series cannot be used with other series including other Pie series.
Scatter and Scatter Line series cannot be used together with other series.
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
68
Telerik UI for ASP.NET Core
Date Series
You can control the display of dates in the Telerik UI Chart for ASP.NET Core.
Automatic selection of granularity or base unit (minutes, hours, days, and so on).
Label formatting that is matched to the granularity.
Grouping of categories into base units and series aggregates.
Specifying categories of type Date switches the axis to a date mode. The automatic mode selection
can be overridden by setting CategoryAxis.Typeto ChartCategoryAxisType.Date.
Date Binding
To bind the date series, use CategoryField. The categories (dates) for all series are sorted and
merged during data binding.
Date Grouping
If the series contain two or more values for a specific period (base unit), they are aggregated to
display a single value.
69
Telerik UI for ASP.NET Core
} })
.Field("Volume")
.CategoryField("Date")
)
.CategoryAxis(categoryAxis => categoryAxis.Type(ChartCategoryAxisType.Date) )
)
The following image demonstrates a chart with a set date category axis.
The following example demonstrates date series that are grouped by the year.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new List<StockDataPoint>() { new StockDataPoint {
Date = new DateTime(2011,12,30),
Volume = 20
},
new StockDataPoint {
Date = new DateTime(2011,12,31),
Volume = 40
},
new StockDataPoint {
Date = new DateTime(2012,1,1),
Volume = 45
},
new StockDataPoint {
Date = new DateTime(2012,1,2),
Volume = 30
},
new StockDataPoint {
Date = new DateTime(2012,1,3),
Volume = 50
} })
.Field("Volume")
.CategoryField("Date")
)
.CategoryAxis(categoryAxis =>
categoryAxis.Type(ChartCategoryAxisType.Date).BaseUnit(ChartAxisBaseUnit.Years) )
)
70
Telerik UI for ASP.NET Core
The following image displays a chart with a grouped date category axis. Note how the maximum
value for each year is now displayed.
Setting Aggregates
You can set an aggregate type for each series.
Min
(Default) Max
Count
Sum
Avg
First
SumOrNull
The following example demonstrates how to handle date grouping with the sum aggregate.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new List<StockDataPoint>() { new StockDataPoint {
Date = new DateTime(2011,12,30),
Volume = 20
},
new StockDataPoint {
Date = new DateTime(2011,12,31),
Volume = 40
},
new StockDataPoint {
Date = new DateTime(2012,1,1),
Volume = 45
71
Telerik UI for ASP.NET Core
},
new StockDataPoint {
Date = new DateTime(2012,1,2),
Volume = 30
},
new StockDataPoint {
Date = new DateTime(2012,1,3),
Volume = 50
} })
.Field("Volume")
.CategoryField("Date")
.Aggregate(ChartSeriesAggregate.Sum)
)
.CategoryAxis(categoryAxis =>
categoryAxis.BaseUnit(ChartAxisBaseUnit.Years).Type(ChartCategoryAxisType.Date) )
)
Default configuration
Manual configuration
Automatic fitting
Labels format
Default Configuration
.CategoryAxis(categoryAxis => categoryAxis
.Categories(new DateTime[] {new DateTime(2005, 1, 1), new DateTime(2006, 1, 1)
})
// baseUnit is set to "years".
)
.CategoryAxis(categoryAxis => categoryAxis
.Categories(new DateTime[] {new DateTime(2005, 1, 1), new DateTime(2005, 1, 2)
})
// baseUnit is set to "days".
)
Manual Configuration
You can also manually specify the BaseUnit. To display every nth base unit, set the BaseUnitStep
option.
Seconds
Minutes
72
Telerik UI for ASP.NET Core
Hours
Days
Weeks
Months
Years
Fit
Automatic Fitting
Setting the BaseUnitto ChartAxisBaseUnit.Fit constrains the total number of base units to
MaxDateGroups. The BaseUnit and BaseUnitStep are selected according to the
AutoBaseUnitSteps.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new List<StockDataPoint>() {
new StockDataPoint {
Date = new DateTime(2012,1,2),
Volume = 30
},
new StockDataPoint {
Date = new DateTime(2012,2,1),
Volume = 50
} })
.Field("Volume")
.CategoryField("Date").Type("line")
)
.CategoryAxis(categoryAxis=> categoryAxis
.BaseUnit(ChartAxisBaseUnit.Fit)
.MaxDateGroups(5)
.AutoBaseUnitSteps(unitSteps => unitSteps
.Days(new int[] { 1 }) // Would produce 31 groups => Skip to weeks.
.Weeks(new int[] { }) // Not allowed as no steps are defined => Skip to months.
.Months(new int[] { 1 }) // Results in 2 groups => Chosen.
))
)
Labels Format
The date category axis provides options for specifying one format per base unit. If specified, the
Labels.Format propertytakes priority. The global culture is used for formatting the dates and can
be overridden by setting the Labels.Cultureproperty.
.CategoryAxis(categoryAxis => categoryAxis
.Labels(labels => labels
.DateFormats(dateFormat => dateFormat.Days("M/d"))
)
)
73
Telerik UI for ASP.NET Core
Automatic selection of granularity or base unit (minutes, hours, days, and so on).
Label formatting that is matched to the granularity.
If the series values are of type Date, the X and Y axes switch into date mode. To override the
automatic mode selection, specify type: "Date".
Min
Max
AxisCrossingValue
MinorUnit
MajorUnit
Default configuration
Manual configuration
Labels format
Default Configuration
The default base unit is determined by the axis (or series) range.
.XAxis(xAxis => xAxis
.Min(new DateTime(2005,1,1))
.Max(new DateTime(2006,1,1))
// baseUnit is set to "years"
)
.XAxis(xAxis => xAxis
.Min(new DateTime(2005,1,1))
.Max(new DateTime(2005,1,2))
// baseUnit is set to "days"
)
Manual Configuration
You can also manually specify the base unit by using the following valid options:
Milliseconds
74
Telerik UI for ASP.NET Core
Seconds
Minutes
Hours
Days
Weeks
Months
Years
Labels Format
The date axis provides options for specifying one format per base unit. If specified, the
labels.format propertytakes priority. The global culture is used for formatting the dates and can
be overridden by setting the labels.cultureproperty.
.XAxis(xAxis => xAxis
.Labels(labels => labels
.DateFormats(formats => formats.Days("M/d"))
)
)
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
75
Telerik UI for ASP.NET Core
Error Bars
The Chart enables you to implement error bars which show the variability of data.
The low and high value for the error bars can be either bound to the data or calculated from the point
or series values. The error bars are specified as part of the series definition.
Area
Vertical Area
Column
Bar
Line
Vertical Line
Scatter
ScatterLine
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743,
low = 4.5,
high = 5
},
new {
value = 7.295,
low = 7,
high = 8
},
new {
value = 6.376,
low = 5,
high = 6.5
}
})
.ErrorLowField("low")
.ErrorHighField("high")
)
)
76
Telerik UI for ASP.NET Core
You can also display error bars for the series x or y value, or both. To set the low and high fields for
the series x value, set the XErrorLowFieldand XErrorHighFieldseries options. To specify the
low and high fields for the y value of the series, use the YErrorLowFieldand YErrorHighField
options.
The following example demonstrates how to bind the error bars for the x value of the series.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Scatter(new object[] {
new {
x= 6.4,
y= 13.4,
low= 5,
high= 7
},
new {
x= 1.7,
y= 11,
low= 1,
high= 3
}, new {
x= 5.4,
y= 8,
low= 3,
high= 6}
})
.XErrorLowField("low")
.XErrorHighField("high")
)
)
The following example demonstrates how to bind the error bars for the y value of the series.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Scatter(new object[] {
new {
x= 6.4,
y= 13.4,
low= 12,
high= 17
},
new {
x= 1.7,
y= 11,
low= 11,
high= 14
}, new {
x= 5.4,
y= 8,
low= 5,
high= 8}
})
.YErrorLowField("low")
.YErrorHighField("high")
)
77
Telerik UI for ASP.NET Core
)
The following example demonstrates how to set a numeric value for the categorical series.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743
},
new {
value = 7.295
},
new {
value = 6.376
}
})
.ErrorBars(err => err.Value("1"))
)
)
The following example demonstrates how to set a numeric value for the scatter series.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Scatter(new object[] {
new {
x = 6.4,
y = 13.4
},
new {
x = 1.7,
y = 11
},
new {
x = 5.4,
y = 8
}
})
.ErrorBars(err => err.YValue("1"))
)
78
Telerik UI for ASP.NET Core
)
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743
},
new {
value = 7.295
},
new {
value = 6.376
}
})
.ErrorBars(err => err.Value("percentage(20)"))
)
The following example demonstrates how to use the standard error type.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743
},
new {
value = 7.295
},
new {
value = 6.376
}
})
.ErrorBars(err => err.Value("stderr"))
)
The following example demonstrates how to use the standard deviation type.
79
Telerik UI for ASP.NET Core
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743
},
new {
value = 7.295
},
new {
value = 6.376
}
})
.ErrorBars(err => err.Value("stddev(0.5)"))
)
The following example demonstrates how to use different percentages for the low and high values.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Column(new object[] {
new {
value = 4.743
},
new {
value = 7.295
},
new {
value = 6.376
}
})
.ErrorBars(err => err.ValueHandler("calculateError"))
)
function calculateError(data) {
var value = data.value;
var lowPercentage = value * 0.05;
var highPercentage = value * 0.1;
return [lowPercentage, highPercentage];
80
Telerik UI for ASP.NET Core
}
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
81
Telerik UI for ASP.NET Core
Notes
The Telerik UI Chart enables you to display the metadata of a point or a specific part of the axis.
Getting Started
The following example demonstrates how to add a note for each series point.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Line(new object[] {
new {
value = 1,
noteText = "min"
},
new {
value = 2,
},
new {
value = 3,
noteText = "max"
}
})
.Field("value")
.NoteTextField("noteText")
)
)
Using Templates
To provide better flexibility, define the content of the notes through a template.
82
Telerik UI for ASP.NET Core
The template provides access to all information that is associated with the point:
value—The point value. Value dimensions are available as properties, for example, value.x
and value.y.
category—The category name.
series—The data series.
(When binding to a data source) dataItem—The original data item.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Line(new object[] {
new {
value = 1,
noteText = "min"
},
new {
value = 2,
},
new {
value = 3,
noteText = "max"
}
})
.Field("value")
.NoteTextField("noteText")
.Notes(n => n
.Label(l => l
.Position(ChartNoteLabelPosition.Outside)
.Template("#= dataItem.noteText # of the series")
))
)
)
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
83
Telerik UI for ASP.NET Core
"Top"
"Bottom"
To control the position of the legend, use any of the following supported Position values:
"Top"
"Bottom"
"Left"
"Right"
"Custom"
To customize the position of the legend, use the offsetX and offsetY options.
84
Telerik UI for ASP.NET Core
To exclude series from the legend, set their VisibleInLegend option to false.
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
85
Telerik UI for ASP.NET Core
Tooltip
The Telerik UI Chart enables you to display details about the data point over which the mouse is
currently hovering.
Getting Started
By default, the tooltip of the Chart is not visible. You can enable it by setting the visible property of
the tooltip object to true.
@(Html.Kendo().Chart()
.Name("chart")
.Series(s => s
.Bar(new double[] { 67.96, 68.93, 75, 74, 78 })
)
.CategoryAxis(c => c
.Categories(new string[] { "2005", "2006", "2007", "2008", "2009" })
)
.Tooltip(t => t.Visible(true))
)
.Series(s => s
.Bar(new double[] { 67.96, 68.93, 75, 74, 78 })
.Tooltip(t=>t.Visible(true))
)
86
Telerik UI for ASP.NET Core
To format the point value, use the Format property. In the following example, N0 indicates that the
value will be rounded to a whole number and will have a thousands separator.
Points in categorical (XY) Charts have two values— {0} and {1} (X and Y).
.Tooltip(t => t
.Visible(true)
.Format("Value: {0:N0}")
)
Using Templates
To provide better flexibility, define the content of a tooltip through a template.
The template provides access to all information associated with the point:
value—The point value. Value dimensions are available as properties, for example, value.x
and value.y.
category—The category name.
series—The data series.
(When binding to a data source) dataItem—The original data item.
.Tooltip(t => t
.Visible(true)
.Template("Value: #= value # ; Category: #= category #")
)
.Tooltip(t => t
.Visible(true)
.TemplateId("tooltipTemplate")
)
<script id="tooltipTemplate" type="text/x-kendo-template">
Value: #= value # ; Category: #= category #
</script>
See Also
Using the API of the Chart HtmlHelper for ASP.NET Core (Demo)
Basic Usage of the Area Chart HtmlHelper for ASP.NET Core (Demos)
Server-Side API
87
Telerik UI for ASP.NET Core
Sparklines are very small charts that are drawn without axes, coordinates, legends, titles, or other
chart-specific elements. They behave like inline elements as they are rendered inside a span element
so that they can be easily embedded in text as opposed to the standard Telerik UI Charts which
behave like block elements as they are rendered inside div elements.
While Sparklines are typically line charts, other types are supported as well:
Line (default)
Bar (Data Bars)
Column
Area
Pie
Bullet
Generally, Sparklines are simple, word-sized graphics that can be embedded in chunks of
text, tables, or headlines. The concept for such graphics was developed by Edward Tufte. The
Telerik UI Sparklines HtmlHelper is a version of the Telerik UI Chart HtmlHelper that is
tailored for this specific application.
Basic Configuration
To create the Sparklines, add Html.Kendo.Sparkline() to the view and provide it with a Name.
Optionally, set the width and height of the desired chart by using CSS.
The width of the Line, Area, and Column Sparklines is determined by the number of data
points.
Bar and Bullet graphs have a default width that can be overridden with CSS.
The Pie width equals the line-height to make a square.
@(Html.Kendo().Sparkline()
.Name("temp-log")
.Type(SparklineType.Column)
.Tooltip(tooltip => tooltip.Format("{0} °C"))
.Data(ViewBag.TemperatureData)
)
88
Telerik UI for ASP.NET Core
Axes configuration
See Also
Basic Usage of the Sparkline HtmlHelper for ASP.NET Core (Demo)
Server-Side API
89
Telerik UI for ASP.NET Core
Data Binding
The Sparkline charts can visualize series that are bound to both local and remote data.
@(Html.Kendo().Sparkline()
.Name("temp-log")
.Type(SparklineType.Column)
.Series(d=>d.Column(new int[] { 10 ,15, 8 ,2,30}))
)
@(Html.Kendo().Sparkline()
.Name("temp-log")
.Type(SparklineType.Column)
.Data(ViewBag.TemperatureData)
)
@(Html.Kendo().Sparkline()
.Name("sparkline-tmax")
.DataSource(ds => ds.Read(read => read.Url(Url.Action("_Weather", "Sparklines"))))
.Series(series => series
.Column("TMax").Color("#ff0000").NegativeColor("#0099ff")
)
See Also
Local Data Binding by the Sparkline HtmlHelper for ASP.NET Core (Demo)
Remote Data Binding by the Sparkline HtmlHelper for ASP.NET Core (Demo)
Server-Side API
90
Telerik UI for ASP.NET Core
Axes Configuration
The Sparkline HtmlHelper is a categorical (discrete) chart and has an implicit category and a value
axis.
The axis orientation (horizontal or vertical) is inferred from the series type.
The following example demonstrates how to use the CategoryAxis object to set the category
names.
@(Html.Kendo().Sparkline()
.Name("World")
.Data(new double[] { 15.7, 16.7, 20, 23.5, 26.6 })
.CategoryAxis(c => c
.Categories(new string[] { "2005", "2006", "2007", "2008", "2009" })
)
)
You can also bind the category name to a field of the data item.
@(Html.Kendo().Sparkline()
.Name("Sparkline")
.Series(s => s.Bar(new object[] { new {
country = "United States",
year = "2005",
value = 67.96
}, new {
country = "United States",
year = "2006",
value = 68.93
}
}).Field("value"))
.CategoryAxis(c => c.Field("year"))
)
Displaying Dates
The category axis provides built-in support for displaying dates. This includes:
Specifying categories of type Date switches the axis to a date mode. The automatic mode selection
91
Telerik UI for ASP.NET Core
Default configuration
Manual configuration
Series aggregates
Default Configuration
.CategoryAxis(c => c
.Categories(new DateTime[] { new DateTime(2005, 1, 1), new DateTime(2006, 1, 1)
})
// baseUnit is set to "years".
)
.CategoryAxis(c => c
.Categories(new DateTime[] { new DateTime(2005, 1, 1), new DateTime(2005, 1, 2)
})
// baseUnit is set to "days".
)
Manual Configuration
Seconds
Minutes
Hours
Days
Weeks
Months
Years
Fit
Series Aggregates
If two or more categories fall within a base unit, its values are aggregated to display a single point.
@(Html.Kendo().Sparkline()
.Name("Sparkline")
.Series(s => s.Column(new int[] { 20, 40, 45, 30, 50 }))
.CategoryAxis(c => c
.Categories(new DateTime[] {
new DateTime(2011,12,30),
92
Telerik UI for ASP.NET Core
new DateTime(2011,12,31),
new DateTime(2012,01,01),
new DateTime(2012,01,02),
new DateTime(2012,01,03)
})
)
)
The code from the previous example results in the following Sparkline chart. Note that values are
displayed as are.
The following example demonstrates the Sparkline with its base unit changed to "years".
.CategoryAxis(c => c
.BaseUnit(ChartAxisBaseUnit.Years)
.Categories(new DateTime[] {
new DateTime(2011,12,30),
new DateTime(2011,12,31),
new DateTime(2012,01,01),
new DateTime(2012,01,02),
new DateTime(2012,01,03)
})
)
The following example demonstrates a Sparkline with a grouped date category axis. Note the way
the Sparkline displays the maximum value for each year.
You can also change the aggregate function for each series.
.Series(s => s
.Column(new int[] { 20, 40, 45, 30, 50 })
.Aggregate(ChartSeriesAggregate.Avg))
Min
Max
Count
Sum
Avg
First
SumOrNull
93
Telerik UI for ASP.NET Core
Getting Started
To access the configuration options, use ValueAxis. The following example configures a numeric
axis with a minimum value of 0 and a maximum value of 100.
@(Html.Kendo().Sparkline()
.Name("Sparkline")
.Series(s => s
.Column(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }))
.ValueAxis(axis => axis.Numeric().Min(0).Max(100))
.CategoryAxis(c => c
.Categories(new string[] { "2005", "2006", "2007", "2008", "2009" })
)
)
@(Html.Kendo().Sparkline()
.Name("temp-range")
.Type(SparklineType.Bullet)
.ValueAxis(axis => axis
.Numeric()
.Min(0)
.Max(30)
.PlotBands(bands =>
{
bands.Add().From(0).To(15).Color("#787878").Opacity(0.15);
bands.Add().From(15).To(22).Color("#787878").Opacity(0.3);
bands.Add().From(22).To(30).Color("#787878").Opacity(0.15);
})
)
.Data(ViewBag.TemperatureRange)
)
See Also
Basic Usage of the Sparklines HtmlHelper for ASP.NET Core (Demo)
Server-Side API
94
Telerik UI for ASP.NET Core
The StockChart is a specialized control visualizing the price movement of any financial instrument
over a certain period of time. StockCharts include extensive touch support and a navigator pane for
easy browsing of extended time periods. Generally, StockCharts extend the Telerik UI Chart and
share most of its features.
All of the following series types that are supported by the StockChart are also accessible from a
Telerik UI Chart:
Candlestick
Open-high-low-close (OHLC)
Column
Line
Area
Basic Configuration
The UI for ASP.NET StockChart makes Ajax requests when it is bound to a data source and has to be
configured for Ajax binding.
The following example demonstrates how to add a new action method which returns data to
populate the StockChart.
@(Html.Kendo().StockChart<Kendo.Mvc.Examples.Models.StockDataPoint>()
.Name("stockChart")
.Title("The Boeing Company (NYSE:BA)")
.DataSource(ds => ds.Read(read => read
.Action("_BoeingStockData", "Home")
))
.DateField("Date")
)
public class StockDataPoint
{
public DateTime Date { get; set; }
public decimal Close { get; set; }
public long Volume { get; set; }
95
Telerik UI for ASP.NET Core
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public string Symbol { get; set; }
}
public IActionResult Index()
{
return View();
}
public IActionResult _BoeingStockData()
{
using (var db = GetContext())
{
// Return the data as JSON.
return Json(
(from s in db.Stocks
where s.Symbol == "BA"
select new StockDataPoint
{
Date = s.Date,
Open = s.Open,
High = s.High,
Low = s.Low,
Close = s.Close,
Volume = s.Volume
}).ToList()
);
}
}
The following example demonstrates how to create the main and the navigator data series.
@(Html.Kendo().StockChart<Kendo.Mvc.Examples.Models.StockDataPoint>()
.Name("stockChart")
.Title("The Boeing Company (NYSE:BA)")
.DataSource(ds => ds.Read(read => read
.Action("_BoeingStockData", "Home")
))
.DateField("Date")
.Series(series => {
series.Candlestick(s => s.Open, s => s.High, s => s.Low, s => s.Close);
})
.Navigator(nav => nav
.Series(series => {
series.Line(s => s.Volume);
})
)
)
96
Telerik UI for ASP.NET Core
Events
You can subscribe to all StockChart events.
@(Html.Kendo().StockChart(Model)
.Name("stockChart")
.Title("The Boeing Company (NYSE:BA)")
.DateField("Date")
.Series(series => {
series.Candlestick(s => s.Open, s => s.High, s => s.Low, s => s.Close);
})
.Events(e => e
.DataBound("stockChart_dataBound")
.SeriesClick("stockChart_seriesClick")
)
)
<script>
function stockChart_dataBound(e) {
// Handle the dataBound event.
}
function stockChart_seriesClick(e) {
// Handle the seriesClick event.
}
</script>
@(Html.Kendo().StockChart(Model)
.Name("stockChart")
.Title("The Boeing Company (NYSE:BA)")
.DateField("Date")
.Series(series => {
series.Candlestick(s => s.Open, s => s.High, s => s.Low, s => s.Close);
})
.Events(e => e
.DataBound(@<text>
function(e) {
//Handle the dataBound event inline.
}
</text>)
97
Telerik UI for ASP.NET Core
.SeriesClick(@<text>
function(e) {
//Handle the seriesClick event inline.
}
</text>)
)
)
// Place the following after the declaration of the Barcode for ASP.NET Core.
<script>
$(function() {
// The Name() of the StockChart is used to get its client-side instance.
var chart = $("#stockChart").data("kendoStockChart");
});
</script>
See Also
Basic Usage of the StockChart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
98
Telerik UI for ASP.NET Core
Data Binding
The Telerik UI StockChart provides the single data-sourceand master and navigator data-sourcebinding
modes.
In both modes, you have to set a DateFieldto indicate the field that contains the date of the data
item.
@(Html.Kendo().StockChart<Kendo.Mvc.Examples.Models.StockDataPoint>()
.Name("stockChart")
.Title("The Boeing Company \n (NYSE:BA)")
.DataSource(ds => ds.Read(read => read
.Action("_BoeingStockData", "Financial")
))
.DateField("Date")
.Series(series =>
{
series.Candlestick(s => s.Open, s => s.High, s => s.Low, s => s.Close);
})
.Navigator(nav => nav
.Series(series =>
{
series.Area(s => s.Close);
})
.Select(
DateTime.Parse("2009/02/05"),
DateTime.Parse("2011/10/07")
)
)
)
99
Telerik UI for ASP.NET Core
resolution. This approach enables the filtering of the main data source and can be made more
efficient. In the master and navigator data-source binding mode, the StockChart is set up with two
data source instances—one for the main chart (master) and one for the Navigator pane (navigator).
For a runnable example, refer to the demo on virtualization.
This mode is useful when the service is expected to provide views over the data with a different time
resolution. The navigator can then load a low resolution preview while the main data source handles
the detailed data.
The data for the Navigator will be fetched only once and without any filters. To change this behavior,
change its configuration or call methods directly on the DataSource. The fetched data will be
displayed in its entirety in the Navigator pane.
The main data source will be filtered based on the selected date range before being fetched. It is
recommended that you use server filtering to make sure that only the visible range data is
transferred. Even without applying server filtering, a reduction in the processing time will occur
which is needed by the Chart to display the data.
Each subsequent pan, zoom, and selection operation will update the filters on the main data source
and fetch it.
The following example demonstrates a StockChart in the master and navigator data-source binding
mode.
@(Html.Kendo().StockChart<Kendo.Mvc.Examples.Models.StockDataPoint>()
.Name("stockChart")
.Title("The ACME Company")
.DataSource(ds => ds
.Read(read => read
.Action("_StockData", "Financial")
)
.ServerOperation(true)
)
.DateField("Date")
.Series(series =>
{
series.Candlestick(s => s.Open, s => s.High, s => s.Low, s => s.Close);
})
.Navigator(nav => nav
.DataSource(ds => ds
.Read(read => read
.Action("_StockData", "Financial")
)
)
.Series(series =>
{
series.Area(s => s.High);
})
.Select(
DateTime.Parse("2009/02/05"),
DateTime.Parse("2011/10/07")
)
)
)
100
Telerik UI for ASP.NET Core
The following example demonstrates a sample filter submitted by the StockChart for the main data
source. The filter field is always Date regardless of the DateField setting.
{
"logic": "and",
"filters": [
{
"field": "Date",
"operator": "gte",
"value": "2009-01-31T22:00:00.000Z"
},
{
"field": "Date",
"operator": "lt",
"value": "2011-10-06T21:00:00.000Z"
}
]
}
See Also
Basic Usage of the StockChart HtmlHelper for ASP.NET Core (Demo)
Server-Side API
101
Telerik UI for ASP.NET Core
The TreeMap displays hierarchical data in a traditional tree structure. TreeMaps also support
different rendering types such us Squarified, Vertical, and Horizontal (slice and dice algorithm).
@(Html.Kendo().TreeMap()
.Name("treeMap")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Population_Read", "TreeMap")
)
.Model(m => m.Children("Items"))
)
.ValueField("Value")
.TextField("Name")
)
public ActionResult Population_Read()
{
var result = new List<Population>();
var population = new Population("Parent One", 1, new List<Population>());
population.Items.Add(new Population("Child 1", 2, null));
population.Items.Add(new Population("Child 2", 3, null));
result.Add(population);
return Json(result);
}
public class Population
{
public Population(string name, int value, List<Population> items)
{
this.Name = name;
this.Value = value;
this.Items = items;
}
public string Name { get; set; }
public int Value { get; set; }
102
Telerik UI for ASP.NET Core
public List<Population> Items { get; set; }
}
Events
You can subscribe to all TreeMap events.
@(Html.Kendo().TreeMap()
.Name("treemap")
.Events(events => events
.ItemCreated("onItemCreated")
.DataBound("onDataBound")
)
)
<script>
function onItemCreated(e) {
// Tthe HTML element.
var element = e.element;
// The dataItem to which the element is bound.
var dataItem = e.sender.dataItem(e.element);
}
function onDataBound(e) {
// Handle the dataBound event.
}
</script>
@(Html.Kendo().TreeMap()
.Name("treemap")
.Events(e => e
.ItemCreated(@<text>
function(e) {
// The HTML element.
var element = e.element;
// The dataItem to which the element is bound.
var dataItem = e.sender.dataItem(e.element);
}
</text>)
.DataBound(@<text>
function(e) {
// Handle the dataBound event.
}
</text>)
)
)
103
Telerik UI for ASP.NET Core
// Place the following after the declaration of the TreeMap for ASP.NET Core.
<script>
$(function() {
// The Name() of the TreeMap is used to get its client-side instance.
var treemap = $("#treemap").data("kendoTreeMap");
});
</script>
See Also
Basic Usage of the TreeMap HtmlHelper for ASP.NET Core (Demo)
Server-Side API
104
Telerik UI for ASP.NET Core
@(Html.Kendo().Chat()
// The name of the Chat is mandatory.
// It specifies the "id" and the "name" attributes of the widget.
.Name("chat")
)
Basic Configuration
The following example demonstrates the available configuration options supported by the Chat
HtmlHelper.
@(Html.Kendo().Chat()
.Name("chat")
// The user configuration of the Chat.
.User(u => u
.Name("ChatBot Name")
.IconUrl("https://demos.telerik.com/kendo-ui/content/chat/avatar.png")
)
// Attach the event handlers.
.Events(e => e
.Post("onPost")
.ActionClick("onActionClick")
.SendMessage("onSendMessage")
.TypingStart("onTypingStart")
.TypingEnd("onTypingEnd")
)
// Configure the placeholder message.
.Messages(m => m
.Placeholder("Type your message")
)
)
See Also
105
Telerik UI for ASP.NET Core
106
Telerik UI for ASP.NET Core
Peer-to-Peer Chat
You can configure a Telerik UI Chat HtmlHelper for ASP.NET Core and a .Net Core SignalRservice to
create a Peer-to-Peer Chat application.
To create the Peer-to-Peer Chat you have to implement the SignalR Hub server and, then, to
implement the application client:
Create a new Telerik UI for ASP.NET Core application from the Standard template
Create a new .Net Core application in Visual Studio and include the Telerik UI for ASP.NET Core
package
Create a new .Net Core application with the CLI and include the Telerik UI for ASP.NET Core
package
namespace CoreSignalR
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
// Add the SignalR service.
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
107
Telerik UI for ASP.NET Core
...
// Point to the route that will return the SignalR Hub.
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chat");
});
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace CoreSignalR
{
// The Hub class should inherit from the Microsoft.AspNet.SignalR.Hub
public class ChatHub : Hub
{
public async Task Send(object sender, string message)
{
// Broadcast the message to all clients except the sender
await Clients.Others.SendAsync("broadcastMessage", sender, message);
}
public async Task SendTyping(object sender)
{
// Broadcast the typing notification to all clients except the sender
await Clients.Others.SendAsync("typing", sender);
}
}
}
@{
var name = Guid.NewGuid().ToString();
}
@(Html.Kendo().Chat()
.Name("chat")
.User(user => user
// Each instance of the app will generate a unique username.
// In this way, the SignalR Hub "knows" who is the user that sends the message
// and who are the clients that have to receive that message.
.Name(@name)
.IconUrl("http://demos.telerik.com/kendo-ui/content/chat/avatar.png")
)
.Events(events => events
108
Telerik UI for ASP.NET Core
.TypingStart("onTypingStart")
.Post("onPost")
)
)
<script>
// The `typingStart` will notify the SignallR Hub that the current client is
typing.
// The Hub, in turn, will notify all the other clients that the user has started
typing.
function onTypingStart(e) {
chatHub.invoke("sendTyping", chat.getUser());
}
// The `post` handler will send the user data and the typed text to the SignalR
Hub.
// The Hub will then forward that info to the other clients.
function onPost(args) {
chatHub.invoke("send", chat.getUser(), args.text);
}
</script>
npm install @aspnet/signalr
2. Copy the @aspnet/signalr folder from the node_modules directory to the wwwroot/lib
folder of the Core project.
3. Include the SignalR script on the HTML page.
<script src="lib/signalr/dist/browser/signalr.min.js"></script>
// Point to the Hub remote endpoint.
window.chatHub = new signalR.HubConnectionBuilder()
.withUrl('/chat')
.build();
chatHub.start()
.catch(function(err) {
console.error(err.toString());
});
109
Telerik UI for ASP.NET Core
6. Attach the event handlers for the respective remote Hub actions.
$(document).ready(function() {
window.chat = $("#chat").getKendoChat();
chatHub.on('broadcastMessage', function(sender, message) {
var message = {
type: 'text',
text: message
};
// Render the received message in the Chat.
chat.renderMessage(message, sender);
});
chatHub.on('typing', function(sender) {
// Display the typing notification in the Chat.
chat.renderMessage({ type: 'typing' }, sender);
});
});
See Also
Basic Usage of the Chat HtmlHelper for ASP.NET Core (Demo)
Server-Side API
110
Telerik UI for ASP.NET Core
FileManager Overview
The Telerik UI for ASP.NET Core FileManager is an Explorer-like component enabling you to manage
file and folders.
It enables you to organize and manage files and folders and provides you with a rich API for
customization. You can show additional information about the selected file in a
template-customizable Preview Pane, which you can show or hide via a switch button. The widget is
built entirely by Kendo UI for jQuery components: Grid, ListView, TreeView, Toolbar, Breadcrumb.
@(Html.Kendo().FileManager()
.Name("filemanager")
.DataSource(ds =>
{
ds.Read(operation => operation
.Type(HttpVerbs.Post)
.Action("Read", "FileManagerData")
);
ds.Destroy(operation => operation
.Type(HttpVerbs.Post)
.Action("Destroy", "FileManagerData")
);
ds.Create(operation => operation
.Type(HttpVerbs.Post)
.Action("Create", "FileManagerData")
);
ds.Update(operation => operation
.Type(HttpVerbs.Post)
.Action("Update", "FileManagerData")
);
})
.UploadUrl("Upload", "FileManagerData")
)
// GET: /FileManager/
private const string contentFolderRoot = "~/Content/";
private const string prettyName = "Folders/";
private static readonly string[] foldersToCopy = new[] {
"~/Content/shared/filemanager" };
/// <summary>
/// Gets the base paths from which content will be served.
/// </summary>
public override string ContentPath
{
111
Telerik UI for ASP.NET Core
get
{
return CreateUserFolder();
}
}
/// <summary>
/// Gets the valid file extensions by which served files will be filtered.
/// </summary>
public override string Filter
{
get
{
return "*.*";
}
}
private string CreateUserFolder()
{
var virtualPath = Path.Combine(contentFolderRoot, "UserFiles", prettyName);
var path = Server.MapPath(virtualPath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
foreach (var sourceFolder in foldersToCopy)
{
CopyFolder(Server.MapPath(sourceFolder), path);
}
}
return virtualPath;
}
private void CopyFolder(string source, string destination)
{
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
foreach (var file in Directory.EnumerateFiles(source))
{
var dest = Path.Combine(destination, Path.GetFileName(file));
System.IO.File.Copy(file, dest);
}
foreach (var folder in Directory.EnumerateDirectories(source))
{
var dest = Path.Combine(destination, Path.GetFileName(folder));
CopyFolder(folder, dest);
}
}
var filemanager = $("#filemanager").data("kendoFileManager");
112
Telerik UI for ASP.NET Core
Visit the Client API sectionfor full description of the configurations methods and events of the Kendo
UI for jQuery FileManager component.
See Also
Basic Usage of the FileManager (Demo)
Binding Overview of the FileManager
Globalization in Telerik UI for ASP.NET Core
113
Telerik UI for ASP.NET Core
DataBiding Overview
Depending on the configuration of its DataSource, the UI for ASP.NET Core FileManager provides
different types of data binding.
Remote Binding
The Telerik UI for ASP.NET Core FileManager provides its own ContentProviderController
which you need to inherit, in order to use the inbuilt read, create, update and destroy methods.
As those as virtual methods, they can be overwritten and extended.
To bind the FileManager to remote data, specify the dataSource option and supply the object with
the needed endpoints for read, create, update and destroy operations. The following example
demonstrates such implementation, where the FileManagerData inherits the
ContentProviderController:
@(Html.Kendo().FileManager()
.Name("filemanager")
.DataSource(ds =>
{
ds.Read(operation => operation
.Type(HttpVerbs.Post)
.Action("Read", "FileManagerData")
);
ds.Destroy(operation => operation
.Type(HttpVerbs.Post)
.Action("Destroy", "FileManagerData")
);
ds.Create(operation => operation
.Type(HttpVerbs.Post)
.Action("Create", "FileManagerData")
);
ds.Update(operation => operation
.Type(HttpVerbs.Post)
.Action("Update", "FileManagerData")
);
})
.UploadUrl("Upload", "FileManagerData")
)
// GET: /FileManager/
private const string contentFolderRoot = "~/Content/";
private const string prettyName = "Folders/";
private static readonly string[] foldersToCopy = new[] {
"~/Content/shared/filemanager" };
/// <summary>
/// Gets the base paths from which content will be served.
/// </summary>
public override string ContentPath
{
get
114
Telerik UI for ASP.NET Core
{
return CreateUserFolder();
}
}
/// <summary>
/// Gets the valid file extensions by which served files will be filtered.
/// </summary>
public override string Filter
{
get
{
return "*.*";
}
}
private string CreateUserFolder()
{
var virtualPath = Path.Combine(contentFolderRoot, "UserFiles", prettyName);
var path = Server.MapPath(virtualPath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
foreach (var sourceFolder in foldersToCopy)
{
CopyFolder(Server.MapPath(sourceFolder), path);
}
}
return virtualPath;
}
private void CopyFolder(string source, string destination)
{
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
foreach (var file in Directory.EnumerateFiles(source))
{
var dest = Path.Combine(destination, Path.GetFileName(file));
System.IO.File.Copy(file, dest);
}
foreach (var folder in Directory.EnumerateDirectories(source))
{
var dest = Path.Combine(destination, Path.GetFileName(folder));
CopyFolder(folder, dest);
}
}
The following list provides information about the default requests and responses for the create,
read, destroy operations.
Create—Makes a POST request for the creation of a directory with the following parameters.
{"Name":"...","Size":0,"Path":"...","Extension":".txt","IsDirectory":...,"HasDi
rectories":...,"Created":"...","CreatedUtc":"...","Modified":"...","ModifiedUtc"
:"..."}
115
Telerik UI for ASP.NET Core
Read—Makes a POST request that contains the path parameter to specify the path which is
browsed and expects a file listing in the following format:
[
{"Name":"Documents","Size":0,"Path":"Documents","Extension":"","IsDirectory":tr
ue,"HasDirectories":false,"Created":"\/Date(1578897289317)\/","CreatedUtc":"\/D
ate(1578897289317)\/","Modified":"\/Date(1578897289332)\/","ModifiedUtc":"\/Dat
e(1578897289332)\/"},
...
]
{"Name":"...","Size":0,"Path":"...","Extension":".txt","IsDirectory":...,"HasDi
rectories":...,"Created":"...","CreatedUtc":"...","Modified":"...","ModifiedUtc"
:"..."}
See Also
Overview of Telerik UI for ASP.NET Core FileManager
Navigation in Telerik UI for ASP.NET Core FileManager
Preview Panes in Telerik UI for ASP.NET Core FileManager
116
Telerik UI for ASP.NET Core
ContextMenu in FileManager
The Telerik UI for ASP.NET Core FileManager's ContextMenu enables you to easily execute
FileManager commands on the selected file or folder.
The component uses the Telerik UI for ASP.NET Core ContextMenu, enabling you to get full
advantage of its Client API. Once an item is selected, the corresponding command is executed.
The default items in the ContextMenu are rename and delete. You can define your custom items
which can execute custom commands. You can also manage what items should be visible, by
enumerating the needed ones in the initialization of the component (see Example below)
@(Html.Kendo().FileManager()
.Name("filemanager")
.ContextMenu(context => context.Items(items =>
{
items.Add("rename");
items.Add("delete");
}))
...
)
See Also
Overview of FileManager
Drag and Drop FileManager
Navigation in FileManager
117
Telerik UI for ASP.NET Core
The following example demonstrated how to disable the Drag and Drop functionality of the
FileManager:
@(Html.Kendo().FileManager()
.Name("filemanager")
.Draggable(false)
...
)
See Also
Overview of Telerik UI for ASP.NET Core FileManager
Preview Panes in Telerik UI for ASP.NET Core FileManager
ToolbarCommands inTelerik UI for ASP.NET Core FileManager
118
Telerik UI for ASP.NET Core
Views Overview
The Telerik UI for ASP.NET Core FileManager provides two inbuilt views for content visualization:
Grid and List Views.
You can switch between views from the Toolbar button group.
Grid View
This view is achieved with the Telerik UI for ASP.NET Core Grid and in renders the files in a tabular
manner (see Image1 below). That said, you can control the configuration of this view trough the
views.grid object of the FileManager (see example below).
@(Html.Kendo().FileManager()
.Name("filemanager")
.Views(v => v.Grid(grid => grid.Columns(cols => cols.Add(....))))
)
@(Html.Kendo().FileManager()
.Name("filemanager")
.Views(v=>v.List(list=>list.TemplateId("...")))
)
119
Telerik UI for ASP.NET Core
See Also
ContextMenu in Telerik UI for ASP.NET Core FileManager
Drag and Drop in Telerik UI for ASP.NET Core FileManager
120
Telerik UI for ASP.NET Core
Navigation Overview
The navigation within the file structure in the Telerik UI for ASP.NET Core FileManager is achieved
with the help of an inbuilt TreeViewand Breacrumbcomponents.
TreeView
On the left-hand side of the FileManager there is a nested Telerik UI for ASP.NET Core TreeView
component, listing all folders loaded in the FileManager. The TreeView allows dragging and dropping
files inside it, or between the Grid and ListView. It also provides you the possibility to rename files or
folders, as well as execute commands with the inbuilt ContextMenu.
The nested Telerik UI for ASP.NET Core TreeViewcomponent is the standard component from the
Telerik UI for ASP.NET Core suite. This is why, all functionalities and features, such as Keyboard
Support and Accessibility compliance, are inherited.
Breadcrumb
As for R1 2020, the Telerik UI for ASP.NET Core Breadcrumbcomponent is added to the Kendo UI suite
and it is incorporated in the FileManager for easy navigation.
See Also
Overview of Kendo UI FileManager
Kendo UI TreeView
Breadcrumb
Sort in Kendo UI FileManager
Search in Kendo UI FileManager
121
Telerik UI for ASP.NET Core
The preview pane visibility could be toggled by the Switch Tool in the FileManager Toolbar. By
default, it shows the following information about the selected file or folder:
The MetaFields object in the PreviewPane configuration, allows you to control which fields from
the above-enumerated should be displayed. If you need to show only the Extension and Size
information in the Preview Pane, the configuration would be as follows:
@(Html.Kendo().FileManager()
.Name("filemanager")
.PreviewPane(p => p.MetaFields("size", "extension"))
.....
)
@(Html.Kendo().FileManager().Name("filemanager")
.PreviewPane(p => p.SingleFileTemplateId("preview-template"))
......
)
<script id="preview-template" type="text/kendo-ui-template">
<div class="#=styles.fileInfo#">
<div class="#=styles.filePreviewWrapper#">
<span class="k-icon k-i-#=kendo.getFileGroup(selection[0].extension,
true)#"></span>
</div>
<div class="#=styles.fileTitleWrapper#">
<span class="#=styles.fileTitle#">#=selection[0].name#</span>
</div>
#if(metaFields){#
<dl class="#=styles.fileMetaWrapper#">
122
Telerik UI for ASP.NET Core
#for(var i = 0; i < metaFields.length; i+=1){#
#var field = metaFields[i]#
<dt class="#=styles.metaLabel#">#=messages[field]#: </dt>
<dd class="#=styles.metaValue# #=styles[field]#">
#if(field == "size"){#
#=kendo.getFileSizeMessage(selection[0][field])#
#} else if(selection[0][field] instanceof Date) {#
#=kendo.toString(selection[0][field], "G")#
#} else if(field == "extension") {#
#=kendo.getFileGroup(selection[0].extension)#
#} else {#
#=selection[0][field]#
#}#
</dd>
<dd class="line-break"></dd>
# } #
</dl>
#}#
</div>
</script>
See Also
Overview of Telerik UI for ASP.NET Core FileManager
Basic Usage of the Telerik UI for ASP.NET Core FileManager (Demo)
Client API section
Sort in Telerik UI for ASP.NET Core FileManager
Toolbar Commands in Telerik UI for ASP.NET Core FileManager
123
Telerik UI for ASP.NET Core
Search in FileManager
The Telerik UI for ASP.NET Core FileManager provides an inbuilt Search functionality, allowing you to
find the specific file in the currently selected folder.
See Also
Overview of Telerik UI for ASP.NET Core FileManager
Sort in Telerik UI for ASP.NET Core FileManager
Toolbar Commands in Telerik UI for ASP.NET Core FileManager
124
Telerik UI for ASP.NET Core
Sort
The Telerik UI for ASP.NET Core FileManager provides an inbuilt Sort functionality, allowing you to
sort the files and folders in the currently selected folder.
The tool from the toolbar exposes several options to sort by:
Name
Type (extension)
File Size
Date Created
Date Modified
See Also
Overview of Telerik UI for ASP.NET Core FileManager
Views in Telerik UI for ASP.NET Core FileManager
Navigation in Telerik UI for ASP.NET Core FileManager
125
Telerik UI for ASP.NET Core
Toolbar Commands
The Telerik UI for ASP.NET Core FileManager component contains a nested Telerik UI for ASP.NET
Core Toolbar component.
The toolbar has a predefined set of tools which you can show or hide, depending on your
preferences and business scenario. By default, the toolbar contains the following tools:
New Folder button, allowing you to create new folders in the current location.
Upload Button prompting you with a window to upload files.
Sort By dropdown, allowing you to sort by a number of predicates
Views button group to control
View Details switch button to toggle the Preview Pane visibility
Search textbox to filter the content
See Also
Overview of Telerik UI for ASP.NET Core FileManager
ContextMenu in Telerik UI for ASP.NET Core FileManager
Drag and Drop in Telerik UI for ASP.NET Core FileManager
126
Telerik UI for ASP.NET Core
FileManager Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
Globalization in Telerik UI for ASP.NET Core
127
Telerik UI for ASP.NET Core
Internationalization
The internationalization process applies specific culture formats to a web application by providing
options for the parsing and formatting of dates and numbers.
See also
Localization of Messages
Globalization in Telerik UI for ASP.NET Core
128
Telerik UI for ASP.NET Core
Localization
The FileManager provides options for localizing its user interface by utilizing the available
configuration options of its composite components. Refer to the Grid Localizationdocumentation
article.
See Also
RTL Support by the FileManager HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
129
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the FileManager HtmlHelper for ASP.NET
Core.
See Also
Globalization in Telerik UI for ASP.NET Core
130
Telerik UI for ASP.NET Core
FileManager Accessibility
The FileManager is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in UI for ASP.NET Core.
Section 508
The FileManager is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for jQuery.
WCAG 2.1
The FileManager supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1.
See Also
WCAG 2.1 Support by the FileManager HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the FileManager HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the FileManager HtmlHelper for ASP.NET Core
Accessibility Compliance in Telerik UI for ASP.NET Core
131
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the FileManager is always available.
The FileManager entirely relies on the composite components for their keyboard navigation
capabilities (Grid, TreeView, ToolBar, Breadcrumb).
See Also
Accessibility in Telerik UI for ASP.NET Core
132
Telerik UI for ASP.NET Core
The Filter is a unified control for filtering data-bound components that have a data source. The user
interface of the Filter is useful for data-bound components that do not have a built-in UI for filtering
but are required to provide filter options—for example, the ListView, Chart, and Scheduler.
You can add or remove the fields by which the data will be filtered and select the global logic of the
filters (for example, AND or OR) and the filter operator for each field (for example, contains or
equals). You can apply the filtering through a built-in button or through an API call. You can also
select the name by which the fields will be displayed to the user and localizethe filter operators and
messages.
133
Telerik UI for ASP.NET Core
Providing the fields is not required because the Filter can extract them from the data source.
If you do not set the fields in the filter settings, the actual field names, and not the
human-readable label, will be displayed to the user. If you set the fields in the filter settings,
they must match the schema of the data source.
Providing an initial filter expression is not required. This feature is useful for restoring
previous states.
<script type="text/x-kendo-template" id="itemTemplate">
<li>
<strong>#= Name #</strong>, aged #= Age #, is on vacation: #= IsOnLeave #
</li>
</script>
@(Html.Kendo().DataSource<SampleData>()
.Name("dataSource1")
.Ajax(d=>d.Read(r => r.Action("GetPeople", "Filter")))
)
@(Html.Kendo().Filter<SampleData>()
.Name("filter")
.MainLogic(FilterCompositionLogicalOperator.And)
.ExpressionPreview() // Shows a text preview of the filter expression.
.ApplyButton() // Shows the built-in Apply button.
.Fields(f => // Defining the fields is not mandatory. Otherwise, they will be
taken from the data source schema.
// If you define the fields, their names and types must match the data source
definition.
{
f.Add(p=>p.Name).Label("Name");
f.Add(p=>p.Age).Label("Age");
f.Add(p=>p.IsOnLeave).Label("On Vacation");
})
.FilterExpression(f => { // Defining an initial filter expression is not required.
f.Add(p => p.Age).IsGreaterThanOrEqualTo(30);
f.Add(p => p.Name).Contains("Doe");
})
.DataSource("dataSource1")
)
@(Html.Kendo().ListView<SampleData>()
.Name("listView")
.TagName("ul")
.DataSource("dataSource1")
.ClientTemplateId("itemTemplate")
)
<script>
$(document).ready(function () {
// Apply filtering immediately after the helper initialization because an
initial filter is set.
$("#filter").getKendoFilter().applyFilter();
});
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
134
Telerik UI for ASP.NET Core
{
public IActionResult GetPeople([DataSourceRequest]DataSourceRequest request)
{
var people = new List<SampleData>() {
new SampleData() { Name = "Jane Doe", Age = 25, IsOnLeave = false },
new SampleData() { Name = "John Doe", Age = 33, IsOnLeave = true },
new SampleData() { Name = "John Smith", Age = 37, IsOnLeave = true },
new SampleData() { Name = "Nathan Doe", Age = 42, IsOnLeave = false }
};
return Json(people.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleData
{
public int Age { get; set; }
public string Name { get; set; }
public bool IsOnLeave { get; set; }
}
<script>
$(function() {
// The Name() of the Filter is used to get its client-side instance.
var filter = $("#theFilter").data("kendoFilter");
});
</script>
See Also
Basic Usage of the Filter HtmlHelper for ASP.NET Core (Demo)
Filter Client-Side API
Filter Server-Side API
135
Telerik UI for ASP.NET Core
The following example demonstrates how to set the equals and contains filter operators to the
string fields and the greater than and less than filter operators to the numerical fields.
<script type="text/x-kendo-template" id="itemTemplate">
<li>
<strong>#= Name #</strong>, aged #= Age #, is on vacation: #= IsOnLeave #
</li>
</script>
@(Html.Kendo().DataSource<SampleData>()
.Name("dataSource1")
.Ajax(d=>d.Read(r => r.Action("GetPeople", "Filter")))
)
@(Html.Kendo().Filter<SampleData>()
.Name("filter")
.Operators(o => // Define the custom texts for the operator names and the
available operators.
{
o.String(s =>
{
s.Eq("Is Exactly");
s.Contains("Partially Matches");
});
o.Number(n =>
{
n.Gte("Older Than");
n.Lt("Younger Than");
});
})
.MainLogic(FilterCompositionLogicalOperator.And)
.ExpressionPreview() // Shows a text preview of the filter expression.
.ApplyButton() // Shows the built-in Apply button.
.Fields(f => // Defining the fields is not mandatory. Otherwise, they will be
taken from the data source schema.
// If you define the fields, their names and types must match the data source
definition.
{
f.Add(p=>p.Name).Label("Name");
f.Add(p=>p.Age).Label("Age");
f.Add(p=>p.IsOnLeave).Label("On Vacation");
})
.FilterExpression(f => { // Defining an initial filter expression is not required.
f.Add(p => p.Age).IsGreaterThanOrEqualTo(30);
f.Add(p => p.Name).Contains("Doe");
})
.DataSource("dataSource1")
)
@(Html.Kendo().ListView<SampleData>()
.Name("listView")
136
Telerik UI for ASP.NET Core
.TagName("ul")
.DataSource("dataSource1")
.ClientTemplateId("itemTemplate")
)
<script>
$(document).ready(function () {
// Apply filtering immediately after the helper initialization because an
initial filter is set.
$("#filter").getKendoFilter().applyFilter();
});
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
{
public IActionResult GetPeople([DataSourceRequest]DataSourceRequest request)
{
var people = new List<SampleData>() {
new SampleData() { Name = "Jane Doe", Age = 25, IsOnLeave = false },
new SampleData() { Name = "John Doe", Age = 33, IsOnLeave = true },
new SampleData() { Name = "John Smith", Age = 37, IsOnLeave = true },
new SampleData() { Name = "Nathan Doe", Age = 42, IsOnLeave = false }
};
return Json(people.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleData
{
public int Age { get; set; }
public string Name { get; set; }
public bool IsOnLeave { get; set; }
}
See Also
Basic Usage of the Filter HtmlHelper for ASP.NET Core (Demo)
Localization of Messages in the Filter HtmlHelper for ASP.NET Core
Server-Side API
137
Telerik UI for ASP.NET Core
The following example demonstrates how to use the change event to automatically apply filtering
and to maintain an up-to-date state of the Filter. Upon a page reload, the stored settings will be
provided to the Filter configuration and will be applied.
<ol>
<li>Change the filter.</li>
<li>Reload the page: <button type="button"
onclick="reloadPage();">Reload</button></li>
<li>The widget will be initialized with the settings that were stored.</li>
<li>Clear the stored information to start fresh: <button
onclick="clearData();">Clear</button></li>
</ol>
<script type="text/x-kendo-template" id="itemTemplate">
<li>
<strong>#= Name #</strong>, aged #= Age #, is on vacation: #= IsOnLeave #
</li>
</script>
@(Html.Kendo().DataSource<Kendo.Mvc.Examples.Models.SampleData>()
.Name("dataSource1")
.Ajax(d => d.Read(r => r.Action("GetPeople", "Filter")))
)
@(Html.Kendo().Filter<Kendo.Mvc.Examples.Models.SampleData>()
.Name("filter")
.Events(ev => ev.Change("applyAndStoreFilterExpression"))
.MainLogic(FilterCompositionLogicalOperator.And)
.ExpressionPreview()
.Fields(f =>
{
f.Add(p => p.Name).Label("Name");
f.Add(p => p.Age).Label("Age");
f.Add(p => p.IsOnLeave).Label("On Vacation");
})
.DataSource("dataSource1")
)
@(Html.Kendo().ListView<Kendo.Mvc.Examples.Models.SampleData>()
.Name("listView")
.TagName("ul")
.DataSource("dataSource1")
.ClientTemplateId("itemTemplate")
)
138
Telerik UI for ASP.NET Core
<script>
$(document).ready(function () {
if (getInitialExpression()) { // Apply the filter if a stored expression
exists.
var filter = $("#filter").data("kendoFilter");
var opts = filter.getOptions();
opts.expression = getInitialExpression();
filter.setOptions(opts);
$("#filter").data("kendoFilter").applyFilter();
}
});
function applyAndStoreFilterExpression(e) {
e.sender.applyFilter(); // Apply filtering on every change.
localStorage["myInitialFilterExpression"] = JSON.stringify(e.expression); //
Store the filter expression for future use.
}
function getInitialExpression() {
if (localStorage["myInitialFilterExpression"]) {
return JSON.parse(localStorage["myInitialFilterExpression"]);
}
}
function reloadPage() {
window.location.reload();
}
function clearData() {
delete localStorage["myInitialFilterExpression"];
reloadPage();
}
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
{
public IActionResult GetPeople([DataSourceRequest]DataSourceRequest request)
{
var people = new List<SampleData>() {
new SampleData() { Name = "Jane Doe", Age = 25, IsOnLeave = false },
new SampleData() { Name = "John Doe", Age = 33, IsOnLeave = true },
new SampleData() { Name = "John Smith", Age = 37, IsOnLeave = true },
new SampleData() { Name = "Nathan Doe", Age = 42, IsOnLeave = false }
};
return Json(people.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleData
{
public int Age { get; set; }
public string Name { get; set; }
139
Telerik UI for ASP.NET Core
public bool IsOnLeave { get; set; }
}
The following example demonstrates how to obtain the current filter expression and any other
settings and apply them when needed.
<ol>
<li>Change the state of the filter.</li>
<li>Save the state <button onclick="saveState();">Save</button></li>
<li>Change the state of the filter again.</li>
<li>Load the state: <button onclick="loadState();">Load</button></li>
<li>Clear the state: <button onclick="clearState();">Clear</button></li>
</ol>
<script type="text/x-kendo-template" id="itemTemplate">
<li>
<strong>#= Name #</strong>, aged #= Age #, is on vacation: #= IsOnLeave #
</li>
</script>
@(Html.Kendo().DataSource<SampleChartData>()
.Name("dataSource1")
.Ajax(d => d.Read(r => r.Action("GetData", "Filter")))
)
@(Html.Kendo().Filter<SampleChartData>()
.Name("filter")
.MainLogic(FilterCompositionLogicalOperator.And)
.ExpressionPreview()
.ApplyButton()
.Fields(f =>
{
f.Add(p => p.Price).Label("Cost");
f.Add(p => p.Year).Label("Year");
})
.DataSource("dataSource1")
)
@(Html.Kendo().Chart<SampleChartData>()
.Name("chart")
.DataSource("dataSource1")
.Series(series =>
{
series.Column(model => model.Price).CategoryField("Year");
})
)
<script>
function saveState(e) {
localStorage["myFilterSettings"] =
JSON.stringify(getFilter().getOptions().expression);
// You can store and restore all options not just the expression.
}
function loadState() {
140
Telerik UI for ASP.NET Core
if (localStorage["myFilterSettings"]) {
var filter = getFilter();
var opts = filter.getOptions();
opts.expression = JSON.parse(localStorage["myFilterSettings"]);
filter.setOptions(opts);
// If you will restore all options, you need only
filter.setOptions(myOptionsLiteral).
filter.applyFilter(); // Apply the new filter expression.
}
}
function clearState() {
delete localStorage["myFilterSettings"];
}
function getFilter() {
return $("#filter").data("kendoFilter");
}
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
{
public IActionResult GetData([DataSourceRequest]DataSourceRequest request)
{
var data = new List<SampleChartData>() {
new SampleChartData() { Price = 25, Year = 2017 },
new SampleChartData() { Price = 29, Year = 2018 },
new SampleChartData() { Price = 33, Year = 2019 }
};
return Json(data.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleChartData
{
public int Price { get; set; }
public int Year { get; set; }
}
See Also
Basic Usage of the Filter HtmlHelper for ASP.NET Core (Demo)
Persisting the State of the Filter HtmlHelper for ASP.NET Core (Demo)
Server-Side API
141
Telerik UI for ASP.NET Core
Filter Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
The globalization functionality of the Filter is enabled through the localization of its messages.
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
Globalization in Telerik UI for ASP.NET Core
Server-Side API
142
Telerik UI for ASP.NET Core
Localization
The Filter provides options for defining the text of its filter operators (for example, contains,
equals, or greater than) and logic messages (for example, AND and OR).
To localize the messages, set the desired strings in the .Operators() and .Messages() options.
You can also use this feature to select the available filter operators.
<script type="text/x-kendo-template" id="itemTemplate">
<li>
<strong>#= Name #</strong>, aged #= Age #, is on vacation: #= IsOnLeave #
</li>
</script>
@(Html.Kendo().DataSource<SampleData>()
.Name("dataSource1")
.Ajax(d=>d.Read(r => r.Action("GetPeople", "Filter")))
)
@(Html.Kendo().Filter<SampleData>()
.Name("filter")
.Messages(m => // Custom texts for localizable UI.
{
m.And("AND"); // The AND main logic text.
m.Or("OR"); // The OR main logic text.
m.Apply("Set Filter"); // The APPLY button text.
})
.Operators(o => // Define the custom texts for the operator names and select the
available operators.
{
o.String(s =>
{
s.Eq("Is Exactly");
s.Contains("Partially Matches");
});
o.Number(n =>
{
n.Gte("Older Than");
n.Lt("Younger Than");
});
})
.MainLogic(FilterCompositionLogicalOperator.And)
.ExpressionPreview() // Shows a text preview of the filter expression.
.ApplyButton() // Shows the built-in Apply button.
.Fields(f => // Defining the fields is not mandatory. Otherwise, they will be
taken from the data source schema.
// If you define the fields, their names and types must match the data source
definition.
{
f.Add(p=>p.Name).Label("Name");
f.Add(p=>p.Age).Label("Age");
f.Add(p=>p.IsOnLeave).Label("On Vacation");
})
.FilterExpression(f => { // Defining an initial filter expression is not required.
f.Add(p => p.Age).IsGreaterThanOrEqualTo(30);
143
Telerik UI for ASP.NET Core
f.Add(p => p.Name).Contains("Doe");
})
.DataSource("dataSource1")
)
@(Html.Kendo().ListView<SampleData>()
.Name("listView")
.TagName("ul")
.DataSource("dataSource1")
.ClientTemplateId("itemTemplate")
)
<script>
$(document).ready(function () {
// Apply filtering immediately after the helper initialization because an
initial filter is set.
$("#filter").getKendoFilter().applyFilter();
});
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
{
public IActionResult GetPeople([DataSourceRequest]DataSourceRequest request)
{
var people = new List<SampleData>() {
new SampleData() { Name = "Jane Doe", Age = 25, IsOnLeave = false },
new SampleData() { Name = "John Doe", Age = 33, IsOnLeave = true },
new SampleData() { Name = "John Smith", Age = 37, IsOnLeave = true },
new SampleData() { Name = "Nathan Doe", Age = 42, IsOnLeave = false }
};
return Json(people.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleData
{
public int Age { get; set; }
public string Name { get; set; }
public bool IsOnLeave { get; set; }
}
See Also
Basic Usage of the Filter HtmlHelper for ASP.NET Core (Demo)
Server-Side API
144
Telerik UI for ASP.NET Core
The Grid is a powerful control for displaying data in a tabular format. It provides options for
executing data operations, such as paging, sorting, filtering, grouping, and editing, which determine
the way the data is presented and manipulated. The Grid supports data binding to local and remote
sets of data by using the Kendo UI for jQuery DataSource component.
Advance Reading
Because of the numerous functionalities it supports, the Grid is the most complex of the Telerik UI
HTML Helpers. To gain greater confidence before you start working with it, make sure you get
familiar with the following concepts:
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.Customer>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.ContactName).Width(140);
columns.Bound(c => c.ContactTitle).Width(190);
columns.Bound(c => c.CompanyName);
columns.Bound(c => c.Country).Width(110);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Customers_Read", "Grid"))
)
)
namespace Kendo.Mvc.Examples.Controllers
{
public partial class GridController : BaseController
{
145
Telerik UI for ASP.NET Core
[Demo]
public IActionResult Index()
{
return View();
}
public IActionResult Customers_Read([DataSourceRequest] DataSourceRequest
request)
{
return Json(GetCustomers().ToDataSourceResult(request));
}
private static IEnumerable<CustomerViewModel> GetCustomers()
{
using (var northwind = new SampleEntitiesDataContext())
{
return northwind.Customers.Select(customer => new CustomerViewModel
{
CustomerID = customer.CustomerID,
CompanyName = customer.CompanyName,
ContactName = customer.ContactName,
ContactTitle = customer.ContactTitle,
Address = customer.Address,
City = customer.City,
Region = customer.Region,
PostalCode = customer.PostalCode,
Country = customer.Country,
Phone = customer.Phone,
Fax = customer.Fax,
Bool = customer.Bool
}).ToList();
}
}
}
}
146
Telerik UI for ASP.NET Core
More settings
Scroll modes
Selection
Rendering and dimensions
Responsive Grid
Performance tips
Globalization
Accessibility
For more information on implementing specific scenarios, refer to the Knowledge Basesection.
<script>
$(function() {
// The Name() of the Grid is used to get its client-side instance.
var grid = $("#grid").data("kendoGrid");
});
</script>
See Also
Basic Usage of the Grid HtmlHelper for ASP.NET Core (Demo)
Using the API of the Grid HtmlHelper for ASP.NET Core (Demo)
Knowledge Base Section
Server-Side API
147
Telerik UI for ASP.NET Core
See Also
Remote Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Local Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
WebAPI Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
OData Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
SignalR Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Custom Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
148
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Grid HtmlHelper extension for Ajax binding.
When configured for Ajax binding, the Grid for ASP.NET Core makes Ajax requests when doing
paging, sorting, filtering, grouping, or when saving data. For a runnable example, refer to the demo on
Ajax binding of the Grid.
The Grid retrieves only the data (in JSON format) representing the current page. As a result,
only the Grid is updated.
All Grid templates (column, detail) are executed client-side. They follow the Kendo UI for
jQuery templatedefinition rules and may contain embedded JavaScript code.
To configure the Grid for ASP.NET Core to do Ajax binding to the Products table of the Northwind
database:
1. Create a new ASP.NET Core web application. Follow the steps from the introductory articleto
add Telerik UI for ASP.NET Core to the application.
2. Install the EntityFrameworkCore NuGet package.
3. Install Microsoft.EntityFrameworkCore.SqlServer package.
4. Run the following command in the Package Management Console. It will generate models
from the tables in a database called 'Sample'. For more information on scaffolding a model
from an existing database refer to this Microsoft article.
Scaffold-DbContext "Server=.\SQLSERVER;Database=Sample;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
5. Open the HomeController.cs and add a new action method which will return the Products
as JSON. The Grid makes Ajax requests to this action.
public IActionResult Customers_Read()
{
}
public IActionResult Customers_Read([DataSourceRequest]DataSourceRequest
request)
{
}
149
Telerik UI for ASP.NET Core
public ActionResult Customers_Read([DataSourceRequest]DataSourceRequest request)
{
using (var northwind = new SampleContext())
{
IEnumerable<Customers> customers = northwind.Customers;
DataSourceResult result = customers.ToDataSourceResult(request);
}
}
8. Return the DataSourceResult as JSON. Configure the Kendo UI Grid for Ajax binding.
public ActionResult Customers_Read([DataSourceRequest]DataSourceRequest request)
{
using (var northwind = new SampleContext())
{
IEnumerable<Customers> customers = northwind.Customers;
DataSourceResult result = customers.ToDataSourceResult(request);
return Json(result);
}
}
9. In the view, configure the Grid to use the action method created in the previous steps.
@(Html.Kendo().Grid<KendoGridAjaxBinding.Models.Customers>()
.Name("grid")
.DataSource(dataSource => dataSource //Configure the Grid data source.
.Ajax() //Specify that Ajax binding is used.
.Read(read => read.Action("Customers_Read", "Home")) // Set the action
method which will return the data in JSON format.
)
.Columns(columns =>
{
//Create a column bound to the ProductID property.
columns.Bound(product => product.ProductID);
//Create a column bound to the ProductName property.
columns.Bound(product => product.ProductName);
//Create a column bound to the UnitsInStock property.
columns.Bound(product => product.UnitsInStock);
})
.Pageable() // Enable paging
.Sortable() // Enable sorting
)
150
Telerik UI for ASP.NET Core
See Also
Custom Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Knowledge Base Section
Server-Side API
151
Telerik UI for ASP.NET Core
Local Binding
When configured for local binding, the Grid for ASP.NET Core will serialize the data as part of its data
source and will perform all data operations, such as paging, sorting, filtering, grouping, and
aggregating, on the client.
For a runnable example, refer to the demo on local binding of the Grid.
public class OrderViewModel
{
public int OrderID
{
get;
set;
}
public string ShipCountry
{
get;
set;
}
}
2. Open the HomeController.cs and return an IEnumerable of the model type with the View.
This is the View() which holds the Grid definition.
public IActionResult Index()
{
// Returns a collection of OrderViewModels.
var model = orderService.Read();
/* For a quick test, you can mock the data, and copy and paste this
snippet.
var model = Enumerable.Range(1, 20).Select(i => new OrderViewModel
{
OrderID = i,
ShipCountry = i % 2 == 0 ? "ShipCountry 1" : "ShipCountry 2"
});
*/
return View(model);
}
3. In the Index.cshtml view, configure the Grid to accept the model in its constructor and set
ServerOperations(false).
152
Telerik UI for ASP.NET Core
@model IEnumerable<AspNetCoreGrid.Models.OrderViewModel>
@(Html.Kendo().Grid(Model)
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(2)
.ServerOperation(false)
)
.ToolBar(tools =>
{
tools.Pdf().Text("Custom PDF button text");
tools.Excel().Text("Custom Excel button text");
})
.Pageable()
.Sortable()
.Groupable()
.Columns(columns =>
{
columns.Bound(f => f.OrderID);
columns.Bound(f => f.ShipCountry);
})
)
See Also
Custom Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Knowledge Base Section
Server-Side API
153
Telerik UI for ASP.NET Core
SignalR Binding
As of the ASP.NET Core R2 2018 release, the suite provides SignalR support for its components.
Demonstrates a sample implementation of a Grid which uses SignalR. The service that is
used is available in this GitHub repository.
Uses Long Polling because WebSocketswork only in some scenariosand server-sent eventsare
not supported by IE/Edge.
$(document).ready(function() {
var hubUrl = "http://domain/signalr-service/products";
var hub = new signalR.HubConnectionBuilder()
.withUrl(hubUrl, {
transport: signalR.HttpTransportType.LongPolling
})
.build();
var hubStart = hub.start();
});
function onPush(e) {
var notification = $("#notification").data("kendoNotification");
notification.success(e.type);
}
@(Html.Kendo().Notification()
.Name("notification")
.Width("100%")
.Position(position => position
.Top(50)
.Left(50))
)
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice);
columns.Bound(p => p.CreatedAt);
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(150);
154
Telerik UI for ASP.NET Core
})
.HtmlAttributes(new { style = "height: 550px;margin-bottom:20px;" })
.ToolBar(toolbar =>
{
toolbar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.SignalR()
.AutoSync(true)
.Events(events => events.Push("onPush"))
.Transport(tr => tr
.Promise("hubStart")
.Hub("hub")
.Client(c => c
.Read("read")
.Create("create")
.Update("update")
.Destroy("destroy"))
.Server(s => s
.Read("read")
.Create("create")
.Update("update")
.Destroy("destroy")))
.Schema(schema => schema
.Model(model =>
{
model.Id("ID");
model.Field("ID", typeof(string)).Editable(false);
model.Field("ProductName", typeof(string));
model.Field("CreatedAt", typeof(DateTime));
model.Field("UnitPrice", typeof(int));
}
)
)
)
)
See Also
SignalR Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Official Microsoft Documentation on Getting Started with ASP.NET Core SignalR
Server-Side API
155
Telerik UI for ASP.NET Core
Custom Binding
The Telerik UI Grid for ASP.NET Core enables you to bypass the built-in data processing and to
handle operations such paging, sorting, filtering, and grouping yourself.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Order> orders = new NorthwindEntities().Orders;
}
2. Handle the appropriate data operations and calculate the total number of records.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Order> orders = new NorthwindEntities().Orders;
// Apply sorting.
if (request.Sorts.Any())
{
foreach (SortDescriptor sortDescriptor in request.Sorts)
{
if (sortDescriptor.SortDirection == ListSortDirection.Ascending)
{
switch (sortDescriptor.Member)
{
case "OrderID":
orders= orders.OrderBy(order => order.OrderID);
break;
case "ShipAddress":
orders= orders.OrderBy(order => order.ShipAddress);
break;
}
}
else
{
switch (sortDescriptor.Member)
{
case "OrderID":
orders= orders.OrderByDescending(order => order.OrderID);
break;
case "ShipAddress":
orders= orders.OrderByDescending(order => order.ShipAddress);
156
Telerik UI for ASP.NET Core
break;
}
}
}
}
else
{
// If cannot page unsorted data.
orders = orders.OrderBy(o => o.OrderID);
}
var total = orders.Count();
// Apply paging.
if (request.Page > 0) {
orders = orders.Skip((request.Page - 1) * request.PageSize);
}
orders = orders.Take(request.PageSize);
}
3. Create a new instance of DataSourceResult. Set the Data and Total properties to the
processed data and to the total number of records.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
// Get the data (code omitted).
IQueryable<Order> orders = new NorthwindEntities().Orders;
// Apply sorting (code omitted).
// Apply paging (code omitted).
// Initialize the DataSourceResult.
var result = new DataSourceResult()
{
Data = orders, // Process data (paging and sorting applied).
Total = total // The total number of records.
};
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
// Get the data (code omitted).
IQueryable<Order> orders = new NorthwindEntities().Orders;
// Apply sorting (code omitted).
// Apply paging (code omitted).
// Initialize the DataSourceResult (code omitted).
var result = new DataSourceResult()
{
Data = orders, // Process data (paging and sorting applied)
Total = total // Total number of records
};
// Return the result as JSON.
return Json(result);
}
157
Telerik UI for ASP.NET Core
@(Html.Kendo().Grid<KendoGridCustomAjaxBinding.Models.Order>()
.Name("Grid")
.EnableCustomBinding(true)
.Columns(columns => {
columns.Bound(o => o.OrderID);
columns.Bound(o => o.ShipAddress);
})
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Read("Orders_Read", "Home")
)
)
See Also
Custom Ajax Binding by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
158
Telerik UI for ASP.NET Core
Editing Overview
Editing is a basic functionality of the Telerik UI Grid HtmlHelper for ASP.NET Core which allows you
to manipulate the way its data is presented.
Inline editing
Popup editing
Incell editing
Custom editors and validation
See Also
Incell Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Inline Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Popup Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Custom Editor by the Grid HtmlHelper for ASP.NET Core (Demo)
Custom Validation Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
159
Telerik UI for ASP.NET Core
Inline Editing
You can define commands and set the edit mode to configure the Telerik UI Grid for ASP.NET Core
for inline editing.
For runnable examples, refer to the demos on implementing the editing approaches in the Grid .
public class ProductViewModel
{
public int ProductID { get; set; }
// The ProductName property is required.
[Required]
public string ProductName { get; set; }
// Use the Integer editor template for the UnitsInStock property.
[UIHint("Integer")]
public short? UnitsInStock { get; set; }
}
2. Open HomeController.cs and add a new action method which will return the Products as
JSON. The Grid will make Ajax requests to this action.
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
// ToDataSourceResult works with IEnumerable and IQueryable.
using (var northwind = new NorthwindEntities())
{
IQueryable<Product> products = northwind.Products;
DataSourceResult result = products.ToDataSourceResult(request);
return Json(result);
}
}
3. Add a new action method to HomeController.cs. It will be responsible for saving the new
data items. Name the method Products_Create.
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest
request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
160
Telerik UI for ASP.NET Core
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity.
northwind.Products.Add(entity);
// Insert the entity in the database.
northwind.SaveChanges();
// Get the ProductID generated by the database.
product.ProductID = entity.ProductID;
}
}
// Return the inserted product. The Grid needs the generated ProductID.
Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
4. Add a new action method to HomeController.cs. It will be responsible for saving the
updated data items. Name the method Products_Update.
public ActionResult Products_Update([DataSourceRequest]DataSourceRequest
request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Attach the entity.
northwind.Products.Attach(entity);
// Change its state to Modified so Entity Framework can update the
existing product instead of creating a new one.
northwind.Entry(entity).State = EntityState.Modified;
// Or use ObjectStateManager if using a previous version of Entity
Framework.
// northwind.ObjectStateManager.ChangeObjectState(entity,
EntityState.Modified);
// Update the entity in the database.
northwind.SaveChanges();
}
}
// Return the updated product. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
5. Add a new action method to HomeController.cs. It will be responsible for saving the
161
Telerik UI for ASP.NET Core
public ActionResult Products_Destroy([DataSourceRequest]DataSourceRequest
request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Attach the entity.
northwind.Products.Attach(entity);
// Delete the entity.
northwind.Products.Remove(entity);
// Or use DeleteObject if using a previous versoin of Entity Framework.
// northwind.Products.DeleteObject(entity);
// Delete the entity in the database.
northwind.SaveChanges();
}
}
// Return the removed product. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
6. In the view, configure the Grid to use the action methods that were created in the previous
steps. The Create, Update, and Destroy action methods have to return a collection with
the modified or deleted records which will enable the DataSource to apply the changes
accordingly. The Create method has to return a collection of the created records with the
assigned ID field.
@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.ProductID).Width(100);
columns.Bound(product => product.ProductName);
columns.Bound(product => product.UnitsInStock).Width(250);
columns.Command(commands =>
{
commands.Edit(); // The "edit" command will edit and update data items.
commands.Destroy(); // The "destroy" command removes data items.
}).Title("Commands").Width(200);
})
.ToolBar(toolbar => toolbar.Create()) // The "create" command adds new
data items.
.Editable(editable => editable.Mode(GridEditMode.InLine)) // Use the
inline edit mode.
.DataSource(dataSource =>
dataSource.Ajax()
.Model(model =>
{
162
Telerik UI for ASP.NET Core
model.Id(product => product.ProductID); // Specify the property which is
the unique identifier of the model.
model.Field(product => product.ProductID).Editable(false); // Make the
ProductID property not editable.
})
.Create(create => create.Action("Products_Create", "Home")) // Action
invoked when the user saves a new data item.
.Read(read => read.Action("Products_Read", "Home")) // Action invoked
when the Grid needs data.
.Update(update => update.Action("Products_Update", "Home")) // Action
invoked when the user saves an updated data item.
.Destroy(destroy => destroy.Action("Products_Destroy", "Home")) // Action
invoked when the user removes a data item.
)
.Pageable()
)
public ActionResult Products_Update([DataSourceRequest]DataSourceRequest
request, ProductViewModel product)
{
if (product.ProductName.Length < 3)
{
ModelState.AddModelError("ProductName", "ProductName should be at least
three characters long.");
}
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Attach the entity.
northwind.Products.Attach(entity);
// Change its state to Modified so Entity Framework can update the
existing product instead of creating a new one.
northwind.Entry(entity).State = EntityState.Modified;
// Or use ObjectStateManager if using a previous version of Entity
Framework.
// northwind.ObjectStateManager.ChangeObjectState(entity,
EntityState.Modified);
163
Telerik UI for ASP.NET Core
// Update the entity in the database.
northwind.SaveChanges();
}
}
// Return the updated product. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
@(Html.Kendo().Grid<KendoGridAjaxEditing.Models.ProductViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.ProductID).Width(100);
columns.Bound(product => product.ProductName);
columns.Bound(product => product.UnitsInStock).Width(250);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("Commands").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource =>
dataSource.Ajax()
.Events(events => events.Error("grid_error")) // Handle the "error"
event.
.Model(model =>
{
model.Id(product => product.ProductID);
model.Field(product => product.ProductID).Editable(false);
})
.Create(create => create.Action("Products_Create", "Home"))
.Read(read => read.Action("Products_Read", "Home"))
.Update(update => update.Action("Products_Update", "Home"))
.Destroy(destroy => destroy.Action("Products_Destroy", "Home"))
)
.Pageable()
)
<script>
function grid_error(e) {
if (e.errors) {
var message = "There are some errors:\n";
// Create a message containing all errors.
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
// Display the message.
alert(message);
// Cancel the changes.
164
Telerik UI for ASP.NET Core
var grid = $("#grid").data("kendoGrid");
grid.cancelChanges();
}
}
</script>
See Also
Editing Approaches by the Grid HtmlHelper for ASP.NET Core (Demos)
Server-Side API
165
Telerik UI for ASP.NET Core
Batch Editing
The Telerik UI Grid HtmlHelper for ASP.NET Core enables you to implement cell editing and make
and save batch updates.
For a runnable example, refer to the demo on batch editing of the Grid.
1. Add a new class to the ~/Models folder. The following example uses the
ProductViewModel name.
public class ProductViewModel
{
public int ProductID { get; set; }
// The ProductName property is required.
[Required]
public string ProductName { get; set; }
// Use the Integer editor template for the UnitsInStock property.
[UIHint("Integer")]
public short? UnitsInStock { get; set; }
}
2. Open HomeController.cs and add a new action method which will return the Products as
JSON. The Grid will make Ajax requests to this action.
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
// ToDataSourceResult works with IEnumerable and IQueryable.
using (var northwind = new NorthwindEntities())
{
IQueryable<Product> products = northwind.Products;
DataSourceResult result = products.ToDataSourceResult(request);
return Json(result);
}
}
3. Add a new action method to HomeController.cs. It will be responsible for saving the new
data items. Name the method Products_Create.
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest
request, [Bind(Prefix="models")]IEnumerable<ProductViewModel> products)
{
// Will keep the inserted entities here. Used to return the result later.
var entities = new List<Product>();
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
foreach (var product in products)
{
// Create a new Product entity and set its properties from the posted
166
Telerik UI for ASP.NET Core
ProductViewModel.
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity.
northwind.Products.Add(entity);
// Store the entity for later use.
entities.Add(entity);
}
// Insert the entities in the database.
northwind.SaveChanges();
}
}
// Return the inserted entities. The Grid needs the generated ProductID.
Also return any validation errors.
return Json(entities.ToDataSourceResult(request, ModelState, product =>
new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
}));
}
4. Add a new action method to HomeController.cs. It will be responsible for saving the
updated data items. Name the method Products_Update.
public ActionResult Products_Update([DataSourceRequest]DataSourceRequest
request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
{
// Will keep the updated entities here. Used to return the result later.
var entities = new List<Product>();
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
foreach (var product in products)
{
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Store the entity for later use.
entities.Add(entity);
// Attach the entity.
northwind.Products.Attach(entity);
// Change its state to Modified so Entity Framework can update the
existing product instead of creating a new one.
northwind.Entry(entity).State = EntityState.Modified;
// Or use ObjectStateManager if using a previous version of Entity
Framework.
// northwind.ObjectStateManager.ChangeObjectState(entity,
EntityState.Modified);
167
Telerik UI for ASP.NET Core
}
// Update the entities in the database.
northwind.SaveChanges();
}
}
// Return the updated entities. Also return any validation errors.
return Json(entities.ToDataSourceResult(request, ModelState, product =>
new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
}));
}
5. Add a new action method to HomeController.cs. It will be responsible for saving the
deleted data items. Name the method Products_Destroy.
public ActionResult Products_Destroy([DataSourceRequest]DataSourceRequest
request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
{
// Will keep the destroyed entities here. Used to return the result
later.
var entities = new List<Product>();
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
foreach (var product in products)
{
// Create a new Product entity and set its properties from the posted
ProductViewModel.
var entity = new Product
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Store the entity for later use.
entities.Add(entity);
// Attach the entity.
northwind.Products.Attach(entity);
// Delete the entity.
northwind.Products.Remove(entity);
// Or use DeleteObject if using a previous version of Entity Framework.
// northwind.Products.DeleteObject(entity);
}
// Delete the entity in the database.
northwind.SaveChanges();
}
}
// Return the destroyed entities. Also return any validation errors.
return Json(entities.ToDataSourceResult(request, ModelState, product =>
new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
}));
168
Telerik UI for ASP.NET Core
}
6. In the view, configure the Grid to use the action methods that were created in the previous
steps. The Create, Update, and Destroy action methods have to return a collection with
the modified or deleted records which will enable the DataSource to apply the changes
accordingly. The Create method has to return a collection of the created records with the
assigned ID field.
@(Html.Kendo().Grid<KendoGridBatchEditing.Models.ProductViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.ProductID).Width(100);
columns.Bound(product => product.ProductName);
columns.Bound(product => product.UnitsInStock).Width(250);
columns.Command(commands =>
{
commands.Destroy(); // The "destroy" command removes data items.
}).Title("Commands").Width(200);
})
.ToolBar(toolbar =>
{
toolbar.Create(); // The "create" command adds new data items.
toolbar.Save(); // The "save" command saves the changed data items.
})
.Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell
editing mode.
.DataSource(dataSource =>
dataSource.Ajax()
.Batch(true) // Enable batch updates.
.Model(model =>
{
model.Id(product => product.ProductID); // Specify the property which is
the unique identifier of the model.
model.Field(product => product.ProductID).Editable(false); // Make the
ProductID property not editable.
})
.Create(create => create.Action("Products_Create", "Home")) // Action
method invoked when the user saves a new data item.
.Read(read => read.Action("Products_Read", "Home")) // Action method
invoked when the Grid needs data.
.Update(update => update.Action("Products_Update", "Home")) // Action
method invoked when the user saves an updated data item.
.Destroy(destroy => destroy.Action("Products_Destroy", "Home")) // Action
method invoked when the user removes a data item.
)
.Pageable()
)
See Also
Batch Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
169
Telerik UI for ASP.NET Core
Custom Editing
The Grid enables you to implement custom column editors and to specify validation rules that apply
while the user edits the data.
The following example demonstrates how to use the NumericTextBox as a custom editor in the Grid.
The UI for ASP.NET Core Visual Studio Templates come with EditorTemplates which are located in
\Views\Shared\EditorTemplates. To utilize the provided Number editor in the example on the
popup edit mode of the Grid, decorate the Model field with a [UIHint("Number")] attribute.
public class OrderViewModel
{
public int OrderID { get; set; }
public string ShipCountry { get; set; }
[UIHint("Number")]
public int? Freight { get; set; }
}
@model int?
@(Html.Kendo().NumericTextBoxFor(m => m)
.HtmlAttributes(new { style = "width:100%" })
)
See Also
Custom Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
Custom Validator Editing by the Grid HtmlHelper for ASP.NET Core (Demo)
170
Telerik UI for ASP.NET Core
Filtering
By default, the filtering functionality of the Telerik UI Grid for ASP.NET Core is disabled.
Getting Started
To control filtering in the Grid, use the Filterable property.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("Grid")
.Filterable() // Enable the Menu filter mode.
...
Each Filterable configuration of the columns allows the setting of a custom DataSource.
...
columns.Bound(e => e.LastName).Width(220).Filterable(ftb => ftb.Multi(true)
.DataSource(ds => ds.Read(r => r.Action("Unique", "Grid").Data("{ field:
'LastName' }")))
);
.ShowIndexes(true))
Filter Modes
The Grid supports the following filter modes:
To set the desired filter mode, use the Filterable->Mode property. You can enable checkbox list
filtering in the filter menu of the Grid HtmlHelper by specifying the Multi(true) setting for the
relevant Grid columns.
...
columns.Bound(p => p.UnitsInStock).Width(140).Filterable(ftb =>
ftb.Multi(true).CheckAll(true));
See Also
Filter Rows by the Grid HtmlHelper for ASP.NET Core (Demo)
Filter Checkboxes by the Grid HtmlHelper for ASP.NET Core (Demo)
Customizing the Filter Menu by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
171
Telerik UI for ASP.NET Core
Grouping
By default, the grouping functionality of the Telerik UI Grid for ASP.NET Core is disabled.
For a runnable example, refer to the demo on using aggregates in the Grid.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.CustomerViewModel>()
.Name("grid")
.Groupable()
...
You can also render groups by setting group expressions in the DataSource of the Grid even without
enabling Groupable.
.Name("Grid")
.DataSource(dataSource => dataSource
.Ajax()
.Group(groups => groups.Add(p => p.UnitsInStock))
See Also
Grouping with Aggregates by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
172
Telerik UI for ASP.NET Core
Aggregates
The Grid enables you to display aggregated number results when the user groups its data.
See Also
Grouping with Aggregates by the Grid (Demo)
Group Templates
173
Telerik UI for ASP.NET Core
Paging
By default, the paging functionality of the Telerik UI Grid for ASP.NET Core is disabled.
To control the paging in the Grid, use the Pageable option. Additionally, you have to specify the
number of records to display on each page by setting the PageSize on the DataSource.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("Grid")
...
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
...
)
)
Try to do paging operations on the server to avoid including too much data in the HTML which might
slow down page performance. To accomplish this, keep the ServerOperation of the DataSource to
true (the default value).
You can change the available page sizes from which the user can choose with an array with integer
values that are set to the PageSizes property.
.Pageable(p=> {
p.PageSizes(new[] { 5, 10, 30 });
})
Use as small page sizes as possible, because rendering too many records causes performance
issues especially when the Grid renders many columns or complex templates for its cells.
See Also
Paging by the Grid HtmlHelper for ASP.NET Core (Demo)
Setting the Pager Visibility in the Grid HtmlHelper for ASP.NET Core
Server-Side API
174
Telerik UI for ASP.NET Core
Sorting
By default, the sorting functionality of the Telerik UI Grid for ASP.NET Core is disabled.
Getting Started
To control the sorting in the Grid, use the Sortable option.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("Grid")
.Sortable()
...
Sort Modes
The Grid supports single and multiple columns sort modes which can be set through its SortMode
property. You can also specify if the columns can be unsorted by setting the AllowUnsort property
to true or false. For a runnable example, refer to the demo on sorting in the Grid.
With multi-column sorting you can also configure the Grid to display the sort indexes in the header
by setting the ShowIndexes property to true.
.Sortable(sortable => sortable
.AllowUnsort(true)
.SortMode(GridSortMode.MultipleColumn)
.ShowIndexes(true))
See Also
Sorting by the Grid HtmlHelper for ASP.NET Core (Demo)
Knowledge Base Section
Server-Side API
175
Telerik UI for ASP.NET Core
Selection
By default, the selection functionality of the Telerik UI Grid for ASP.NET Core is disabled.
Getting Started
To control the selection in the Grid, use the Selectable property.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("rowSelection")
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
...
Select Modes
The Grid supports the following select modes:
You can set the select mode to Multiple or Single. Additionally, the Grid provides the Row and
Cell select types which allow multiple or single selection of rows or cells.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("cellSelection")
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple)
.Type(GridSelectionType.Cell))
...
.PersistSelection(true)
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.OrderID))
See Also
176
Telerik UI for ASP.NET Core
177
Telerik UI for ASP.NET Core
Search Panel
Out of the box, the Grid enables the users to search through its data by using the search panel.
Under the hood, the search panel uses filtering to show only the relevant records in the Grid.
Getting Started
To enable the search panel functionality, include the Search option to the toolbar configuration.
When the server operations are enabled, you can search only by using string fields. Using the
Contains filter operation is available only for string types.
@(Html.Kendo().Grid<CustomerViewModel>()
.Name("Grid")
.ToolBar(t => t.Search()) // Enable the Search panel.
...
You can also customize which fields to search through the data when a value is entered in the
search input.
...
.Search(s=> { s.Field(c => c.ContactName); })
Known Limitations
When filtering is enabled in the filter textboxes for all Grid columns will be populated with the value
entered in the search textbox.
See Also
Server-Side API
Knowledge Base Section
178
Telerik UI for ASP.NET Core
State Persistence
The Grid enables you to save the custom settings of the user and restore them after the user logs
back at some future moment.
To persist the settings that were previously applied to its structure, use the getOptions() and
setOptions() methods of the Grid. These methods allow you to serialize the current state of the
Grid if needed and recover that state later. For a runnable example, refer to the demo on persisting the
state of the Grid.
See Also
Persisting the State of the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
179
Telerik UI for ASP.NET Core
Column Widths
To set the widths of the Grid columns, use their Width() method.
By default, scrolling is enabled for the Grid in Kendo UI for jQuery, UI for JSP, and UI for PHP.
When scrolling is enabled:
The table-layout style is set to fixed and all columns without a defined width appear
equally wide.
When the horizontal space is not enough, columns without a defined width shrink to a
zero width.
Regardless of the cell content, the defined column widths are obeyed.
If the content of a cell cannot fit, the Grid will either wrap or clip it.
During the resizing of columns, only the resized column and the tablewill change its
widths.
When a column is resized or hidden, the Grid applies a pixel width to its table elements.
This behavior helps maintain the widths of all remaining columns except for the column
that is currently resized or hidden.
When all columns have pixel widths and their sum exceeds the width of the Grid, a
horizontal scrollbar appears.
When all columns have pixel widths and their sum is less than the width of the Grid, the
column widths are ignored and the browser expands all columns.
By default, scrolling is disabled for the Grid in UI for ASP.NET MVC and UI for ASP.NET Core.
When scrolling is disabled:
The table-layout style is set to auto. If not explicitly defined, the column widths are
determined by the browser and by the cell content, which is the default behavior of HTML
tables.
The browser will try to obey all column widths that are set but might adjust the widths of
some columns depending on their content.
#GridID > table // A header and data table.
{
table-layout: fixed;
}
180
Telerik UI for ASP.NET Core
See Also
Knowledge Base Section
Server-Side API
181
Telerik UI for ASP.NET Core
Locked Columns
Locked (frozen) columns enable you to display specific columns at all times while the user scrolls
the Grid horizontally.
For a runnable example, refer to the demo on implementing locked columns in the Grid.
For the feature to work properly, the following configuration settings has to be provided. They ensure
that at least one non-locked column is always visible and that it is possible to scroll the non-locked
columns horizontally. If the horizontal space intended for it is not enough, the horizontal scrollbar
does not appear.
Enable scrolling.
Lock at least one column initially.
Define the height of the Grid.
Set explicit pixel widths to all columns to allow the Grid to adjust the layout of the frozen and
non-frozen table parts.
Make sure that the total width of all locked columns is equal to or less than the width of the
Grid minus three times the width of the scrollbar.
Make sure that the Grid is not initialized inside a hidden container.
The client-side API of the Grid lockColumn()and unlockColumn()methods allow you to lock
and unlock columns on the fly. However, this is possible only if at least one column is initially
locked during initialization. The HTML output and script behavior of the Grid are different
when you apply frozen columns. That is why the widget cannot switch between frozen and
unfrozen mode after initialization.
The locked columns can be positioned only at the left side of the Grid. Positioning them on
the right side is not supported.
The row template and detail features are not supported in combination with locked columns.
If you use multi-column headers, you can lock a column at the topmost level only.
Locked columns cannot be scrolled on touch because they are wrapped in a container with an
overflow:hidden style. To work around this limitation on desktop devices, use the mousewheel
event. However, no workaround exists for touch devices.
Locked columns rely on synchronizing the row height of the frozen and non-frozen parts of the Grid.
Some browsers, such as Internet Explorer 9 and Firefox, require a line-height style set in pixels.
Otherwise, the synchronization might not work properly because of sub-pixel issues.
div.k-grid td
{
line-height: 18px;
}
When you implement custom code and rely on selectors or target the Grid table, the Grid creates
separate tables for its locked and scrollable sections. The locked columns are inside a
182
Telerik UI for ASP.NET Core
See Also
Implementing Locked Columns in the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
183
Telerik UI for ASP.NET Core
Multi-Column Headers
The multicolumn headers of the Grid represent a tree-like structure where the user can group one or
more columns together by a common header.
For a runnable example, refer to the demo on implementing multi-column headers in the Grid .
That common header in turn can be a child of another upper MultiColumn header which can also
span both columns and other headers.
.Columns(columns =>
{
columns.Group(colGroup =>
{
colGroup.Title("Ship Information");
colGroup.Columns(cols =>
{
cols.Bound(f => f.OrderID).Width(200);
cols.Bound(f => f.ShipCountry).Width(200);
});
});
})
See Also
Implementing Multi-Column Headers in the Grid (Demo)
Server-Side API
184
Telerik UI for ASP.NET Core
Resizing of Columns
The resizing behavior of the Grid columns depends on whether scrolling is enabled or disabled.
For a runnable example, refer to the demo on resizing columns in the Grid.
When scrolling is disabled and a Grid column is resized, other columns change widths too, so that
the sum of all column widths remains constant. If both the columns and the Grid <div> already have
their minimum possible widths applied, then the resizing of the columns stops working. In such
scenarios, use either of the following approaches:
When scrolling is enabled and a column is resized, all other columns maintain their widths. When
column resizing is applied, the following outcomes with regard to the sum of all column widths are
possible:
If the sum of all column widths is greater than the width of the Grid, a horizontal scrollbar
appears.
If the sum of all column widths is equal to the width of the Grid, no horizontal scrollbar
appears.
If the sum of all column widths is less than the width of the Grid, an empty space after the
last column appears.
By design, the last column of the Grid has no right border, so that no double border appears at the
right end of the Grid if the Grid table width matches the Grid width. If needed, you can apply a right
border with the CSS code from the following example. The color value of the #ccc border has to
match the color of the cell border from the Kendo UI theme. To obtain this, check the styles of the
table cell by using a DOM inspector.
.k-grid-header-wrap > table,
.k-grid-content > table {
border-right: 1px solid #ccc;
}
See Also
Column Resizing by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
185
Telerik UI for ASP.NET Core
Reordering of Columns
The Grid provides options for reordering its columns.
To enable the user to reorder the columns of the Grid by dragging, set the
Reorderable.Columns() method to true. For a runnable example, refer to the demo on
implementing column reordering in the Grid.
.Reorderable(reorderable => reorderable.Columns(true))
See Also
Column Reordering by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
186
Telerik UI for ASP.NET Core
Custom Commands
You can implement custom commands for handling the records of the Grid.
To include a command column which will render a button for triggering the command in the column
cells:
.Columns(columns => {
columns.Command(command =>
command.Custom("ViewDetails").Click("showDetails"));
})
2. Wire the click event of the button to a JavaScript function which will receive the
corresponding Grid data item as an argument. In the function definition, handle the
command.
<script type="text/javascript">
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
kendo.alert(dataItem.ShipName);
}
</script>
For a runnable example, refer to the demo on implementing custom commands in the Grid.
See Also
Knowledge Base Section
Server-Side API
187
Telerik UI for ASP.NET Core
Column Virtualization
The Grid provides a built-in option for virtualizing its columns. To enable it, set
Scrollable(scrollable => scrollable.Virtual(GridVirtualizationMode.Columns)).
As a result, the columns outside the current visible aria of the Grid will not be rendered and this will
improve the rendering performance. When scrolling is performed the visual subset of columns is
changed accordingly.
To work properly, the column virtualization requires you to set the columns width with their Width()
method.
To enable virtualized columns:
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Scrollable(s=>s.Virtual(GridVirtualizationMode.Columns))
)
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Scrollable(s=>s.Virtual(GridVirtualizationMode.RowsAndColumns))
)
See Also
Column Virtualization by the Grid (Demo)
Virtual Scrolling of the Telerik UI for ASP.NET Core Grid
Column Widths
Knowledge Base Section
Server-Side API
188
Telerik UI for ASP.NET Core
Hierarchy
The Grid provides options for visualizing the relations between parent and child records by
displaying its table data in a hierarchical manner.
To implement hierarchy in the Grid, use the ClientDetailTemplateId() method and filter the
records in the child table based on the parent key field value. For a runnable example, refer to the
demo on using hierarchy in the Grid.
See Also
Hierarchy by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
189
Telerik UI for ASP.NET Core
Scrolling Overview
By default, the scrolling functionality of the Grid is disabled. When scrolling is enabled, the widget
applies a default height of 200px to its data area. This can be changed or removed by setting an
optional height style in the Grid's Scrollable() method.
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Scrollable(s => s.Height(400)) // Set a 400px-height style.
)
// Alternatively:
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Scrollable(s => s.Height("auto")) // Remove the default height.
)
The Virtual scrolling always displays a single page of data. Scrolling only changes the data which
is currently displayed. The Endless scrolling mode appends new pages of data to the already
rendered records. The Endless scrolling is suitable for limited number of records, because after
some point the browser will start to freeze (due to the amount of DOM elements on the page). For
huge amount of records it is recommended to use Virtual scrolling or standard paging.
For more information about the scroll modes of the Grid, refer to the articles on:
Virtual scrolling
Endless scrolling
Depending on the enabled scroll mode, the rendering of the dimensions and layout of the Grid varies.
For more information, refer to the following articles:
Getting Started
To achieve a maximum level of accessibility through assistive technologies, the scrolling feature of
the Grid has to be disabled.
By default, when scrolling is enabled, the Grid renders two tables—one for the header area and one
for the scrollable data area. The two tables are important when you need to manually make
JavaScript or CSS updates to the Grid tables.
<div class="k-widget k-grid">
190
Telerik UI for ASP.NET Core
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>...</table>
</div>
</div>
<div class="k-grid-content">
<table>...</table>
</div>
</div>
The following example demonstrates the HTML output in a Grid with virtual scrolling. For more
information, refer to the article on on virtual scrolling.
<div class="k-widget k-grid">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>...</table>
</div>
</div>
<div class="k-grid-content">
<div class="k-virtual-scrollable-wrap">
<table>...</table>
</div>
</div>
</div>
To achieve vertical scrolling, set the height of the Grid. Otherwise, it will expand vertically to
show all rows.
To achieve horizontal scrolling, explicitly define the width of all columns in pixels and make
sure their sum exceeds the width of the Grid.
When scrolling is enabled, the vertical scrollbar of the Grid is always visible even if not needed which
simplifies the implementation and improves the performance of the widget. To remove the vertical
scrollbar, use CSS rules and make sure that neither the Grid nor its data area apply fixed heights so
that they are able to shrink and expand according to the number of table rows. In the following
example, the #GridID allows the application of styles only to a particular Grid instance. To use
these styles in all Grid instances, replace the ID with the .k-grid CSS class.
#GridID .k-grid-header
{
padding: 0 !important;
}
#GridID .k-grid-content
{
overflow-y: visible;
}
191
Telerik UI for ASP.NET Core
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Scrollable()
/* Other configuration. */
.Events(events=>events
.DataBound("onGridDataBound")
.DataBinding("onGridDataBinding")
)
)
$(function () {
// Initialize the variable which will hold the scroll positions.
var scrollOffset = {
left: 0,
top: 0
};
// Save the scroll position before the new data is rendered.
function onGridDataBinding (e) {
var container = e.sender.wrapper.children(".k-grid-content"); // Or
".k-virtual-scrollable-wrap".
scrollOffset.left = container.scrollLeft();
scrollOffset.top = container.scrollTop(); // Use only if virtual scrolling is
disabled.
}
// Restore the scroll position after the new data is rendered.
function onGridDataBound (e) {
var container = e.sender.wrapper.children(".k-grid-content"); // Or
".k-virtual-scrollable-wrap".
container.scrollLeft(scrollOffset.left);
container.scrollTop(scrollOffset.top); // Use only if virtual scrolling is
disabled.
}
});
192
Telerik UI for ASP.NET Core
window.resize.
If the Grid is in the right-to-left (RTL) mode, use the "padding-left" instead of the
"padding-right" configuration.
$(window).resize(function (e) {
var grid = $('#GridID').data("kendoGrid");
grid.thead.closest(".k-grid-header").css("padding-right",
kendo.support.scrollbar(true));
});
See Also
Scrolling a Grid HtmlHelper for ASP.NET Core with Locked Columns (Demo)
Server-Side API
193
Telerik UI for ASP.NET Core
Virtual Scrolling
Virtual scrolling is an alternative to paging.
For runnable examples, refer to the demo on virtualization of remote data by the Grid.
Getting Started
When virtual scrolling is enabled, the Grid loads data from its remote data source while the user
scrolls vertically.
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.Name("grid")
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable(scrollable => scrollable.Virtual(true))
)
In virtual scrolling, the HTML output is different from the standard scrolling functionality—the data
table of the Grid is not placed inside a scrollable container. The scrollbar belongs to a separate
div.k-scrollbar which affects scenarios when the data rows have to be manually scrolled to a
particular position.
<div class="k-widget k-grid">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>...</table>
</div>
</div>
<div class="k-grid-content">
<div class="k-virtual-scrollable-wrap">
<table>...</table>
</div>
<div class="k-scrollbar k-scrollbar-vertical">
...<!-- div elements which generate a scrollbar -->...
</div>
</div>
</div>
When the user scrolls a Grid in its virtual-scrolling mode, the Grid renders the table rows for the
reached scroll position on the fly. If the Gris uses local data or if its remote data has already been
loaded and cached, the rendering rate and performance of the widget depend on:
If the total number of items is large and the scrolling is fast, the table of the Grid can be re-rendered
frequently. If, additionally, the page size is huge, the user might observe issues with the smoothness
194
Telerik UI for ASP.NET Core
of the scrolling. In such cases, reduce the page size and increase the Grid height to improve the
scrolling performance.
.k-virtual-scrollable-wrap tr
{
height: 3em;
}
// Or
.k-virtual-scrollable-wrap td
{
white-space: nowrap;
}
Using on Mobile
On mobile devices where a scrollbar that can be grabbed and dragged is not visible, virtual scrolling
of a large number of data items (for example thousands) might hinder the easy access to all table
rows because the large number of data items will require a great deal of touch scrolling. On the other
hand, using virtual scrolling with a very small number of items (for example, less than 200) does not
make much sense. Virtual scrolling on touch devices relies on drag-and-drop events, which are
slower than native scrolling. This might lead to performance issues.
Known Limitations
When virtual scrolling is not supported or recommended and depending on the number of data
items, either revert to standard paging or to non-virtual scrolling without paging.
195
Telerik UI for ASP.NET Core
scrollable data area. Otherwise the vertical virtual scrollbar will not be created. The page size of
the Grid must be over three times larger than the number of visible table rows in the data area.
A scrollable Grid with a set height needs to be visible when initialized. In this way the Grid
adjusts the height of its scrollable data area in accordance with the total height of the
widget. In certain scenarios the Grid might be invisible when initialized - for example, when
placed inside an initially inactive TabStrip tab or in another widget. In such cases use either
of the following options:
Initialize the Grid while its element is still visible.
Initialize the Grid in a suitable event of the parent widget - for example, in the
Activate() event handler of the TabStrip.
Because of height-related browser limitations (which cannot be avoided), virtual scrolling
works with up to one or two million records. The exact number of records depends on the
browser and the row height. If you use a row count that is larger than the browser can
handle, unexpected widget behavior or JavaScript errors might occur. In such cases, revert
to standard paging.
Refreshing or replacing the Grid data in the virtual mode has to be accompanied by resetting
the position of the virtual scrollbar to zero—for example, by using $('#GridID
.k-scrollbar').scrollTop(0);. In some scenarios, you might also need to call the
refresh() method.
Programmatic scrolling to a particular Grid row is not supported when virtual scrolling is
enabled, because it is not possible to reliably predict the exact scroll offset of the row.
When the Grid is navigatable, keyboard navigation supports only the Up Arrow and Down
Arrow keys. The Page Up and Page Down key scrolling is not supported.
See Also
Virtualization of Remote Data by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
196
Telerik UI for ASP.NET Core
Endless Scrolling
Endless scrolling is suitable when you display large number of items and use editing, grouping,
filtering, sorting, or hierarchy.
Getting Started
To enable endless scrolling, set the Scrollable.Endless(true)property to true.
The Grid supports endless scrolling both when it is bound to local and remote data:
When bound to local data arrays, the Grid serializes all items to the client and while the user
scrolls, the widget displays new items.
When bound to remote data, the Grid serializes only the items for one page. When the user
scrolls to the end of the list, the Grid sends an AJAX request to get the items for the next
page. When the data is returned, the Grid renders only the new items and appends them to
the old ones.
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.Name("grid")
.Scrollable(sc => sc.Endless(true))
/* Other configuration. */
)
If the Grid is scrolled to the bottom, the number of the items it will request will be equal to
the number of items and the page size.
If the last group of items is collapsed, the Grid will still make requests for the items from that
group.
If a group of items spans across multiple pages, the Grid will make multiple requests.
197
Telerik UI for ASP.NET Core
When a particular subset of items is returned, the items will be rendered and hidden because
the group is collapsed. The Grid will continue to request the items until a new group is
reached or until none of the items are present for to be requested.
The filtering, sorting, and grouping operations reset the scroll position.
See Also
Endless Scrolling of Remote Data by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
198
Telerik UI for ASP.NET Core
Export Overview
By default, the Telerik UI Grid HtmlHelper for ASP.NET Core provides a PDF and Excel export
functionality.
For more information about the available export options of the Grid, refer to the articles on:
Excel export
PDF export
Printing
Under the hood, most of the PDF export options use the Kendo UI for jQuery Drawing libraryand the
Excel export builds a kendo.ooxml.Workbook.
To enable the PDF and Excel Export functionality, add the following ToolBar configuration:
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.Name("grid")
.ToolBar(tools=>
{
tools.Pdf();
tools.Excel();
})
)
See Also
Server-Side API
199
Telerik UI for ASP.NET Core
PDF Export
The UI for ASP.NET Core Grid HtmlHelper provides a built-in PDF export functionality.
For a runnable example, refer to the demo on exporting the Grid to PDF.
With regard to its PDF export, the Grid enables you to:
Getting Started
To enable PDF export:
1. Include the corresponding toolbar command and set the export settings.
Toolbar configuration
PDF export configuration
2. Include the Pako Deflate library in the page to enable compression.
To initiate PDF export, press the Toolbar button or use the Grid client-side APIand call the saveAsPdf
method.
By default, the Grid exports the current page of the data with sorting, filtering, grouping, and
aggregates applied.
The Grid uses the current column order, visibility, and dimensions to generate the PDF file.
The following example demonstrates how to enable the PDF export functionality of the Grid.
<!-- Load Pako Deflate library to enable PDF compression -->
<script
src="http://kendo.cdn.telerik.com/2019.3.1023/js/pako_deflate.min.js"></script>
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.FileName("Kendo UI Grid Export.pdf")
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
200
Telerik UI for ASP.NET Core
When the AllPages() method is used with and server paging (Ajax binding default), the Grid will
make a "read" request for all data. If the data items are too many, the browser may become
unresponsive. In such cases, use server-side export.
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
You can specify a paper size that will be applied to the whole document. The content will be scaled
to fit the specified paper size. The automatic scale factor can be overridden, for example, to make
room for additional page elements. To use all available space, the Grid will:
Adjust the column widths to fill the page so try to avoid setting width on all columns.
Vary the number of rows for each page, placing page breaks where appropriate.
Omit the toolbar and the pager.
To fit the Grid content to the paper size, all records have to be rendered at once.
The exact maximum number of exportable rows will vary depending on the browser, system
resources, template complexity, and other factors.
A good practice is to verify your own worst-case scenarios in each browser you intend to
support.
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
.Landscape()
201
Telerik UI for ASP.NET Core
.PaperSize("A4")
.Scale(0.75)
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
pageNumber
totalPages
<style>
body {
font-family: "DejaVu Serif";
font-size: 12px;
}
.page-template {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.page-template .header {
position: absolute;
top: 30px;
left: 30px;
right: 30px;
border-bottom: 1px solid #888;
text-align: center;
font-size: 18px;
}
.page-template .footer {
position: absolute;
bottom: 30px;
left: 30px;
right: 30px;
}
</style>
<script type="x/kendo-template" id="page-template">
202
Telerik UI for ASP.NET Core
<div class="page-template">
<div class="header">
Acme Inc.
</div>
<div class="footer">
<div style="float: right">Page #: pageNum # of #: totalPages #</div>
</div>
</div>
</script>
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
.PaperSize("A4")
.Margin("2cm", "1cm", "1cm", "1cm")
.Landscape()
.RepeatHeaders()
.Scale(0.75)
.TemplateId("page-template")
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
.ProxyURL("/MyProxy")
.Landscape()
.PaperSize("A4")
.Scale(0.75)
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
203
Telerik UI for ASP.NET Core
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.ForceProxy(true)
.ProxyURL("/Pdf_Export_Save")
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
[HttpPost]
public ActionResult Pdf_Export_Save(string contentType, string base64, string
fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
<style>
/*
Use the DejaVu Sans font for display and embedding in the PDF file.
The standard PDF fonts have no support for Unicode characters.
*/
.k-grid {
font-family: "DejaVu Sans", "Arial", sans-serif;
}
</style>
<script>
// Import the DejaVu Sans font for embedding.
// NOTE: Only required if the Kendo UI stylesheets are loaded
// from a different origin, for example, kendo.cdn.telerik.com.
kendo.pdf.defineFont({
"DejaVu Sans" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans.ttf",
"DejaVu Sans|Bold" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Bold.ttf",
"DejaVu Sans|Bold|Italic" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Oblique.ttf",
"DejaVu Sans|Italic" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Oblique.ttf"
});
</script>
204
Telerik UI for ASP.NET Core
<!-- Load Pako ZLIB library to enable PDF compression -->
<script src="//kendo.cdn.telerik.com/2019.3.1023/js/pako_deflate.min.js"></script>
@(Html.Kendo().Grid<.ProductViewModel>()
.Name("grid")
.ToolBar(tools => tools.Pdf())
.Pdf(pdf => pdf
.AllPages()
)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
Known Limitations
All known limitationsof the Kendo UI for jQuery HTML Drawing module apply.
Exporting a hierarchical Grid is not supported.
PDF export is not supported when the Grid has a locked (frozen) column enabled. If the
algorithm decides to move a node to the next page, all DOM nodes that follow it will be also
moved although there might be enough space for part of them on the current page.
The built-in PDF export option of the Kendo UI Grid exports as many columns as it can fit on
a page with a defined page size. If the columns do not fit, they will be cropped. If you need to
support more columns that can be fit on a page, use the Kendo UI for jQuery side-to-side PDF
exportapproach instead.
Further Reading
Export tabular data as PDF in Kendo UI
PDF output by the Kendo UI Drawing library
Drawing DOM elements with the Kendo UI Drawing library
Saving files with Kendo UI
See Also
Server-Side API
Rendering and Dimensions of the Grid HtmlHelper for ASP.NET Core
Adaptive Rendering of the Grid HtmlHelper for ASP.NET Core
205
Telerik UI for ASP.NET Core
Printing
Even though the content of the Grid might not be the only content on a page, the Grid provides
options to ignore the rest of the page and print only its contents.
To print only the Grid from a page, use either of the following approaches:
Print the existing page and hide the irrelevant content with print CSS.
Print a separate web page with only the Grid on it.
If the Grid is scrollable, some rows or columns may not be visible on the printed paper.
Therefore, the Grid height and scrollability are disabled on the print-friendly page.
Depending on the column width, some of the cell content may be clipped and not fully
visible. This issue is resolved by forcing an automatic table-layout to the Grid table which
disables the ellipsis (...).
If scrolling is enabled (which is set by default except for the MVC wrapper of the Grid), the
Grid renders a separate table for the header area. Because the browser does not relate the two
Grid tables, it will not repeat the header row on top of every printed page. The following
example demonstrates how to address this issue by cloning the header table row into the
data table.
When you print a Grid with locked (frozen) columns, it is possible that the resulting columns
or rows get misaligned or that the overall layout gets broken. In such cases, use a separate
print-friendly Grid instance with no frozen columns.
<button type="button" class="k-button" id="printGrid">Print Grid</button>
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.Name("grid")
.Columns(c =>
{
c.Bound(f => f.OrderID);
c.Bound(f => f.ShipCountry);
})
.DataSource(d =>
{
d.Ajax()
.Read(r => r.Action("ReadOrders", "Home"));
})
)
<script>
206
Telerik UI for ASP.NET Core
function printGrid() {
var gridElement = $('#grid'),
printableContent = '',
win = window.open('', '', 'width=800, height=500, resizable=1,
scrollbars=1'),
doc = win.document.open();
var htmlStart =
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<meta charset="utf-8" />' +
'<title>Kendo UI Grid</title>' +
'<link href="https://kendo.cdn.telerik.com/' + kendo.version +
'/styles/kendo.common.min.css" rel="stylesheet" /> ' +
'<style>' +
'html { font: 11pt sans-serif; }' +
'.k-grid { border-top-width: 0; }' +
'.k-grid, .k-grid-content { height: auto !important; }' +
'.k-grid-content { overflow: visible !important; }' +
'div.k-grid table { table-layout: auto; width: 100% !important; }' +
'.k-grid .k-grid-header th { border-top: 1px solid; }' +
'.k-grouping-header, .k-grid-toolbar, .k-grid-pager > .k-link { display:
none; }' +
// '.k-grid-pager { display: none; }' + // optional: hide the whole pager
'</style>' +
'</head>' +
'<body>';
var htmlEnd =
'</body>' +
'</html>';
var gridHeader = gridElement.children('.k-grid-header');
if (gridHeader[0]) {
var thead = gridHeader.find('thead').clone().addClass('k-grid-header');
printableContent = gridElement
.clone()
.children('.k-grid-header').remove()
.end()
.children('.k-grid-content')
.find('table')
.first()
.children('tbody').before(thead)
.end()
.end()
.end()
.end()[0].outerHTML;
} else {
printableContent = gridElement.clone()[0].outerHTML;
}
doc.write(htmlStart + printableContent + htmlEnd);
doc.close();
win.print();
}
$('#printGrid').click(function () {
printGrid();
});
</script>
207
Telerik UI for ASP.NET Core
See Also
Excel Export by the Grid HtmlHelper for ASP.NET Core (Demo)
Copying to Excel by the Grid HtmlHelper for ASP.NET Core (Demo)
PDF Export of the Grid HtmlHelper for ASP.NET Core
Server-Side API
208
Telerik UI for ASP.NET Core
Templates Overview
The Progress Telerik UI Grid HtmlHelper for ASP.NET Core provides a number of templating options
that can be used to customize the way the data is visualized in the table.
Under the hood, the templates use the Kendo UI Templates syntax.
Column templates
Row templates
Client detail templates
Group templates
Editor templates
See Also
Templates by the Grid HtmlHelper for ASP.NET Core (Demos)
Server-Side API
209
Telerik UI for ASP.NET Core
Column Templates
The Grid renders table rows (tr) which represent the data source items.
Demo on using the row template of the Grid HtmlHelper for ASP.NET Core
Demo on using the detail-row template of the Grid HtmlHelper for ASP.NET Core
Demo on using the toolbar template of the Grid HtmlHelper for ASP.NET Core
Each table row consists of table cells (td) which represent the Grid columns. By default, the Grid
displays the HTML-encoded value of the field in the column.
The following example demonstrates how to set the template as a string and wrap the column value
in HTML.
.Columns(c =>
{
c.Bound(f => f.ShipCountry).ClientTemplate("<strong>#= ShipCountry #
</strong>");
})
The following example demonstrates how to set column templates as a Kendo UI template.
.Columns(c =>
{
c.Bound(f => f.ShipCountry).ClientTemplate("<strong>#= ShipCountry #
</strong>");
})
<script type="kendo-template" id="my-template">
<em>#= ShipCountry # </em>
</script>
.Columns(c =>
{
c.Bound(f => f.Products).ClientTemplate("#=showProducts(data)#");
})
<script>
function showProducts(data) {
if (data.Products) {
var template = "<ul>";
for (var i = 0; i < data.Products.length; i++) {
var product = data.Products[i];
template += kendo.format("<li>Product: {0}, Price: {1:c} </li>",
product.ProductName, product.Price) ;
}
template += "</ul>"
return template;
210
Telerik UI for ASP.NET Core
}
}
</script>
See Also
Templates by the Grid HtmlHelper for ASP.NET Core (Demos)
Server-Side API
211
Telerik UI for ASP.NET Core
Row Templates
The Kendo UI Grid supports row templates which enable you to place custom content into a Grid
row.
Demo on using the row template of the Grid HtmlHelper for ASP.NET Core
Demo on using the detail-row template of the Grid HtmlHelper for ASP.NET Core
Demo on using the toolbar template of the Grid HtmlHelper for ASP.NET Core
The following example demonstrates how to use a string row template which generates two
columns. The outermost HTML element in the template must be a table row ( <tr>). That table row
must have the uid data attribute set to #= uid #. The grid uses the uid data attribute to determine
the data to which a table row is bound to.
.ClientRowTemplate("<tr data-uid='#=data.uid#'>" +
"<td>#=data.OrderID#</td>" +
"<td><strong>#=ShipCountry #</strong></td>" +
"</tr>")
See Also
Using Row Templates in the Grid HtmlHelper for ASP.NET Core (Demo)
Using Detail-Row Templates in the Grid HtmlHelper for ASP.NET Core (Demo)
Using Toolbar Templates in the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
212
Telerik UI for ASP.NET Core
For a runnable example, refer to the demo on detail templates in the Grid.
1. Open HomeController.cs and add a new action method which will return the Products as
JSON. The Grid makes Ajax requests to this action.
public ActionResult Products_Read()
{
}
2. Add a new parameter of type DataSourceRequest to the action. This parameter will contain
the current Grid request information—page, sort, group, and filter. Decorate that parameter
with the DataSourceRequestAttribute. This attribute will populate the
DataSourceRequest object from the posted data.
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
}
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
using (var northwind = new NorthwindEntities())
{
IQueryable<Product> products = northwind.Products;
DataSourceResult result = products.ToDataSourceResult(request);
}
}
213
Telerik UI for ASP.NET Core
4. Return the DataSourceResult as JSON. Configure the Grid for Ajax binding.
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request)
{
using (var northwind = new NorthwindEntities())
{
IQueryable<Product> products = northwind.Products;
DataSourceResult result = products.ToDataSourceResult(request);
return Json(result);
}
}
5. In the view, configure the Grid to use the action method created in the previous steps.
@(Html.Kendo().Grid<KendoGridClientDetailTemplate.Models.Product>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
.Columns(columns =>
{
columns.Bound(product => product.ProductID);
columns.Bound(product => product.ProductName);
})
.Pageable()
)
6. Define the client template using the Kendo UI for jQuery templatesyntax. The context of the
template is the data item—Product entity—to which the current Grid row is bound.
@(Html.Kendo().Grid<KendoGridClientDetailTemplate.Models.Product>()
.Name("grid")
.DataSource(dataSource => dataSource
214
Telerik UI for ASP.NET Core
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
.Columns(columns =>
{
columns.Bound(product => product.ProductID);
columns.Bound(product => product.ProductName);
})
.Pageable()
.ClientDetailTemplateId("client-template")
)
1. Open HomeController.cs and add a new action method which will return the Category
entities as JSON. The Grid makes Ajax requests to this action.
public ActionResult Categories_Read()
{
}
2. Add a new parameter of type DataSourceRequest to the action. This parameter will contain
the current grid request information - page, sort, group and filter. Decorate that parameter
with the DataSourceRequestAttribute. That attribute will populate the
DataSourceRequest object from the posted data.
public ActionResult Categories_Read([DataSourceRequest]DataSourceRequest
request)
{
}
public ActionResult Categories_Read([DataSourceRequest]DataSourceRequest
request)
{
using (var northwind = new NorthwindEntities())
{
IQueryable<Category> categories = northwind.Categories;
// Flatten the Category to avoid circular references during JSON
serialization.
DataSourceResult result = categories.ToDataSourceResult(request, category
=> new {
category.CategoryID,
215
Telerik UI for ASP.NET Core
category.CategoryName
});
}
}
4. Return the DataSourceResult as JSON. Now let's configure the Grid for AJAX binding.
public ActionResult Categories_Read([DataSourceRequest]DataSourceRequest
request)
{
using (var northwind = new NorthwindEntities())
{
IQueryable<Category> categories = northwind.Categories;
// Flatten the Category to avoid circular references during JSON
serialization.
DataSourceResult result = categories.ToDataSourceResult(request, category
=> new {
category.CategoryID,
category.CategoryName
});
return Json(result);
}
}
5. Open HomeController.cs and add a new action method which will return the Product
entities for a given category as JSON. The child Grid makes Ajax requests to this action.
public ActionResult Products_Read([DataSourceRequest]DataSourceRequest request,
int categoryId)
{
using (var northwind = new NorthwindEntities())
{
IQueryable<Product> products = northwind.Products.Where(product =>
product.CategoryID == categoryId);
// Flatten the Product to avoid circular references during JSON
serialization
DataSourceResult result = products.ToDataSourceResult(request, product =>
new {
product.ProductID,
product.ProductName
});
return Json(result);
}
}
@(Html.Kendo().Grid<KendoGridClientHierarchy.Models.Category>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(category => category.CategoryID);
216
Telerik UI for ASP.NET Core
columns.Bound(category => category.CategoryName);
})
.DataSource(dataSource =>
dataSource.Ajax().Read(read => read.Action("Categories_Read", "Home"))
)
)
7. Define the client template using Kendo UI Templatesyntax. The context of the template is the
Category entity to which the current Grid row is bound. The template itself contains another
Grid which is bound to the Products_Read action.
Always call the ToClientTemplate method when using Telerik UI for ASP.NET Core
helpers in a client template.
Escape the # characters used for a template expression when using a column
ClientTemplate in a detail template, so that the expression is evaluated in the correct
context.
<script id="client-template" type="text/x-kendo-template">
@(Html.Kendo().Grid<KendoGridClientHierarchy.Models.Product>()
.Name("grid_#=CategoryID#") // make sure the Name is unuque
.Columns(columns =>
{
columns.Bound(product => product.ProductID);
columns.Bound(product =>
product.ProductName).ClientTemplate("<strong>\\#:ProductName\\#</strong>"); //
escape the "#" characters
})
.DataSource(dataSource =>
// Make a request to Products_Read and provide the current CategoryID as
a route parameter.
dataSource.Ajax().Read(read => read.Action("Products_Read", "Home", new {
categoryId = "#=CategoryID#" }))
)
.Pageable()
.ToClientTemplate()
)
</script>
@(Html.Kendo().Grid<KendoGridClientHierarchy.Models.Category>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(category => category.CategoryID);
columns.Bound(category => category.CategoryName);
})
.DataSource(dataSource =>
dataSource.Ajax().Read(read => read.Action("Categories_Read", "Home"))
)
.ClientDetailTemplateId("client-template")
)
217
Telerik UI for ASP.NET Core
See Also
Client Detail Templates by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
218
Telerik UI for ASP.NET Core
Group Templates
Group rows help organize data rows into a tree structure when data grouping is applied.
A group row contains an expanding and collapsing group icon that enables end-users to expand and
collapse a group row, and thus show or hide its child rows. One of the main features of group rows is
to display group summary values. The Grid provides three different templates that can be used to
customize the appearance of the group rows:
If no template is defined, the name of the field and the current group are displayed in the following
way.
The only difference in the use of ClientGroupHeaderTemplate is that the template content is
compiled and displayed instead of the field and current group value.
219
Telerik UI for ASP.NET Core
Due to the fact that ClientGroupHeaderTemplate is displayed next to the expanding icon of the
group row, it takes precedence over the ClientGroupHeaderColumnTemplate of the first visible
column. If you want to show the ClientGroupHeaderColumnTemplate content for the first column
of the Grid, do not set the ClientGroupHeaderTemplate for the group column. The following Grid
configuration shows that commenting the ClientGroupHeaderTemplate for the Units In Stock
column shows the ClientGroupHeaderColumnTemplate for the Product Name column.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName)
.ClientGroupHeaderColumnTemplate("Count: #=count#");
columns.Bound(p => p.UnitPrice).Format("{0:C}");
columns.Bound(p => p.UnitsOnOrder);
columns.Bound(p => p.UnitsInStock);
//.ClientGroupHeaderTemplate("Min: #= min #");
})
.Pageable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Aggregates(aggregates =>
{
aggregates.Add(p => p.UnitsInStock).Min();
aggregates.Add(p => p.ProductName).Count();
})
.Group(groups => groups.Add(p => p.UnitsInStock))
.Read(read => read.Action("Aggregates_Read", "Grid"))
)
)
220
Telerik UI for ASP.NET Core
See Also
Templates by the Grid HtmlHelper for ASP.NET Core (Demos)
Server-Side API
221
Telerik UI for ASP.NET Core
Editor Templates
You can create an editing UI of a Telerik UI Grid for ASP.NET Core by defining editor templates.
Getting Started
The Telerik UI Grid for ASP.NET Core relies on ASP.NET Core editor templates to create an editing
UI. If the Grid is configured for in-line or in-cell editing, it uses the Html.EditorFor method to get
the editor HTML for every property which is editable.
The configuration later in this article will be used to get the editor HTML for the OrderDate and
ShipCountry properties.
@(Html.Kendo().Grid<Order>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.OrderDate);
columns.Bound(o => o.ShipCountry);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
The following example demonstrates the code that will be used to get the editor HTML for the
OrderDate and ShipCountry properties.
@(Html.EditorFor(o => o.OrderDate);
@(Html.EditorFor(o => o.ShipCountry);
If the Grid is configured for popup editing, it will use the Html.EditorForModel to get the editor
HTML for the whole model.
1. Consider the following models which represent the Order and Employee entities from the
Northwind database.
public class Order
{
public int OrderID { get; set; }
public string ShipCountry { get; set; }
222
Telerik UI for ASP.NET Core
public Employee Employee { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
2. Create an editor template for the Employee property which will display a Kendo UI for jQuery
DropDownList with all available employees. Add a new partial view to the
~/Views/Shared/EditorTemplates folder—for example, EmployeeEditor.cshtml.
3. Add the DropDownList to that partial view. Set the Name of the DropDownList to the name of
the property which will be edited—"Employee" in this case.
@(Html.Kendo().DropDownList()
.Name("Employee") // The name of the widget has to be the same as the name
of the property.
.DataValueField("EmployeeID") // The value of the drop-down is taken from
the EmployeeID property.
.DataTextField("EmployeeName") // The text of the items is taken from the
EmployeeName property.
.BindTo((System.Collections.IEnumerable)ViewData["employees"]) // A list of
all employees which is populated in the controller.
)
4. In the action method, which renders the view that contains the Grid, populate the ViewData
with a list of all employees.
public ActionResult Index()
{
ViewData["employees"] = new NorthwindDataContext()
.Employees
.Select(e => new Employee
{
EmployeeID = e.EmployeeID,
EmployeeName = e.FirstName + " " + e.LastName
})
.OrderBy(e => e.EmployeeName);
return View();
}
5. Decorate the Employee property with the UIHintattribute. It needs the name of the editor
template created in Step 3 without the extension "EmployeeEditor".
public class Order
{
public int OrderID { get; set; }
223
Telerik UI for ASP.NET Core
public string ShipCountry { get; set; }
[UIHint("EmployeeEditor")]
public Employee Employee { get; set; }
}
See Also
Templates by the Grid HtmlHelper for ASP.NET Core (Demos)
Server-Side API
224
Telerik UI for ASP.NET Core
Height
By default, the Grid has no set height and expands to fit all table rows.
Getting Started
Set the height to the Grid only when its scrolling is enabled. For more information on the supported
scroll modes by the Grid, refer to the article on scrolling.
To set the height of the Grid, use any of the following approaches:
Apply an inline height style to the <div> from which the Grid is initialized.
Use the height property of the Grid which will apply an inline style to the Grid wrapper—the
same as the previous option.
Use external CSS. For example, use the ID or the .k-grid CSS class to apply a height style.
When the height of the Grid is set, it calculates the appropriate height of its scrollable data area, so
that the sum of the header rows, filter row, data, footer, and pager is equal to the expected height of
the Grid. That is why if you change the height of the Grid through JavaScript after you create the Grid,
you have to call the resize methodafterwards. In this way the Grid recalculates the height of its data
area.
var gridWidget = $("#GridID").data("kendoGrid");
// Apply the new height and trigger the layout readjustment.
gridWidget.wrapper.height(800);
gridWidget.resize();
// Force the layout readjustment without setting a new height.
gridWidget.resize(true);
In specific scenarios you can set a height style to the scrollable data area either by using JavaScript
or external CSS which is a div.k-grid-content element. In such cases avoid setting a height to
the Grid.
<div style="width:500px;">
@(Html.Kendo().Grid<OrderViewModel>()
.Scrollable()
.HtmlAttributes(new { style = "height: 200px;" })
/* other configurations */
)
</div>
225
Telerik UI for ASP.NET Core
#GridID .k-grid-content
{
min-height: 100px;
max-height: 400px;
}
Enabling Auto-Resizing
Enabling the auto-resize feature is applicable to scrollable Grids only. For more information on the
supported scroll modes by the Grid, refer to the article on scrolling.
1. To allow the Grid to resize together with its parent, apply a 100% height style to its <div
class="k-grid"> wrapper. According to the web standards, elements which have their
height set in percentage require that the height of their parent is also explicitly set. This
requirement applies recursively until either an element with a pixel height or the html
element is reached. Elements that are 100% high cannot have margins, paddings, borders, or
sibling elements. That is why you have to remove the default border of the Grid as well.
2. Make sure that the inner layout of the Grid adapts to changes in the height of the <div>
wrapper. If these changes are triggered by the resizing of the browser window, subscribe to
the window resize event of the browser and execute the resize()method of the Grid. The
resize method measures the height of the Grid <div> and adjusts the height of the
scrollable data area.
If the Grid is placed inside a Kendo UI Splitter or Kendo UI Window, you do not need to
226
Telerik UI for ASP.NET Core
call the resize method because these widgets will execute it automatically. Also, it is not
necessary to apply the method if you use locked columns.
If the vertical space that is available for the Grid depends on a custom resizing of the
layout, which is controlled by the user, use a suitable event or method related to the
layout changes to execute the resize method of the Grid. In this case, call the resize
method even if you use locked columns.
See Also
Scrolling by the Grid HtmlHelper for ASP.NET Core (Demos)
Scroll Modes of the Grid HtmlHelper for ASP.NET Core
Server-Side API
227
Telerik UI for ASP.NET Core
Width
By default, the Grid has no set width, behaves like a block-level element, and expands to a 100%
width (the width of the parent element).
Getting Started
To control the width of the Grid, set the CSS width properties to the Grid itself or to some of its
ancestors. If you use hierarchy and unless the detail template is scrollable, the detail template has to
be narrower than the sum of the widths of all master columns. For more information on the
supported scroll modes by the Grid, refer to the article on scrolling.
If you enable scrolling and the sum of all column widths is greater than the width of the Grid, a
horizontal scrollbar appears. If you disable scrolling and the columns do not fit, they overflow the
<div> element of the Grid. The div overflowing results in the passing of the right border of the Grid
through the data cells because the Grid is a <table> element inside a <div> element and while to
enclose their content tables can expand horizontally beyond 100%, <div> elements lack this
behavior.
Enable the scrolling functionality which, by default, is disabled when the Kendo UI Grid MVC
wrapper is in use.
Set a large-enough width or a min-width style to the Grid wrapper—the <div
class="k-widget k-grid"> element.
(Use this approach only if the previous two are unacceptable.) Floatthe Grid wrapper and
clearthe float right after the Grid. Floated elements expand and shrink automatically to
enclose their content when needed.
#GridID
{
min-width: 800px;
}
If scrolling is enabled and the Grid is not hierarchical (with no nested tables), use the
following CSS. For more information on the supported scroll modes by the Grid, refer to the
article on scrolling.
228
Telerik UI for ASP.NET Core
#GridID .k-grid-header-wrap > table, // A header table.
#GridID .k-grid-content table, // A data table, no virtual scrolling.
#GridID .k-virtual-scrollable-wrap table // A data table, with virtual
scrolling.
{
min-width: 800px;
}
If scrolling is enabled and the Grid is hierarchical (with nested tables), use the following CSS.
For more information on the supported scroll modes by the Grid, refer to the article on
scrolling.
#GridID .k-grid-header-wrap > table, // A header table.
#GridID .k-grid-content table, // A data table, no virtual scrolling.
#GridID .k-virtual-scrollable-wrap table // A data table, with virtual
scrolling.
{
min-width: 800px;
}
#GridID .k-grid-content table table, // A data table, no virtual scrolling.
#GridID .k-virtual-scrollable-wrap table table // A data table, with virtual
scrolling.
{
min-width: initial;
}
See Also
Scrolling by the Grid HtmlHelper for ASP.NET Core (Demos)
Scroll Modes of the Grid HtmlHelper for ASP.NET Core
Server-Side API
229
Telerik UI for ASP.NET Core
Rows
The Grid enables you to handle the appearance of its rows by using the id of the data item, adding
custom rows, utilizing row templates, and disabling the hover effect.
1. Make sure the Id field is defined in the model configurationof the data source of the Grid.
2. Retrieve the row model, the model UID, and the Grid table row consecutively.
The following example demonstrates how to add a table row in the DataBound()event handler of
the Grid.
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.Name("grid")
.Filterable()
/* Other configuration. */
.Events(e=>e.DataBound("onGridDataBound"))
)
function onGridDataBound(e) {
if (!e.sender.dataSource.view().length) {
var colspan = e.sender.thead.find("th:visible").length,
emptyRow = '<tr><td colspan="' + colspan + '">... no records ...</td></tr>';
e.sender.tbody.parent().width(e.sender.thead.width()).end().html(emptyRow);
}
}
230
Telerik UI for ASP.NET Core
Hover is a UI state which provides better visualization across long table rows and when the Grid is in
its edit mode. However, if your project requires you to avoid the hover state, use either of the
following approaches:
Open the Kendo UI theme CSS file (for example, kendo.default.min.css) and remove the
following CSS rule.
.k-grid tr:hover {
/* ...background styles here... */
}
Override the hover styling by using the CSS code from the following example. The #f1f1f1
value corresponds to the background color of the .k-alt table rows. To find the correct
value for the Kendo UI theme that you are applying, use the DOM inspector of the browser.
Alternatively, set a background color value of your preference.
.k-grid tr:not(.k-state-selected):hover {
background: none;
color: inherit;
}
.k-grid tr.k-alt:not(.k-state-selected):hover {
background: #f1f1f1;
}
See Also
Using Row Templates in the Grid HtmlHelper for ASP.NET Core (Demo)
Row Templates in the Grid HtmlHelper for ASP.NET Core
Server-Side API
231
Telerik UI for ASP.NET Core
Hidden Containers
If you initialize a Grid inside a hidden container, the Grid may not adjust its layout correctly.
For example, when you apply scrolling, virtual scrolling, or locked columns and initialize the Grid in a
hidden container, its vertical layout will not be correctly adjusted because the JavaScript size
calculations do not work for elements with a display:none style. For more information on the
supported scroll modes by the Grid, refer to the article on the available scroll modes of the Grid
HtmlHelper for ASP.NET Core.
You can identify that the Grid is initialized in a hidden state if any of the following symptoms occur:
To handle the behavior that is related to the initialization of the Grid inside a hidden container, use
any of the following approaches:
Delay the initialization of the Grid or change the order in which various Kendo UI widgets are
initialized, so that the Grid is initialized after its element becomes visible.
Execute the Kendo UI for jQuery resize()method after the Grid becomes visible.
Instead of setting an overall height for the Grid in its configuration, define the height for the
scrollable data area only. In this case, no height calculations are made.
This approach is applicable only if frozen columns and virtual scrolling are not used.
#GridID .k-grid-content
{
height: 270px;
}
This approach is applicable if virtual scrolling is enabled and the Kendo UI version is older
than 2014.3.1119.
$("#GridID").data("kendoGrid").dataSource.fetch();
See Also
Scrolling by the Grid HtmlHelper for ASP.NET Core (Demos)
232
Telerik UI for ASP.NET Core
233
Telerik UI for ASP.NET Core
Adaptive Rendering
The Telerik UI Grid for ASP.NET Core provides consistency to the customer experience on any device
by supporting adaptive enhancements.
For example, when you filter or edit data on mobile, the system slides in a new screen for the user,
which is a departure from the desktop-like inline and popup behaviors. For a runnable example, refer
to the demo on implementing the responsive web design in the Grid .
@(Html.Kendo().Grid<ProductViewModel>()
.Name("grid")
.Mobile()
.HtmlAttributes(new { style = "height:450px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
@(Html.Kendo().Grid<ProductViewModel>()
.Name("grid")
.Mobile(MobileMode.Phone)
.HtmlAttributes(new { style = "height:450px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
)
)
Resizing Columns
The column resizing feature on touch screen devices is triggered when the user holds a finger on the
respective column header. When the resizing icon appears, the user can resize the column by
dragging.
234
Telerik UI for ASP.NET Core
1. Call the Kendo UI for jQuery kendo.destroy()method over the closest .k-pane-wrapper
ancestor which is created around the Grid.
235
Telerik UI for ASP.NET Core
See Also
Responsive Columns by the Grid HtmlHelper for ASP.NET Core (Demo)
Adaptive Rendering by the Grid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
236
Telerik UI for ASP.NET Core
Best Practices
This article lists the best practices and approaches which optimize and boost the performance of
the Grid.
Enable paging
Enable virtualization
Reduce the quantity of data
Use fast browsers
Enabling Paging
In theory, if paging is enabled, all performance issues will be resolved. Limiting the number of
records per page to a reasonable count enables you to implement all Grid functionality without
affecting its performance. For example, rendering 50 records per page even with 20 columns results
in 1,000 cells which will be handled quickly by the browsers. For more complex scenarios where, for
example, you need to render editors directly in the column template instead of in the editor template,
you can further reduce the pageSize—if you initialize a widget in each cell, you will end up with
1,000 widgets which will be a major hit.
After you enable the paging functionality, you have to decide whether to handle the data operations
on the client or on the server. This approach applies to all data operations such as filtering, grouping,
and sorting.
The Grid will display a limited number of records. If the number of records grows, it is
possible to exceed the maxJsonLength and you might need to increase the limit.
The data will be user-based and other users will not be expected to update the same records.
You want to avoid separate AJAX requests for each data operation.
You need access to all dataItems on the client side for custom data operations. To retrieve
the entire dataset, use the data method of the dataSource.
Enabling Virtualization
Virtual scrollingis an alternative to paging and renders the records over the previously rendered
records. The approach reduces the DOM elements but enables the user to smoothly scroll the data.
237
Telerik UI for ASP.NET Core
You can use both local binding or remote binding (for huge amounts of data) for the virtual scrolling.
While the user scrolls down the records, new requests for retrieving the next view will be initiated.
However, the virtualization delivers some known limitations—for more information about what they
are, refer to this article.
To reduce the quantity of data, you can also set initial filter criteria for a specific field in the
dataSource of the Grid. However, if filtering is enabled and the column which is bound to that field is
visible, the user will be able to remove it.
238
Telerik UI for ASP.NET Core
Common Mistakes
This article lists the configuration approaches which most frequently affect the performance of the
Grid.
Rendering everything
Excessive use of editors or widgets directly in the columns
Extreme number of columns
Expanding all content
Rendering Everything
If the Grid displays too many records and columns without having its paging or virtual scrolling
functionality enabled, the result is a huge amount of DOM elements and event listeners on the page.
While some browsers can handle more records than others, avoid rendering more than 100 records
per page without paging or virtualization. To find specific records, enable filtering which is faster
than, for example, rendering 1,000 records and scrolling down to find what the user is looking for.
If you prevent the rebinding of the Grid after each change by removing the two-way binding and by
manually changing the dataItem values (changing the properties without using the set method and
setting the dirty property to true), you can edit multiple records without re-rendering the Grid.
However, the issue with the initial initialization of the widget is still present and to work around it,
reduce the PageSize() up to five or ten records per page depending on the number of columns.
To work around this issue, if your Grid displays up to 20 columns, define all of them in its
configuration and decrease the PageSize() to up to 50 (1,000 cells). You can also hide some of the
columns and enable the ColumnMenu() so that the user can choose which columns to display.
However, if your Grid displays 100 or more columns, implement external logic for allowing the end
user to choose a list of columns that will be rendered. You can then use that list to initialize the Grid
with only that set of columns. The benefit of this approach is that no hidden columns will be
239
Telerik UI for ASP.NET Core
rendered in the DOM and you will reduce the cell count drastically.
Another issue you might encounter when the Grid displays too many columns is the usage of the
autoFitColumn() method which traverses each column cell to retrieve the width of its content. To
work around this behavior, avoid using autoFitColumn().
See Also
Server-Side API
Rendering and Dimensions of the Grid HtmlHelper for ASP.NET Core
Adaptive Rendering of the Grid HtmlHelper for ASP.NET Core
240
Telerik UI for ASP.NET Core
columns.Bound(o => o.Description).Encoded(false);
.Columns(columns =>
{
columns.Bound(p => p.Title).ClientTemplate("<strong>#: Title #</strong>");
})
columns.Bound(p => p.ProductName).ClientTemplate(
"# if (HasIcon == true) { #" +
"<img src='" + Url.Content("~/Content/icons/") + "#= ProductID #.png' alt='#=
ProductName # icon' />" +
"# } else { #" +
"#: ProductName #" +
"# } #"
);
241
Telerik UI for ASP.NET Core
The following example demonstrates the syntax when you use a column template in a server-bound
Grid.
columns.Bound(p => p.ProductName).Template( @<text>
@if(@item.ProductName != null){
@item.ProductName
} else {
"No data"
}
</text>
);
columns.Bound(p => p.Enabled).ClientTemplate(
"<input type='checkbox' value='#= ProductID #' " +
"# if (Enabled) { #" +
"checked='checked'" +
"# } #" +
"/>"
);
columns.Bound(p => p.ProductID).Template(@<text>
@Html.ActionLink("Show Product Details", "ProductDetails", new { id =
@item.ProductID } )>
</text>);
For Ajax-bound Grids, use the ClientTemplate method. The following example
demonstrates an action link in an Ajax-bound Grid column.
columns.Bound(p => p.ProductID).ClientTemplate(
"<a href='" +
Url.Action("ProductDetails", "Product") +
"/#= ProductID #'" +
">Show Product Details</a>"
);
242
Telerik UI for ASP.NET Core
The following example demonstrates how to use a JavaScript function in the ClientTemplate.
// Omitted for brevity.
columns.Bound(p => p.ProductID).ClientTemplate("#= productDetails(data) #");
// Omitted for brevity.
<script>
function productDetails(product) {
var action = '@Url.Action("ProductDetails", "Product")';
var html = kendo.format("<a href='{0}/{1}'>Show Product Details</a>",
action,
product.ProductID
);
return html;
}
</script>
The following example demonstrates how to add a Kendo UI Menu inside a Grid column template.
Note that the Menu requires the Grid cells to allow overflowing, which is disabled by default.
@(Html.Kendo().Grid<ModelType>()
.Name("GridID")
.Columns(columns => {
columns.Template(@<text></text>).HtmlAttributes(new { @class = "templateCell"
}).ClientTemplate(
Html.Kendo().Menu()
.Name("menu_#=OrderID#")
.Items(its =>
{
its.Add().Text("foo").Items(nested =>
{
nested.Add().Text("bar");
nested.Add().Text("baz");
});
})
.ToClientTemplate().ToHtmlString()
);
243
Telerik UI for ASP.NET Core
})
.Events(ev => ev.DataBound("initMenus"))
)
function initMenus(e) {
$(".templateCell").each(function(){
eval($(this).children("script").last().html());
});
}
.k-widget .templateCell
{
overflow: visible;
}
The following example demonstrates how to specify the format of a bound column.
columns.Bound(o => o.OrderDate).Format("{0:d}"); // Will use the short date pattern
The following example demonstrates how to add Kendo UI icons to custom command buttons.
@(Html.Kendo().Grid()
.Name("grid")
.Columns(columns =>
{
columns.Command(command => { command.Custom("myCommand").Text("My
Text").IconClass("k-icon k-i-custom"); });
})
)
244
Telerik UI for ASP.NET Core
// Omitted for brevity.
.DataSource(dataSource => dataSource.Server()
.Read(read => read.Action("Read", "Home", new { userID = (int)ViewData["UserID"]
}))
)
// Omitted for brevity.
If the Grid is Ajax-bound, use the Data method to specify the name of the JavaScript function, which
will return the additional data.
The following example demonstrates how to send additional data in an Ajax-bound Grid.
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.Read(read => read
.Action("Read", "Home")
.Data("additionalData")
)
)
// Omitted for brevity.
<script>
function additionalData() {
return {
userID: 42,
search: $("#search").val()
};
}
</script>
The property names of the object that are passed as additional data must not match the property
names in the ViewModel. Otherwise, the MVC binder will not recognize which property corresponds
to the ViewModel and which to the additional data object.
var grid = $("#Grid").data("kendoGrid");
grid.dataSource.read();
245
Telerik UI for ASP.NET Core
To flatten your data, use View Model objects, reduce the number of serialized properties, or avoid
circular reference serializaton exceptions.
The following example demonstrates how to convert the processed data.
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var northwind = new NorthwindDataContext();
var orders = northwind.Orders;
var result = orders.ToDataSourceResult(request, o => new {
OrderID = o.OrderID,
CustomerName = o.Customer.ContactName
});
}
// Models.
public class Order
{
public int OrderID { get; set; }
// This property creates a circular reference because of the Customer class.
// Refers to the Order class through the Orders property.
public Customer Customer { get; set; }
}
public class Customer
{
public string ContactName { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
// Action.
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var northwind = new NorthwindDataContext();
var orders = northwind.Orders;
// Avoid the circular reference by creating a View Model object and skipping the
Customer property.
var result = orders.ToDataSourceResult(request, o => new {
OrderID = o.OrderID,
CustomerName = o.Customer.ContactName
});
}
246
Telerik UI for ASP.NET Core
The following example demonstrates how to handle errors in the Ajax binding mode.
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.Events(events => events.Error("onError"))
// Omitted for brevity.
<script>
function onError(e, status) {
alert("A server error has occurred!");
}
</script>
The following example demonstrates how to perform paging, sorting, filtering, and grouping in
memory.
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.ServerOperation(false)
// Omitted for brevity.
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult MyReadMethod()
{
247
Telerik UI for ASP.NET Core
/* ... */
}
Configure the Kendo UI DataSource to make POST instead of GET Ajax requests for the Read
action.
Use jQuery's ajaxSetupconfiguration method. This influences all Ajax requests that the web
application performs.
$.ajaxSetup ({
cache: false
});
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.Events(events => events.Error("onError"))
// Omitted for brevity.
<script>
function onError(e, status) {
if (e.errors) {
var message = "The following errors have occurred:\n";
$.each(e.errors, function(key, value) {
if (value.errors) {
message += value.errors.join("\n");
}
});
alert(message);
}
}
</script>
The Custom Object Templatesblog post contains a lot of information about creating a custom editor
248
Telerik UI for ASP.NET Core
template.
The Html.EditorForModel is used only in popup edit mode. In-cell and in-line edit modes use
Html.EditorFor and pass the expression used to declare the bound column—for example,
Html.EditorFor(o => o.OrderDate).
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.Model(model =>
{
model.Field(p => p.Name).DefaultValue("N/A");
model.Field(p => p.Price).DefaultValue(9.99);
})
// Omitted for brevity.
The following example demonstrates how to create a custom helper that wraps the Grid
configurator.
public static class Extensions
{
public static GridBuilder<T> MyGrid<T>(this HtmlHelper helper)
where T: class
{
return helper.Kendo().Grid<T>()
.Scrollable();
}
}
@using TheNamespaceOfTheExtensionsClass
249
Telerik UI for ASP.NET Core
@(Html.MyGrid.Name("foo")) // The Grid is already configured to be Scrollable
If you want to avoid adding the using statement in each view this Html helper is used, add a
namespace reference to the Web.config file inside the Views folder of your MVC project.
The following example demonstrates the Read-only property through the ReadOnly attribute.
public class Order
{
[ReadOnly(true)]
public int OrderID { get; set; }
}
The following example demonstrates the Read-only property through the Editable method.
// Omitted for brevity.
.DataSource(dataSource => dataSource.Ajax()
.Model(model =>
{
model.Field(o => o.OrderID).Editable(false);
})
// Omitted for brevity.
The ReadOnly and Editable settings work only in in-line and in-cell editing modes. Use a custom
popup editor if you want to exclude certain properties from the editor form.
250
Telerik UI for ASP.NET Core
@(Html.Kendo().DateTimePicker()
.Value(DateTime.Now)
.DateInput()
)
public class Order
{
public int OrderID { get; set; }
public string ShipCountry { get; set; }
[UIHint("KendoDateEditor")]
public Date OrderDate { get; set; }
}
@(Html.Kendo().NumericTextBox()
.Round(false)
.Spinners(false)
)
public class Order
{
public int OrderID { get; set; }
public string ShipCountry { get; set; }
[UIHint("KendoNumberEditor")]
public decimal Price { get; set; }
}
See Also
251
Telerik UI for ASP.NET Core
252
Telerik UI for ASP.NET Core
Grid Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
Internationalization
Localization of messages
Right-to-left support
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
Globalization of the Grid HtmlHelper for ASP.NET Core (Demo)
RTL Support by the Grid HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
Server-Side API
253
Telerik UI for ASP.NET Core
Internationalization
The internationalization process applies specific culture formats to a web application by providing
options for the parsing and formatting of dates and numbers.
See also
Localization of Messages
Globalization in Telerik UI for ASP.NET Core
254
Telerik UI for ASP.NET Core
Localization
The Grid provides options for localizing its user interface by utilizing the available Resources
messages as well as providing custom messages as part of its configuration.
Getting Started
To use the community-sources Resources files, override the executing context and set the
server-side culture. This causes the ASP.NET Core Grid to use the matching Resource file messages
and localize them accordingly. In case of missing messages, you can update the Resources file or
include the message in the configuration of the grid.
using Microsoft.AspNetCore.Mvc.Filters;
using System.Globalization;
public override void OnActionExecuting(ActionExecutingContext context)
{
CultureInfo.DefaultThreadCurrentCulture =
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("fr-FR");
base.OnActionExecuting(context);
}
3. Match the client-side culture. By including the Kendo UI culture scripts, the number formats,
the week and month names, the date and time formats, and so on will match the server-side
culture and prevent validation errors. The culture scripts are generated from the Windows 10
and .NET 4.7 server-side culture definitions and match them by design.
<script
src="http://kendo.cdn.telerik.com/2019.3.1023/js/cultures/kendo.culture.fr-FR.m
in.js">
<!-- include the call to the kendo.culture() method before any widgets are
initialized -->
<script>kendo.culture("fr-FR");</script>
@(Html.Kendo().Grid<OrderViewModel>()
/* grid definition */
)
255
Telerik UI for ASP.NET Core
Toolbar Messages
The following example demonstrates how to implement the custom translation of the toolbar
messages in the Grid by using the Toolbar.[Command].Text() method.
@(Html.Kendo().Grid<AspNetCoreGrid.Models.OrderViewModel>()
.ToolBar(tools=>
{
tools.Pdf().Text("Custom PDF button text");
tools.Excel().Text("Custom Excel button text");
tools.Save().Text("Custom Save Changes button text");
tools.Create().Text("Custom Create button text");
})
Menu Messages
The following example demonstrates how to implement the message translation of the column
menu in the Grid by using the ColumnMenu.Messages() method.
.ColumnMenu(colMenu=>colMenu.Messages(messages=> {
messages.SortAscending("Custom Sort Asc Message");
messages.SortDescending("Custom Sort Asc Message");
messages.Columns("Custom Columns Message");
messages.Filter("Custom Column Filter message");
messages.Lock("Custom Column Lock message");
})
)
Command Messages
The following example demonstrates how to implement the translation of the column command
messages in the Grid by using the command Columns.[Command].Text() method.
.Columns(columns =>
{
columns.Bound(f => f.OrderID).Width(200);
columns.Bound(f => f.ShipCountry).Width(200);
columns.Command(command =>
{
command.Edit().Text("Custom Edit button text");
command.Destroy().Text("Custom Destroy button text");
});
})
Filter Messages
The following example demonstrates how to implement the translations of the filter menu and
operator messages in the Grid by using the Filterable.Messages() and
Filterable.Operators.For[Type]() methods.
256
Telerik UI for ASP.NET Core
.Filterable(filterable => {
filterable.Messages(messages =>
{
messages.Info("My Info");
messages.Clear("My Clear");
messages.Or("My Or");
messages.And("My and");
messages.IsTrue("My Custom True");
messages.Operator("my custom operator message");
/* and others */
});
filterable.Operators(op => {
op.ForString(strop=> {
strop.Clear(); // default filter operator
strop.Contains("My Contains");
});
});
})
.Groupable(groupable=> {
groupable.Messages(messages =>
{
messages.Empty("My Drag Here to group by column message");
});
})
Pager Messages
The following example demonstrates how to implement the translations of the pager messages in
the Grid. For more information, refer to the messagesAPI reference.
.Pageable(pageable=> {
pageable.Refresh(true);
pageable.Messages(messages => {
messages.Refresh("My Refresh");
messages.Next("My Next");
messages.Last("My Last");
messages.Display("My {0} - {1} of {2} items"); // {0} is the index of the first
record on the page, {1} - the index of the last")
/* and others */
});
})
See Also
Localization Support by the Grid HtmlHelper for ASP.NET Core (Demo)
RTL Support by the Grid HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
257
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the Grid HtmlHelper for ASP.NET Core.
See Also
Localization Support by the Grid HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
258
Telerik UI for ASP.NET Core
Grid Accessibility
The Grid is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in UI for ASP.NET Core.
Section 508
The Grid is compliant with the Section 508 requirements. For more information, refer to the article on
Section 508 support in Kendo UI for jQuery.
WCAG 2.1
The Grid supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1.
See Also
WCAG 2.1 Support by the Grid HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Grid HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Grid HtmlHelper for ASP.NET Core
Accessibility Compliance in Telerik UI for ASP.NET Core
259
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Grid is always available.
For a complete example, refer to the demo on using the keyboard navigation of the Grid.
The Grid supports its keyboard navigation functionality through the Navigatable() method. When
enabled, you can initially select a row or cell and then move within the Grid by using the Arrow keys.
The navigation occurs at a cell level regardless of what the Selectable() mode is. To select the
current row or cell, press Space.
The following example demonstrates how to enable the key navigation in the Grid.
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("grid")
/* Other configuration. */
.Navigatable()
)
The keyboard navigation of the Grid works by listening to the keydown events on the wrapper
element of the helper. Its behavior is based on the assumption that whatever the user does is in
accordance with the currently focused Grid cell and not with the focused element of the browser. If
the data cells of the Grid contain hyperlinks that have to be activated through the keyboard:
To return the focus on the table cell, press Esc. In order for the hyperlinks to be inaccessible through
tabbing, set the tabindex="-1" attribute to the custom hyperlinks.
You can also avoid the procedure and bypass the keyboard navigation of the Grid, access the
custom hyperlinks with tabbing, and activate them with Enter. To achieve this, prevent the keydown
event bubbling of the custom hyperlinks. As a result, the Enter key-presses will be unnoticed by the
Grid.
See Also
Keyboard Navigation by the Grid HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
260
Telerik UI for ASP.NET Core
The ListView enables you to display a custom layout of data-bound items. The ListView is ideally
suited for displaying a list of items in a consistent manner. You can see commonplace examples of
its use in the design structures of the Internet, search engine results, tweets from Twitter, Facebook
updates, inbox items in Gmail, card lists in Trello, and so on.
The ListView enables you to control the display of data. It does not provide a default rendering of
data-bound items. Instead, it relies on templates to define the way a list of items is displayed,
including alternating items and items that are in the process of editing.
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the widget.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used on paging.
.Pageable() // Enable paging.
)
Basic Configuration
The following example demonstrates the basic configuration for the ListView HtmlHelper.
<script type="text/x-kendo-tmpl" id="template">
261
Telerik UI for ASP.NET Core
<div class="product-view k-widget">
<dl>
<dt>Product Name</dt>
<dd>#:ProductName#</dd>
<dt>Unit Price</dt>
<dd>#:kendo.toString(UnitPrice, "c")#</dd>
<dt>Units In Stock</dt>
<dd>#:UnitsInStock#</dd>
<dt>Discontinued</dt>
<dd>#:Discontinued#</dd>
</dl>
<div class="edit-buttons">
<a class="k-button k-edit-button" href="\\#"><span class="k-icon
k-i-edit"></span></a>
<a class="k-button k-delete-button" href="\\#"><span class="k-icon
k-i-delete"></span></a>
</div>
</div>
</script>
@(Html.Kendo().ListView<Kendo.Mvc.Examples.Models.ProductViewModel>(Model)
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource => dataSource
.Model(model => model.Id("ProductID"))
.PageSize(4)
.Read(read => read.Action("Editing_Read", "ListView"))
.Update(update => update.Action("Editing_Update", "ListView"))
.Destroy(destroy => destroy.Action("Editing_Destroy", "ListView"))
)
.Pageable()
.Editable()
)
See Also
Basic Usage of the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
262
Telerik UI for ASP.NET Core
Ajax Binding
When configured for Ajax binding, the ListView for ASP.NET Core makes Ajax requests when doing
paging.
Getting Started
To configure the ListView for ASP.NET Core for Ajax binding:
1. Add a new action method which returns data to populate the ListView. Note that the action
method has a parameter of type Kendo.Mvc.UI.DataSourceRequest. It will contain the
current ListView request information. Decorate that parameter with the
Kendo.Mvc.UI.DataSourceRequestAttribute. This attribute is responsible for
populating the DataSourceRequest object.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
// The result can be any IEnumerable or IQueriable.
var result = myService.Orders;
var dsResult = result.ToDataSourceResult(request);
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
// Get orders from the service.
var orders = myService.Orders;
// Apply the requested sort, page, group, filtering with the
ToDataSourceResult() extension method.
var dsResult = orders.ToDataSourceResult(request);
return Json(dsResult);
}
263
Telerik UI for ASP.NET Core
4. In the view, configure the ListView to use the action method created in the previous steps.
You may use the sample model and data from the following example. The
ToDataSourceResult method uses the DataSourceRequest parameter and Linq
expressions to apply paging, sorting, filtering, and grouping. The JSON response of the
action method will contain only a single page of data. The ListView will be bound to that
data.
@(Html.Kendo().ListView<ListViewCore.Models.OrderViewModel>()
.Name("ListView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("Orders_Read", "ListView"))
)
.Pageable()
)
<script type="text/x-kendo-tmpl" id="template">
<div class="order">
<h3>#= OrderID #</h3>
<dl>
<dt>Ship Name:</dt>
<dd>#= ShipName #</dd>
</dl>
<dl>
<dt>Ship City:</dt>
<dd>#= ShipCity #</dd>
</dl>
<dl>
<dt>Freight:</dt>
<dd>#= kendo.toString(Freight, "n2")#</dd>
</dl>
<dl>
<dt>Order Date:</dt>
<dd>#= kendo.toString(OrderDate, "D")#</dd>
</dl>
</div>
</script>
<style>
.order {
float: left;
width: 30%;
height: 300px;
position: relative;
margin-left: 30px;
text-align:center;
}
</style>
public class OrderViewModel
{
264
Telerik UI for ASP.NET Core
public int OrderID
{
get;
set;
}
public decimal? Freight
{
get;
set;
}
public DateTime? OrderDate
{
get;
set;
}
public string ShipCity
{
get;
set;
}
public string ShipName
{
get;
set;
}
}
public class ListViewController : Controller
{
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest
request)
{
// The result can be any IEnumerable or IQueriable.
// This is just an example that you can copy and paste.
var result = Enumerable.Range(0, 50).Select(i => new OrderViewModel
{
OrderID = i,
Freight = i * 10,
OrderDate = new DateTime(2016, 9, 15).AddDays(i % 7),
ShipName = "ShipName " + i,
ShipCity = "ShipCity " + i
});
var dsResult = result.ToDataSourceResult(request);
return Json(dsResult);
}
}
265
Telerik UI for ASP.NET Core
additional data.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request,
string firstName, string lastName)
{
// The implementation is omitted for brevity.
}
@(Html.Kendo().ListView<ListViewCore.Models.OrderViewModel>()
.Name("ListView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("Orders_Read",
"ListView").Data("additionalData"))
)
.Pageable()
)
<script>
function additionalData() {
return {
firstName: "John",
lastName: "Doe"
};
}
</script>
.DataSource(dataSource => dataSource
.ServerOperation(false) // All data will be requested at once and data operations
will be applied client-side.
.Read(read => read.Action("Orders_Read", "ListView"))
)
See Also
Binding to Remote Data by the ListView HtmlHelper for ASP.NET Core (Demo)
Customizing the Data Source of the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
266
Telerik UI for ASP.NET Core
Editing
The Telerik UI ListView for ASP.NET Core enables you to edit its records.
namespace ListViewExample.Models
{
public class OrderViewModel
{
public int OrderID
{
get;
set;
}
public decimal? Freight
{
get;
set;
}
[Required]
public DateTime? OrderDate
{
get;
set;
}
[Required]
public string ShipCity
{
get;
set;
}
[Required]
public string ShipName
{
get;
set;
}
}
}
267
Telerik UI for ASP.NET Core
click events for elements with k-edit-button and k-delete-button class names will be
automatically handled and treated by the Telerik UI ListView as update and destroy actions. To
facilitate the create operation add a click handler to the k-add-button, get the Telerik UI ListView
instance and call the add()method.
<!-- Button for the Create operation. Use it to call the client ListView method add()
-->
<a class="k-button k-button-icontext k-add-button" href="#"><span class="k-icon
k-add"></span>Add new record</a>
@(Html.Kendo().ListView<ListViewExample.Models.OrderViewModel>()
/* listview configuration */
)
<script>
$(function () {
var listView = $("#listView").data("kendoListView");
$(".k-add-button").click(function (e) {
listView.add();
e.preventDefault();
});
});
</script>
<script type="text/x-kendo-tmpl" id="template">
<div class="order">
<h3>#= OrderID #</h3>
<dl>
<dt>Ship Name:</dt>
<dd>#= ShipName #</dd>
</dl>
<dl>
<dt>Ship City:</dt>
<dd>#= ShipCity #</dd>
</dl>
<dl>
<dt>Freight:</dt>
<dd>#= kendo.toString(Freight, "n2")#</dd>
</dl>
<dl>
<dt>Order Date:</dt>
<dd>#= kendo.toString(OrderDate, "D")#</dd>
</dl>
<!-- The following markup contains the `Edit` and `Delete` buttons -->
<div class="edit-buttons">
<a class="k-button k-edit-button" href="\\#"><span class="k-icon
k-i-edit"></span></a>
<a class="k-button k-delete-button" href="\\#"><span class="k-icon
k-i-delete"></span></a>
</div>
</div>
268
Telerik UI for ASP.NET Core
</script>
1. Declare the editor template in a file that uses the name of the edited model—for example,
OrderViewModel.cshtml.
2. Place this file in the ~Views\Shared\EditorTemplates directory of your project.
click events for elements with k-update-button and k-cancel-button class names will be
automatically handled and treated by the Telerik UI ListView as save and cancel actions. Similar to
the item template, you have to wrap the editor template in an HTML container.
@model ListViewExample.Models.OrderViewModel
<div class="order">
<h3 data-bind="text:OrderID"></h3>
<dl>
<dt>Ship Name:</dt>
<dd>
@(Html.Kendo().TextBoxFor(o => o.ShipName))
</dd>
<dt>Ship City:</dt>
<dd>
@(Html.Kendo().TextBoxFor(o => o.ShipCity))
</dd>
<dt>Freight</dt>
<dd>
@(Html.Kendo().NumericTextBoxFor(o => o.Freight))
</dd>
<dt>Order Date:</dt>
<dd>
@(Html.Kendo().DatePickerFor(o => o.OrderDate))
<span data-for="OrderDate" class="k-invalid-msg"></span>
</dd>
</dl>
<div class="edit-buttons">
<a class="k-button k-button-icontext k-update-button" href="\\#"><span
class="k-icon k-i-check"></span></a>
<a class="k-button k-button-icontext k-cancel-button" href="\\#"><span
class="k-icon k-i-cancel"></span></a>
</div>
</div>
<style>
span.k-tooltip {
position:absolute;
margin:6px;
}
</style>
269
Telerik UI for ASP.NET Core
@(Html.Kendo().ListView<ListViewExample.Models.OrderViewModel>()
.Name("listView")
.TagName("div")
.ClientTemplateId("list-view-template")
.Editable() //<-- Enable editing.
)
@(Html.Kendo().ListView<ListViewExample.Models.OrderViewModel>()
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.Editable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(4)
.Model(m => m.Id("OrderID"))
.Read(read => read.Action("Orders_Read", "ListView"))
.Create(create => create.Action("Orders_Create", "ListView"))
.Update(update => update.Action("Orders_Update", "ListView"))
.Destroy(destroy => destroy.Action("Orders_Destroy", "ListView"))
)
.Pageable()
)
For a quick test add a static list and copy and paste it in the controller, or use own service or data
base which returns an IEnumerable or IQueriable.
public class ListViewController : Controller
{
public static List<OrderViewModel> dbOrders = Enumerable.Range(1, 20).Select(i =>
new OrderViewModel
{
OrderID = i,
Freight = i * 10,
OrderDate = new DateTime(2016, 9, 15).AddDays(i % 7),
ShipName = "ShipName " + i,
ShipCity = "ShipCity " + i
}).ToList();
}
The following example demonstrates how to implement the read action method.
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
var dsResult = dbOrders.ToDataSourceResult(request);
return Json(dsResult);
}
270
Telerik UI for ASP.NET Core
The following example demonstrates how to implement the create action method.
public ActionResult Orders_Create([DataSourceRequest] DataSourceRequest request,
OrderViewModel order)
{
if (order != null && ModelState.IsValid)
{
// Own update logic or use with sample data to test.
var nextId = dbOrders.Count + 1;
order.OrderID = nextId;
dbOrders.Add(order);
}
// Return any validation errors, if any.
return Json(new [] { order }.ToDataSourceResult(request, ModelState));
}
The following example demonstrates how to implement the update action method.
public ActionResult Orders_Update([DataSourceRequest] DataSourceRequest request,
OrderViewModel order)
{
if (order != null && ModelState.IsValid)
{
// Own create logic or use with sample data to test.
for (int i = 0; i < dbOrders.Count; i++)
{
if (order.OrderID == dbOrders[i].OrderID)
{
dbOrders[i] = order;
}
}
}
// Return any validation errors, if any.
return Json(new[] { order }.ToDataSourceResult(request, ModelState));
}
The following example demonstrates how to implement the destroy action method.
public ActionResult Orders_Destroy([DataSourceRequest] DataSourceRequest request,
OrderViewModel order)
{
if (order != null)
{
// Own destroy logic or use with sample data to test.
for (int i = 0; i < dbOrders.Count; i++)
{
if (order.OrderID == dbOrders[i].OrderID)
{
dbOrders.Remove(dbOrders[i]);
break;
}
271
Telerik UI for ASP.NET Core
}
}
// Return any validation errors, if any.
return Json(new[] { order }.ToDataSourceResult(request, ModelState));
}
See Also
Editing by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
272
Telerik UI for ASP.NET Core
Paging
By default, paging in the ListView is disabled.
When the number of items that are bound to a ListView is larger than expected, a pager will control
the items that are displayed. By default, the ListView displays a pager even when the total amount of
its data source items is less than the PageSize value.
Getting Started
To enable the paging functionality of the ListView:
```Template
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
```
```Razor
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to
the Model which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It
specifies the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It
specifies the element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering
the ListView items.
.Scrollable()
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
```
```Template
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
273
Telerik UI for ASP.NET Core
</dl>
</div>
</script>
```
```Razor
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to
the Model which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It
specifies the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It
specifies the element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering
the ListView items.
.Scrollable()
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
dataSource.PageSize(4); // Set the page size for the ListView.
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
```
See Also
Paging by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
274
Telerik UI for ASP.NET Core
Templates
The Telerik UI ListView for ASP.NET Core uses templates to visualize its data items in a consistent
manner.
In order for the ListView to function seamlessly, defining its templates is mandatory.
Getting Started
To set the template, refer it when you initialize the ListView. The template displays the result that is
set by the service.
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Scrollable()
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
275
Telerik UI for ASP.NET Core
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.ClientAltTemplateId("altTemplate") // This template will be used for the
alternating items in the ListView.
.Scrollable()
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<img src="https://demos.telerik.com/kendo-ui/content/web/foods/#= ProductID
#.jpg" alt="#: ProductName # image" />
<h3>#:ProductName#</h3>
<p>#:kendo.toString(UnitPrice, "c")#</p>
</div>
</script>
<script type="text/x-kendo-tmpl" id="altTemplate">
<div class="product alt">
<img src="https://demos.telerik.com/kendo-ui/content/web/foods/#= ProductID
#.jpg" alt="#: ProductName # image" />
<h3>#:ProductName#</h3>
<p>#:kendo.toString(UnitPrice, "c")#</p>
</div>
</script>
See Also
Templates in the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
Editor Template for the ListView HtmlHelper for ASP.NET Core
276
Telerik UI for ASP.NET Core
Scroll Modes
By default, the scrolling functionality of the Telerik UI ListView for ASP.NET Core is disabled.
Getting Started
To control scrolling in the ListView, use its Scrollable property.
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Scrollable()
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
Endless Scrolling
The endless scrolling functionality enables the ListView to display large amounts of data by
appending additional pages of data on demand. The loading of new items happens when the
scrollbar of the ListView reaches its end. When the data is returned, only the new items are rendered
and appended to the old ones. The endless scrolling of the ListView works with both local and
remote data. For a runnable example, refer to the demo on endless scrolling by the ListView.
The following example demonstrates how to enable the endless scroll mode of the ListView by
setting the Scrollable property to the Endless value of the ListViewScrollableMode enum.
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
277
Telerik UI for ASP.NET Core
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Scrollable(ListViewScrollableMode.Endless)
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
See Also
Endless Scrolling by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
278
Telerik UI for ASP.NET Core
Selection
By default, the selection functionality of the Telerik UI ListView for ASP.NET Core is disabled.
Single Selection
The single selection functionality allows the user to select only one item at a time.
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Scrollable()
.Selectable(ListViewSelectionMode.Single) // Set the selection mode to single.
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
Multiple Selection
The multiple selection functionality allows the user to select one or more items at a time.
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the ListView.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Scrollable()
.Selectable(ListViewSelectionMode.Multiple) // Set selection mode to multiple
.HtmlAttributes(new { style="height:350px;" })
.DataSource(dataSource => {
dataSource.Read(read => read.Action("Products_Read", "ListView"));
279
Telerik UI for ASP.NET Core
}) // The DataSource configuration. It will be used for paging.
.Pageable() // Enable paging.
)
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
See Also
Selection by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
280
Telerik UI for ASP.NET Core
ListView Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
The globalization functionality of the ListView is enabled through its right-to-left support.
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
RTL Support by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
281
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the ListView.
See Also
Server-Side API
282
Telerik UI for ASP.NET Core
ListView Accessibility
The ListView is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on accessibility support in Telerik UI for ASP.NET Core.
Section 508
The ListView is compliant with the Section 508 requirements. For more information, refer to the
article on accessibility support in Telerik UI for ASP.NET Core.
WCAG 2.1
The ListView supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on accessibility support
in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the ListView HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the ListView HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
283
Telerik UI for ASP.NET Core
Keyboard Navigation
By default, the keyboard navigation of the ListView HtmlHelper is disabled.
The ListView supports its keyboard navigation functionality through the Navigatable option. When
set to true, you can initially select an item and then move within the ListView by using the Arrow
keys. The navigation occurs at item level regardless of what the selectable mode is. To select the
current item, press Space.
The following example demonstrates how to enable the key navigation in the ListView.
@(Html.Kendo().ListView(Model) // The ListView will be initially bound to the Model
which is the Products table.
.Name("productListView") // The name of the ListView is mandatory. It specifies
the "id" attribute of the widget.
.TagName("div") // The tag name of the ListView is mandatory. It specifies the
element which wraps all ListView items.
.ClientTemplateId("template") // This template will be used for rendering the
ListView items.
.Navigatable()
.HtmlAttributes(new { style="height:350px;" })
)
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<h3>#=ProductName#</h3>
<dl>
<dt>Price:</dt>
<dd>#=kendo.toString(UnitPrice, "c")#</dd>
</dl>
</div>
</script>
See Also
Keyboard Navigation by the ListView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
284
Telerik UI for ASP.NET Core
Basic Configuration
To configure the PivotGrid for Ajax binding to an Adventure Works cube that is hosted on
https://demos.telerik.com/olap/msmdpump.dll:
1. Create a new ASP.NET Core application. If you have the Telerik UI for ASP.NET Core Visual
Studio Extensionsinstalled, create a Telerik UI for ASP.NET Core application. Name the
application KendoPivotGrid. If you decide not to use the Telerik UI for ASP.NET Core
Visual Studio Extensions, follow the steps from the introductory articleto add Telerik UI for
ASP.NET Core to the application.
2. Add a PivotGrid to the Index view.
@(Html.Kendo().PivotGrid()
.Name("pivotgrid")
.DataSource(dataSource => dataSource.
Xmla()
.Columns(columns => {
columns.Add("[Date].[Calendar]").Expand(true);
columns.Add("[Geography].[City]");
})
.Rows(rows => rows.Add("[Product].[Product]"))
.Measures(measures => measures.Values(new string[]{"[Measures].[Internet
Sales Amount]"}))
.Transport(transport => transport
.Connection(connection => connection
.Catalog("Adventure Works DW 2008R2")
.Cube("Adventure Works"))
.Read(read => read
.Url("https://demos.telerik.com/olap/msmdpump.dll")
.DataType("text")
.ContentType("text/xml")
.Type(HttpVerbs.Post)
)
)
)
)
285
Telerik UI for ASP.NET Core
Data binding
Filtering
Sorting
Templates
Excel export
PDF export
var pivotgrid = $("#pivotgrid").data("kendoPivotGrid");
See Also
Basic Usage of the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
286
Telerik UI for ASP.NET Core
Data Binding
The PivotGrid for ASP.NET Core supports Ajax data binding to an HTTP accessible Online Analytical
Processing (OLAP) cube and to flat data.
Telerik UI provides an OLAP service dll that can be used for testing and is hosted at
https://demos.telerik.com/olap/msmdpump.dll. To see the responses, the service needs to
be queried and cannot be opened directly in the browser. For more information on binding the
PivotGrid to data over an OLAP cube, refer to the following articles:
When the PivotGrid is bound to flat data, it creates a client-side cube which allows the categorization
of the flat data. For runnable examples on binding the PivotGrid to flat data, refer to the following
online demos:
See Also
Local Data Binding by the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Remote Data Binding by the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
287
Telerik UI for ASP.NET Core
OLAP Fundamentals
The PivotGrid resembles a pivot tablethat uses Online Analytical Processing (OLAP) concepts for
representing multidimensional data.
What Is OLAP?
OLAP is an acronym that stands for Online Analytical Processing. It allows access to data that is
aggregated and organized in a multidimensional structure that is called a "cube". OLAP tools enable
users to interactively perform analysis over multidimensional data.
What Is XMLA?
XMLA is an acronym that stands for XML for Analysis. XMLA is a protocol that is designed for
universal data access to a multidimensional data source which resides on the Web. For more
information, refer to this article.
The PivotDataSourceconfiguration provides built-in support for XMLA by using specific XMLA
transport and schema options.
See Also
288
Telerik UI for ASP.NET Core
289
Telerik UI for ASP.NET Core
Installing SSAS
For more information on installing the SQL Server Analysis Services, refer to the MSDN tutorial.
For more information on setting up the MSMDPUMP.ddl extension, refer to the MSDN HTTP
access tutorial.
For an online accessible OLAP service for testing purposes, use
http://demos.telerik.com/olap/msmdpump.dll. The URL does not open directly in the
browser.
The following sections demonstrate how to enable CORS on an Internet Information Services (IIS)
server. Cross-domain access requires you to configure the HTTP Response Headers and the
OPTIONS method server response.
290
Telerik UI for ASP.NET Core
The following example demonstrates the list of the HTTP Response Headers that show the settings
which are required to enable the IIS CORS behavior.
Access-Control-Allow-Origin The URI names that may The names of the allowed
access the resource. When an domains have to be separated
asterisk (*) is defined, all with a comma (,).
domains are allowed.
Access-Control-Request-Met POST The name of the HTTP
hod method that will be used in
the actual request.
291
Telerik UI for ASP.NET Core
The following example demonstrates the list of settings that you have to apply.
Use a proxy service which communicates with the cube on a secured protocol. This proxy
has to support the XMLA protocol. In the Microsoft world, the solution is to use ADOMD.NET.
For more information, refer to this forum thread.
Send the credentials with a request header even though the Username and Password will be
visible on the client side (browser). For more information on passing credentials with request
headers, refer to this StackOverflow discussion. You can define the required callbacks and
settings directly in the transport.readobject because they will be passed to the $.ajax
method.
See Also
OLAP Cube Fundamentals
PivotConfigurator Overview
292
Telerik UI for ASP.NET Core
PivotConfigurator Overview
The Telerik UI PivotConfigurator HtmlHelper for ASP.NET Corerepresents an OLAP cube structure.
The PivotConfigurator can be used for configuring the column and row dimensions, and the measure
fields of the PivotGrid. It is a supplementary component which is strongly related to the Telerik UI
PivotDataSource.
@(Html.Kendo().PivotConfigurator()
.Name("configurator")
.Filterable(true)
.Height(570)
)
@(Html.Kendo().PivotGrid()
.Name("pivotgrid")
.Height(570)
.Filterable(true)
.Configurator("#configurator")
// Other configuration.
)
Basic Configuration
The following example demonstrates how to configure the PivotConfigurator.
@(Html.Kendo().PivotConfigurator()
.Name("configurator")
.Filterable(true)
.Sortable()
.Height(570)
)
@(Html.Kendo().PivotGrid()
.Name("pivotgrid")
.ColumnWidth(200)
.Height(570)
.Filterable(true)
.Sortable()
.Configurator("#configurator")
.DataSource(dataSource => dataSource.
Xmla()
.Columns(columns => {
columns.Add("[Date].[Calendar]").Expand(true);
columns.Add("[Product].[Category]");
})
.Rows(rows => rows.Add("[Geography].[City]"))
.Measures(measures => measures.Values(new string[]{"[Measures].[Reseller
293
Telerik UI for ASP.NET Core
Freight Cost]"}))
.Transport(transport => transport
.Connection(connection => connection
.Catalog("Adventure Works DW 2008R2")
.Cube("Adventure Works"))
.Read(read => read
.Url("https://demos.telerik.com/olap/msmdpump.dll")
.DataType("text")
.ContentType("text/xml")
.Type(HttpVerbs.Post)
)
)
.Events(e => e.Error("onError"))
)
)
The following image demonstrates the output from the previous example.
var pivotconfigurator = $("#pivotconfigurator").data("kendoPivotConfigurator");
See Also
OLAP Cube Fundamentals
OLAP Cube Setup
294
Telerik UI for ASP.NET Core
Filtering
The PivotGrid supports filtering both in the OLAP and flat data-binding scenarios.
The filter descriptor is similar to the filter option of the kendo.data.DataSourceand contains the
following options:
See Also
Basic Usage of the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
295
Telerik UI for ASP.NET Core
Sorting
The PivotGrid supports sorting only in the OLAP data-binding scenario.
The PivotGrid supports sorting by the caption name of the members. The structure of the sort
descriptor is similar to the sort option of the kendo.data.DataSourceand contains the following
options:
All inner members of the sorted dimension will be sorted with the same sort dimension.
See Also
Basic Usage of the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
296
Telerik UI for ASP.NET Core
Templates
The Telerik UI PivotGrid HtmlHelper for ASP.NET Core provides templating options that can be used
to customize the way its data is visualized in the table.
Under the hood, the templates use the Kendo UI Templates syntax.
To use templates in the PivotGrid, apply any of the available template options:
In the data cell template, you can use the following fields:
In the column header template, you can use the following fields:
297
Telerik UI for ASP.NET Core
The row header template is the templatewhich renders the content of the row header cell. By default,
it renders the caption of the tuple member.
In the row header template, you can use the following fields:
See Also
Templates in the Telerik UI PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-side API
298
Telerik UI for ASP.NET Core
Excel Export
The PivotGrid enables you to export its content to Excel.
By default, the Excel export is enabled when kendo.ooxml.min.js is loaded on the page.
kendo.ooxml.min.js is included in kendo.all.min.js and kendo.web.min.js.
2. In the handler, manipulate the generated workbook. The example alternates the background
color of the rows cells.
<script>
function excelExport(e) {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
if (rowIndex % 2 == 0) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
299
Telerik UI for ASP.NET Core
row.cells[cellIndex].background = "#aabbcc";
}
}
}
}
</script>
Using Templates
The PivotGrid does not use dataCellTemplate, columnHeaderTemplate, and
rowHeaderTemplate during Excel export and exports only its data because the templates may
contain arbitrary HTML which cannot be converted to Excel column values.
See Also
Excel Export by the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
300
Telerik UI for ASP.NET Core
PDF Export
As of the 2015 Q1 release, the PivotGrid HtmlHelper provides a built-in PDF export functionality.
To customize the appearance of the exported PDF file, refer to the articles on the PDF output by the
Kendo UI Drawing library.
See Also
PDF Export by the PivotGrid HtmlHelper for ASP.NET Core (Demo)
Server-Side API
301
Telerik UI for ASP.NET Core
The Spreadsheet allows you to edit and visualize tabular data by using cell formatting options,
styles, and themes.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Sheets(sheets => {
sheets.Add()
.Name("Food Order")
.MergedCells("A1:F1", "C15:E15")
.Columns(columns =>
{
columns.Add().Width(100);
columns.Add().Width(215);
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(155);
})
.Rows(rows =>
{
rows.Add().Height(50).Cells(cells =>
{
cells.Add()
.Value("My Company")
.FontSize(25)
.Background("rgb(142,196,65)")
.TextAlign(SpreadsheetTextAlign.Center)
.Color("white");
});
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Product")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
302
Telerik UI for ASP.NET Core
.Value("Quantity")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Price")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Tax")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Amount")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
});
});
})
)
public class SpreadsheetController : Controller
{
public ActionResult Index()
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration for the Spreadsheet HtmlHelper.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Rows(10)
.Columns(10)
.Sheetsbar(true)
.Toolbar(true)
.HtmlAttributes(new { style = "width:100%" })
.Toolbar(t => t.Home(true).Data(false).Insert(false))
.Excel(excel => excel
.ProxyURL(Url.Action("Index_Save", "Spreadsheet"))
)
.Pdf(pdf => pdf
.ProxyURL(Url.Action("Index_Save", "Spreadsheet"))
)
.Sheets(sheets =>
{
sheets.Add()
.Name("Food Order")
.MergedCells("A1:F1", "C15:E15")
.Columns(columns =>
{
columns.Add().Width(100);
columns.Add().Width(215);
303
Telerik UI for ASP.NET Core
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(155);
})
.Rows(rows =>
{
rows.Add().Height(50).Cells(cells =>
{
cells.Add()
.Value("My Company")
.FontSize(25)
.Background("rgb(142,196,65)")
.TextAlign(SpreadsheetTextAlign.Center)
.Color("white");
});
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Product")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Quantity")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Price")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Tax")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Amount")
.Background("rgb(212,223,50)")
.TextAlign(SpreadsheetTextAlign.Center);
});
});
})
)
304
Telerik UI for ASP.NET Core
Events
You can subscribe to all Spreadsheet events. For a complete example on basic Spreadsheet events,
refer to the demo on using the events of the Spreadsheet.
The following example demonstrates how to subscribe to the changing and change events.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Events(events => events
.Changing("onChanging")
.Change("onChange")
)
.Sheets(sheets =>
{
sheets.Add()
.Name("Sheet1")
.Columns(columns =>
{
columns.Add().Width(115);
})
.Rows(rows =>
{
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.TextAlign(SpreadsheetTextAlign.Center);
});
});
})
)
<script>
function onChanging(e) {
// Handle the changing event.
}
function onChange(e) {
// Handle the change event.
}
</script>
// Place the following after the Spreadsheet for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The Name() of the Spreadsheet is used to get its client-side instance.
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
});
305
Telerik UI for ASP.NET Core
</script>
See Also
Basic Usage of the Spreadsheet HtmlHelper for ASP.NET Core (Demo)
Server-Side API
306
Telerik UI for ASP.NET Core
Comments
The Spreadsheet offers support for comments to be placed within each of its cells.
The following example demonstrates how a cell in the Spreadsheet can be initially configured to
contain a comment.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Sheets(sheets =>
{
sheets.Add()
.Name("Sheet1")
.Columns(c =>
{
c.Add().Width(300);
})
.Rows(rows =>
{
rows.Add().Height(70).Cells(cells =>
{
cells.Add()
.Value("This cell has a comment.")
.Bold(true)
.Comment("Comment set on the cell with the Spreadsheet initialization.");
});
});
})
)
See Also
Server-Side API
307
Telerik UI for ASP.NET Core
Custom Functions
In formulas, you can create your own custom JavaScript functions (primitives) by calling the
kendo.spreadsheet.defineFunction(name, func).
The first argument (string) is the name for your function in formulas (case-insensitive), and the
second one is a JavaScript function (the implementation).
Synchronous Primitives
The following example demonstrates how to define a function that calculates the distance between
two points.
kendo.spreadsheet.defineFunction("distance", function(x1, y1, x2, y2){
var dx = Math.abs(x1 - x2);
var dy = Math.abs(y1 - y2);
var dist = Math.sqrt(dx*dx + dy*dy);
return dist;
}).args([
[ "x1", "number" ],
[ "y1", "number" ],
[ "x2", "number" ],
[ "y2", "number" ]
]);
If you include the above JavaScript code, you can then use DISTANCE in formulas. For example, to
find the distance between coordinate points (2,2) and (5,6), type in a cell =DISTANCE(2, 2, 5,
6). Optionally, you can use the function in combined expressions such as =DISTANCE(0, 0, 1,
1) + DISTANCE(2, 2, 5, 6).
In the above example, defineFunction returns an object that has an args method. You can use it
to specify the expected types of arguments. If the function is called with mismatching argument
types, the runtime of the Spreadsheet automatically returns an error and your implementation is not
called. This spares the time for manually writing code that does argument type checking and
provides a nice declarative syntax instead.
Asynchronous Primitives
To retrieve currency information from a remote server, define a primitive to make this information
available in formulas. To define an asynchronous function, call argsAsync instead of args.
kendo.spreadsheet.defineFunction("currency", function(callback, base, curr){
// A suggested fetchCurrency function.
// The way it is implemented is not relevant to the goal of the demonstrated
scenario.
fetchCurrency(base, curr, function(value){
callback(value);
});
}).argsAsync([
308
Telerik UI for ASP.NET Core
[ "base", "string" ],
[ "curr", "string" ]
]);
The argsAsync passes a callback as the first argument to your implementation function, which you
need to call with the return value.
It is possible to use new approaches in formulas such as =CURRENCY("EUR", "USD") and =A1 *
CURRENCY("EUR", "USD"). Note that the callback is invisible in formulas. The second formula
shows that even though the implementation itself is asynchronous, it can be used in formulas in a
synchronous way—that is, the result yielded by CURRENCY is multiplied by the value in A1.
Argument Types
As can be seen in the examples above, both args and argsAsync expect a single array argument. It
contains one definition for each argument. Each definition is in turn an array where the first element
is the argument name that has to be a valid JavaScript identifier and the second element is a type
specifier.
309
Telerik UI for ASP.NET Core
defineFunction("truncate", function(value){
return value;
}).args([
[ "value", "integer" ]
]);
If you call =TRUNCATE(12.634), the result is 12. You can also call =TRUNCATE(TRUE), it returns 1.
All numeric types silently accept a Boolean, and convert true to 1 and false to 0.
Error Values
By default, if an argument is an error, your function is not called and that error is returned.
defineFunction("iserror", function(value){
return value instanceof kendo.spreadsheet.CalcError;
}).args([
[ "value", "anyvalue" ]
]);
With this implementation, when you type =ISERROR(1/0), #DIV/0! instead of true is returned—the
error is passed over and aborts the computation. To allow the passing of errors, append a ! to the
type.
...args([
[ "value", "anyvalue!" ]
]);
310
Telerik UI for ASP.NET Core
Sometimes you might need to write functions that receive a reference instead of a resolved value.
Such an example is the ROW function of Excel. In its basic form, it takes a cell reference and returns
its row number, as demonstrated in the following example. The actual ROW function is more
complicated.
defineFunction("row", function(cell){
// Add one because internally row indexes are zero-based.
return cell.row + 1;
}).args([
[ "reference", "cell" ]
]);
If you now call =ROW(A5), you get 5 as a result, regardless of the content in the A5 cell—it might be
empty or it is possible that this very formula sits in the A5 cell and there must be no circular
reference error in such a case.
See the References section below for more information about references.
311
Telerik UI for ASP.NET Core
defineFunction("my.position", function(min, max, value){
return (value - min) / (max - min);
}).args([
[ "min", "number" ],
[ "max", "number" ],
[ "value", [ "and", "number",
[ "[between]", "$min", "$max" ] ] ]
312
Telerik UI for ASP.NET Core
]);
[ "and", "number",
[ "[between]", "$min", "$max" ] ]
The code requires that the parameter is a number and that it has to be between min and max. To
refer to a previous argument, prefix the identifier with a $ character. This approach works for
arguments of "between" (and friends), "assert", "values" and "null".
Arbitrary Assertions
The above function is not quite correct because it does not check that max is actually greater than
min. To do that, use "assert", as demonstrated in the following example.
defineFunction("my.position", function(min, max, value){
return (value - min) / (max - min);
}).args([
[ "min", "number" ],
[ "max", "number" ],
[ "value", [ "and", "number",
[ "[between]", "$min", "$max" ] ] ],
[ "?", [ "assert", "$min < $max", "N/A" ] ]
]);
The "assert" type specification allows you to introduce an arbitrary condition into the JavaScript
code of the type-checking function. An argument name of "?" does not actually introduce a new
argument, but provides a place for such assertions. The third argument to "assert" is the error
code that it should produce if the condition does not stand (and #N/A! is actually the default).
Optional Arguments
As hinted above, you can use the "null" specifier to support optional arguments.
The following example demonstrates the actual definition of the ROW function.
defineFunction("row", function(ref){
if (!ref) {
return this.formula.row + 1;
}
if (ref instanceof CellRef) {
return ref.row + 1;
}
return this.asMatrix(ref).mapRow(function(row){
return row + ref.topLeft.row + 1;
});
}).args([
[ "ref", [ "or", "area", "null" ]]
]);
313
Telerik UI for ASP.NET Core
The code requires that the argument can either be an area (a cell or a range) or null (that is,
missing). By using the "or" combiner, you make it accept either of these. If the argument is missing,
your function gets null. In such cases, it has to return the row of the current formula that you get by
this.formula.row. For more details, refer to the section on context objects.
In most cases, “optional” means that the argument takes some default value if one is not provided.
For example, the LOG function computes the logarithm of the argument to a base, but if the base is
not specified, it defaults to 10.
defineFunction("log", function(num, base){
return Math.log(num) / Math.log(base);
}).args([
[ "*num", "number++" ],
[ "*base", [ "or", "number++", [ "null", 10 ] ] ],
[ "?", [ "assert", "$base != 1", "DIV/0" ] ]
]);
Return Errors
To return an error code, return a spreadsheet.CalcError object.
defineFunction("tan", function(x){
// If x is sufficiently close to PI, "tan" will return
// infinity or some really big number.
// The example will error out instead.
if (Math.abs(x - Math.PI/2) < 1e-10) {
return new spreadsheet.CalcError("DIV/0");
}
return Math.tan(x);
}).args([
[ "x", "number" ]
]);
For convenience, you can also throw a CalcError object for synchronous primitives—that is, if you
use args and not argsAsync.
It is possible to do the above through an assertion as well.
defineFunction("tan", function(x){
return Math.tan(x);
}).args([
[ "x", [ "and", "number",
[ "assert", "1e-10 < Math.abs($x - Math.PI/2)", "DIV/0" ] ] ]
]);
314
Telerik UI for ASP.NET Core
The simplest way is to use the "rest" type specifier. In such cases, the last argument is an array
that contains all remaining arguments, whatever types they might be.
The following example demonstrates how to use a function that joins arguments with a separator
producing a string.
defineFunction("join", function(sep, list){
return list.join(sep);
}).args([
[ "sep", "string" ],
[ "list", "rest" ]
]);
This allows for =JOIN("-", 1, 2, 3) which returns 1-2-3 and for =JOIN(".") which returns the
empty string because the list will be empty.
The "collect" clauses collect all remaining arguments that match a certain type specifier, ignoring
all others except for the errors. You can use them in functions like SUM that sums all numeric
arguments, but does not care about empty or text arguments.
defineFunction("sum", function(numbers){
return numbers.reduce(function(sum, num){
return sum + num;
}, 0);
}).args([
[ "numbers", [ "collect", "number" ] ]
]);
The "collect" clause aborts when it encounters an error. To ignore errors as well, use the
"#collect" specification. Note that "collect" and "#collect" only make sense when either is
the first specifier—that is, they cannot be nested in "or", "and", and the like.
There are functions that allow an arbitrary number of arguments of specific types. For example, the
SUMPRODUCT function takes an arbitrary number of arrays, multiplies the corresponding numbers in
these arrays, and then returns the sum of the products. In this case, you need at least two arrays.
315
Telerik UI for ASP.NET Core
[
[ "a1", "matrix" ],
[ "+",
[ "a2", [ "and", "matrix",
[ "assert", "$a2.width == $a1.width" ],
[ "assert", "$a2.height == $a1.height" ] ] ] ]
]
The "+" in the second definition means that one or more arguments are expected to follow and that
the a2 argument, defined there, can repeat. Notice how you can use assertions to make sure the
matrices have the same shape as the first one ( a1).
For another example, look at the SUMIFS function (see Excel documentation). It takes a sum_range, a
criteria_range, and a criteria. These are the required arguments. Then, any number of
criteria_range and criteria arguments can follow. In particular, criteria ranges must all have
the same shape (width/height). Here is the argument definition for SUMIFS:
[
[ "range", "matrix" ],
[ "m1", "matrix" ],
[ "c1", "anyvalue" ],
[ [ "m2", [ "and", "matrix",
[ "assert", "$m1.width == $m2.width" ],
[ "assert", "$m1.height == $m2.height" ] ] ],
[ "c2", "anyvalue" ] ]
]
The repeating part now is simply enclosed in an array, not preceded by "+". This indicates to the
system that any number might follow, including zero, while "+" requires at least one argument.
To be compatible with Excel and to avoid the unwilling implementation of this bug, the Spreadsheet
uses 1899-12-31 as the base date. Dates that are greater than or equal to 1900-03-31 have the same
numeric representation as in Excel, while dates before 1900-03-31 are smaller by 1.
Time is kept as a fraction of a day—that is, 0.5 means 12:00:00. For example, the date and time Sep
27 1983 12:35:59 is numerically stored as 30586.524988425925. To verify that in Excel, paste
this number in a cell and then format it as a date or time.
316
Telerik UI for ASP.NET Core
var runtime = kendo.spreadsheet.calc.runtime;
// Unpacking
var date = runtime.unpackDate(28922.55);
console.log(date); // { year: 1979, month: 2, date: 8, day: 4 }
var time = runtime.unpackTime(28922.55);
console.log(time); // { hours: 13, minutes: 12, seconds: 0, milliseconds: 0 }
var date = runtime.serialToDate(28922.55); // produces JavaScript Date object
console.log(date.toISOString()); // 1979-03-08T13:12:00.000Z
// Packing
console.log(runtime.packDate(2015, 5, 25)); // year, month, date
console.log(runtime.packTime(13, 35, 0, 0)); // hours, minutes, seconds, ms
console.log(runtime.dateToSerial(new Date()))
Note that the serial date representation does not carry any timezone information, so the functions
involving Date objects (serialToDate and dateToSerial) use the local components and not
UTC—as Excel does.
References
As mentioned earlier, certain type specifiers allow you to get a reference in your function rather than
the resolved value. Note that when you do so, you cannot rely on the values in those cells to be
calculated. As a result, if your function might need the values as well, you have to compute them.
Because the function which does this is asynchronous, your primitive has to be defined in an
asynchronous style as well.
defineFunction("test", function(callback, x){
this.resolveCells([ x ], function(){
console.log(x instanceof spreadsheet.CellRef); // true
console.log("So we have a cell:");
console.log(x.sheet, x.row, x.col);
console.log("And its value is:");
console.log(this.getRefData(x));
callback("Cell value: " + this.getRefData(x));
});
}).argsAsync([
[ "x", "cell" ]
]);
This function accepts a cell argument and you can only call it like =test(B4). It calls
this.resolveCells from the context object to verify that the cell value is calculated. Without this
step and if the cell actually contains a formula, the value returned by this.getRefData could be
outdated. Then it prints some information about that cell.
The following list explains the types of references that your primitive can receive:
spreadsheet.Ref—A base class only. All references inherit from it, but no direct instance
of this object should ever be created. The class is exported just to make it easier to check
whether something is a reference: x instanceof spreadsheet.Ref.
spreadsheet.NULLREF—An object (a singleton) and not a class. It represents the NULL
317
Telerik UI for ASP.NET Core
reference, and could occur, for example, when you intersect two disjoint ranges, or when a
formula depends on a cell that has been deleted. For example, when you put in some cell
=test(B5) and then right-click on column B and delete it. To test when something is the NULL
reference, just do x === spreadsheet.NULLREF.
spreadsheet.CellRef—Represents a cell reference. Note that the references here follow
the same programming language concept. They do not contain data. Instead they just point
to where the data is. So a cell reference contains 3 essential properties:
sheet — the name of the sheet that this cell points to (as a string)
row — the row number, zero-based
col — the column number, zero-based
spreadsheet.RangeRef—A range reference. It contains topLeft and bottomRight, which
are CellRef objects.
spreadsheet.UnionRef—A union. It contains a refs property, which is an array of
references (it can be empty). A UnionRef can be created by the union operator, which is the
comma.
The following example demonstrates how to use a function that takes an arbitrary reference and
returns its type of reference.
defineFunction("refkind", function(x){
if (x === spreadsheet.NULLREF) {
return "null";
}
if (x instanceof spreadsheet.CellRef) {
return "cell";
}
if (x instanceof spreadsheet.RangeRef) {
return "range";
}
if (x instanceof spreadsheet.UnionRef) {
return "union";
}
return "unknown";
}).args([
[ "x", "ref" ]
]);
The following example demonstrates how to use a function that takes an arbitrary reference and
returns the total number of cells it covers.
defineFunction("countcells", function(x){
var count = 0;
function add(x) {
if (x instanceof spreadsheet.CellRef) {
count++;
} else if (x instanceof spreadsheet.RangeRef) {
count += x.width() * x.height();
} else if (x instanceof spreadsheet.UnionRef) {
x.refs.forEach(add);
} else {
// unknown reference type.
throw new CalcError("REF");
}
}
add(x);
return count;
318
Telerik UI for ASP.NET Core
}).args([
[ "x", "ref" ]
]);
=COUNTCELLS(A1) — returns 1.
=COUNTCELLS(A1:C3) — returns 9.
=COUNTCELLS( (A1,A2,A1:C3) ) — returns 11. This is a union.
=COUNTCELLS( (A1:C3 B:B) ) — returns 3. This is an intersection between the A1:C3
range and the B column.
defineFunction("backgroundof", function(cell){
var workbook = this.workbook();
var sheet = workbook.sheetByName(cell.sheet);
return sheet.range(cell).background();
}).args([
[ "cell", "cell" ]
]);
It uses this.workbook() to retrieve the workbook, and then uses the Workbook/Sheet/Range APIs
to fetch the background color of the given cell.
Matrices
Matrices are defined by spreadsheet.calc.runtime.Matrix. Your primitive can request a
Matrix object by using the "matrix" type specification. In this case, it can accept a cell reference,
a range reference, or a literal array. You can type literal arrays in formulas like in Excel, e.g., { 1, 2;
3, 4 } (rows separated by semicolons).
Matrices were primarily added to deal with the “array formulas” concept in Excel. A function can
return multiple values, and those will be in a Matrix object.
The following example demonstrates how to use a function that doubles each number in a range
and returns a matrix of the same shape.
defineFunction("doublematrix", function(m){
return m.map(function(value){
return value * 2;
});
}).args([
[ "m", "matrix" ]
]);
319
Telerik UI for ASP.NET Core
The following table lists some of the methods and properties the Matrix objects provide.
Context Object
Every time a formula is evaluated, a special Context object is created and each involved primitive
function is invoked in the context of that object—that is, it is accessible as this.
The following table demonstrates some of the methods the Context object provides.
320
Telerik UI for ASP.NET Core
METHOD DESCRIPTION
resolveCells(array, callback) Verifies that all references in the given array
are resolved before invoking your
callback—that is, executes any formula. If this
array turns out to include the cell where the
current formula lives, it returns a #CIRCULAR!
error. Elements that are not references are
ignored.
cellValues(array) Returns as a flat array the values in any
reference that exist in the given array.
Elements that are not references are copied
over.
asMatrix(arg) Converts the given argument to a matrix, if
possible. It accepts a RangeRef object or a
plain JavaScript non-empty array. Additionally,
if a Matrix object is provided, it is returned as
is.
workbook() Returns the Workbook object where the
current formula is evaluated.
getRefData(ref) Returns the data—that is the value—in the
given reference. If a CellRef is given, it
returns a single value. For a RangeRef or
UnionRef, it returns a flat array of values.
Additionally, there is a formula property, an object representing the current formula. Its details are
internal, but you can rely on it having the sheet (sheet name as a string), row and col properties, the
location of the current formula.
If args or argsAsync are not called, the primitive function receives exactly two arguments:
The following example demonstrates how to use a function that adds two things.
defineFunction("add", function(callback, args){
callback(args[0] + args[1]);
});
Results:
=ADD(7, 8) → 15
321
Telerik UI for ASP.NET Core
=ADD() → NaN
=ADD("foo") → fooundefined
=ADD(A1, A2) → A1A2
In other words, if you use this raw form, you are responsible for type-checking the arguments and
your primitive is always expected to be asynchronous.
See Also
Server-Side API
322
Telerik UI for ASP.NET Core
Cell Formatting
The Spreadsheet supports cell-formatting options such as formatting of strings, text, numbers,
dates, and time.
Strings
While the format strings are compatible with the Excel number formats, some notable exceptionsstill
exist. A format string consists of one or more sections that are separated by semicolons. Optionally,
a section specifies a color and a condition.
The following example demonstrates how to display a number with up to three decimals.
#.###
The following example demonstrates how to display positive numbers, or zero, in green, and
negative numbers in red.
[Green]#.###;[Red]#.###
The following example demonstrates how to display positive numbers in green, negative numbers in
red, and the "Zero" text in blue if the number is zero.
[Green]#.###;[Red]#.###;[Blue]"Zero"
This following example is the same as the previous one, with the difference to display any possible
text in the cell in magenta.
[Green]#.###;[Red]#.###;[Blue]"Zero";[Magenta]@
<div id="example">
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.HtmlAttributes(new { style = "width:100%" })
.Sheets(sheets =>
{
sheets.Add()
.Name("Food Order")
.MergedCells("A1:G1", "C15:E15")
.Columns(columns =>
{
columns.Add().Width(100);
columns.Add().Width(215);
columns.Add().Width(115);
323
Telerik UI for ASP.NET Core
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(155);
})
.Rows(rows =>
{
rows.Add().Height(70).Cells(cells =>
{
cells.Add()
.Value("Invoice #52 - 06/23/2015")
.FontSize(32)
.Background("rgb(96,181,255)")
.TextAlign(SpreadsheetTextAlign.Center)
.Color("white");
});
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Product")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Quantity")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Price")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Tax")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Amount")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Background("rgb(167,214,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(216321)
.Background("rgb(255,255,255)")
324
Telerik UI for ASP.NET Core
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Calzone")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(12.39)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C3*D3*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C3*D3+E3")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(546897)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Margarita")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(2)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(8.79)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
325
Telerik UI for ASP.NET Core
.Color("rgb(0,62,117)")
.Formula("C4*D4*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C4*D4+E4")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(456231)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Pollo Formaggio")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(13.99)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C5*D5*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C5*D5+E5")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(455873)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
326
Telerik UI for ASP.NET Core
cells.Add()
.Value("Greek Salad")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(9.49)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C6*D6*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C6*D6+E6")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(456892)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Spinach and Blue Cheese")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(3)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(11.49)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C7*D7*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
327
Telerik UI for ASP.NET Core
cells.Add()
.Formula("C7*D7+E7")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(546564)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Rigoletto")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(10.99)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C8*D8*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C8*D8+E8")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(789455)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Creme Brulee")
.Background("rgb(255,255,255)")
328
Telerik UI for ASP.NET Core
.Color("rgb(0,62,117)");
cells.Add()
.Value(5)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(6.99)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C9*D9*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C9*D9+E9")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(123002)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Radeberger Beer")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(4)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(4.99)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C10*D10*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
329
Telerik UI for ASP.NET Core
.Color("rgb(0,62,117)")
.Formula("C10*D10+E10")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(564896)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Budweiser Beer")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(3)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(4.49)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C11*D11*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C11*D11+E11")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Index(11).Cells(cells =>
{
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
330
Telerik UI for ASP.NET Core
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
});
rows.Add().Index(12).Cells(cells =>
{
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
});
rows.Add().Index(13).Cells(cells =>
{
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
331
Telerik UI for ASP.NET Core
cells.Add()
.Value("Tip")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Right);
cells.Add()
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.Formula("SUM(F3:F11)*0.1")
.Format("$#,##0.00")
.Bold(true);
cells.Add()
.Background("rgb(167,214,255)");
});
rows.Add().Index(14).Height(50).Cells(cells =>
{
cells.Add()
.Index(0)
.Background("rgb(193,226,255)");
cells.Add()
.Index(1)
.Background("rgb(193,226,255)");
cells.Add()
.Value("Total Amount")
.Index(2)
.TextAlign(SpreadsheetTextAlign.Right)
.Color("rgb(0,62,117)")
.FontSize(20)
.Background("rgb(193,226,255)");
cells.Add()
.Index(5)
.Background("rgb(193,226,255)")
.Color("rgb(0,62,117)")
.Formula("SUM(F3:F14)")
.Format("$#,##0.00")
.FontSize(20)
.Bold(true);
cells.Add()
.Index(6)
.Background("rgb(193,226,255)");
});
});
})
)
</div>
<script>
$(document).ready(function () {
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
spreadsheet.sheets()[0].range("C3:C11").format('[=1][GREEN]#,##0;[=2][YELLOW]#,##0;[=3
][CYAN]#,##0;[RED]#,###');
})
</script>
332
Telerik UI for ASP.NET Core
public class SpreadsheetController : Controller
{
public ActionResult Index()
{
return View();
}
}
According to the Excel documentation, Excel supports a maximum of four sections. If all of them are
present, Excel interprets them in the following order:
The following example demonstrates how to display numbers greater than 100 in green, numbers
less than minus 100 in yellow, and other numbers in cyan.
[>100][GREEN]#,##0;[<=-100][YELLOW]#,##0;[CYAN]#,##0
In this case, it is not clear whether only up to four sections are allowed, of which the last one must be
text, while the Spreadsheet formatter allows for any number of conditional sections.
333
Telerik UI for ASP.NET Core
When situated between any digit placeholders, it outputs a number in thousands that are
separated by the separator in the current culture. For example, #,# formats 1234567 as
1,234,567.
When a comma follows a digit placeholder but is not followed by one, it scales the number
by one thousand. For example, #.##, formats 12345 as 12.35. This is a more complicated
format displaying in which cases such behavior is useful:
[>1000000]#.##,,"M";[>1000]#.##,"K";[>0]#"B";[=0]"Empty";[<0]"Replace
HDD!".
VALUE DISPLAY
334
Telerik UI for ASP.NET Core
12345678 12.35M
34567 34.57K
123 123B
0 Empty
-10 Replace HDD!
335
Telerik UI for ASP.NET Core
See Also
Server-Side API
336
Telerik UI for ASP.NET Core
Images
The Spreadsheet supports the placing of images in its sheets.
Then, in the popup window, you can select or drag in a file from the file system.
337
Telerik UI for ASP.NET Core
* A pointer to the cell that will hold the top-left corner of the image:
`TopLeftCell`.
* X and Y offset of the top-left corner: `OffsetX` and `OffsetY`.
* Dimensions of the rendered image: `Width` and `Height`.
* A pointer to the image key that is used in the `Images` configuration of the
Spreadsheet: `Image`.
The following example demonstrates how to configure the Spreadsheet to display an image with
top-left corner placed in the J6 cell.
338
Telerik UI for ASP.NET Core
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Images(new { testImage = "/images/image1.png" })
.Sheets(sheets =>
{
sheets.Add()
.Name("Sheet1")
.Drawings(dr =>
{
dr.Add()
.TopLeftCell("J6")
.OffsetX(30)
.OffsetY(10)
.Width(50)
.Height(50)
.Image("testImage");
})
.Columns(columns =>
{
columns.Add().Width(115);
})
.Rows(rows =>
{
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.TextAlign(SpreadsheetTextAlign.Center);
});
});
})
)
When you use the export functionality of the Spreadsheet together with images, note the
following:
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Sheets(sheets =>
{
sheets.Add()
.Name("Sheet1")
.Columns(columns =>
{
columns.Add().Width(115);
})
.Rows(rows =>
339
Telerik UI for ASP.NET Core
{
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.TextAlign(SpreadsheetTextAlign.Center);
});
});
})
)
<script>
$(document).ready(function () {
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
var sheet = spreadsheet.activeSheet();
var drawing = kendo.spreadsheet.Drawing.fromJSON({
topLeftCell: "J6",
offsetX: 30,
offsetY: 10,
width: 50,
height: 50,
image: spreadsheet.addImage("/images/chrome.gif")
});
sheet.addDrawing(drawing);
})
</script>
See Also
Server-Side API
340
Telerik UI for ASP.NET Core
For a runnable example, refer to the demo on binding the Spreadsheet HtmlHelper to the DataSource .
The Spreadsheet DataSource from that example uses the readand submittransport options. The
submit option is required to properly handle a scenario in which the user creates, updates and
deletes items simultaneously.
When using separate create, update, and destroyhandlers, it is possible that one of them fails,
while the others do not. That will result in a mismatch of the data state between the client (the
Spreadsheet) and the remote source. The submit option handles all operations within a single
request. It will not save any changes if any of the items is invalid.
Specific Behavior
Data Source binding switches the sheet to a special data-bound mode. It differs from the standard
behavior in the following ways:
Column headers are inferred from the data item fields. Configure the column headers and
ordering by using the sheet setDataSource method.
Cell styles, formulas, and formats are not persisted in the data source.
Row height and column width are not persisted in the data source.
Sorting and filtering are applied locally.
Inserted rows are always appended at the end, regardless of the actual row index.
Updating cell content translates into update operations.
Deleting rows translates into destroy operations.
Inserting and removing columns is not supported.
Unsupported Scenarios
The Sheet cannot be bound to a source which does not contain any items because the
header row in the sheet is generated based on the data items fields.
Records cannot be edited after sorting the sheet ( related feature request).
Records cannot be edited after filtering the sheet ( related feature request).
See Also
Server-Side API
Custom Functions
Cell Formatting
Export to Excel
341
Telerik UI for ASP.NET Core
Excel Export
The Spreadsheet utilizes the Kendo UI for jQuery Excel exportframework to produce Excel files directly
in the browser.
The output files are in the OOXML Spreadsheet format with an .xlsx extension. The legacy .xls
binary format is not supported.
User Interface
The default toolbar configuration includes an Export button. Clicking it opens a dialog box for
entering the file name and selecting the desired output format for the exported document.
The following image demonstrates the export of the Spreadsheet data to Excel.
342
Telerik UI for ASP.NET Core
The Spreadsheet client-side API includes the saveAsExcelmethod for initiating the export with
JavaScript. This method does not ask you to specify a file name. Instead, it sets the value in
excel.fileName.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.Excel(ex => ex.FileName("Order.xlsx"))
)
Known Issues
Currently, the export module does not handle sorting and filtering. This limitation will be addressed
before the widget goes out of its Beta version.
See Also
Server-Side API
Custom Functions
Cell Formatting
Data Source Binding
343
Telerik UI for ASP.NET Core
User Guide
This guide is intended for the end user of the Spreadsheet.
The document provides information about the functionalities of the widget for data entry and
management.
Conventions
This guide uses the following conventions:
Item Convention
Buttons, menus, tabs, dialog titles boldface font
Keyboard buttons, names of functions screen font
Overview
The Spreadsheet is used for the implementation of related data and its visualization in a tabular
format (rows and columns). This kind of data structuring provides for an easier management and
analysis. The widget renders the touch and feel of a Microsoft Excel tableby offering many
cell-formatting options, styles, and themes while utilizing simpler and easy-to-master user interface.
344
Telerik UI for ASP.NET Core
Actions
Sheets
When you open the Spreadsheet, the widget automatically generates a worksheet and applies to it a
collection of default settings.
Reorder Click and hold the sheet tab, and drag it to the
desired location on the Sheet Tab Bar
Delete Click X [ ] on the tab of the sheet you want to
remove
345
Telerik UI for ASP.NET Core
Cells
346
Telerik UI for ASP.NET Core
Merge cells (via Toolbar) 1. Select the cells you want to merge
2. Click Merge Cells [ ] on the Toolbar
3. Choose an option from the drop-down
list
Rows
347
Telerik UI for ASP.NET Core
3. Choose Hide
Columns
348
Telerik UI for ASP.NET Core
Fonts
349
Telerik UI for ASP.NET Core
Filters
Оr
350
Telerik UI for ASP.NET Core
351
Telerik UI for ASP.NET Core
Export to Excel
352
Telerik UI for ASP.NET Core
Export in PDF
2. In the File name field fill in a name for the
file that is going to be exported.
3. From the drop-down list against Save as
type choose Portable Document Format (.pdf).
353
Telerik UI for ASP.NET Core
Other
Apply the Undo function Click Undo [ ] on the Menu to reverse the
actions you made during your current session.
The number of actions you can reverse using
Undo is unlimited.
Apply the Redo function Click Redo [ ] on the Menu to repeat the
354
Telerik UI for ASP.NET Core
Further customize the format of numbers 1. Select the cells whose content you
want to format
2. Click Custom Format [ ] > More
Formats. Choose any of the following
options:
355
Telerik UI for ASP.NET Core
Choose data from predefined values The Spreadsheet supports the implementation
of custom editors. They facilitate your input of
data in a cell by providing you with predefined
date and list values that are already placed in
the necessary format.
1. Select a cell.
2. An icon appears right next to it. Click
on it to see the options that are
predefined for you to choose from.
Define names for cells and ranges of cells It is possible to define a custom name for a
cell or a range of cells in the Spreadsheet. As a
result, instead of typing the range in formulas
later on, you can directly refer to the range by
its name.
356
Telerik UI for ASP.NET Core
Delete names of cells and ranges of cells 1. Select the name of the cell or the range
of cells from the Name Box.
2. Click X.
Important
Keyboard Navigation
The Spreadsheet supports many of the Excel keyboard shortcuts as seen in the List of Keyboard
Shortcuts.
Known Limitations
Because of specific requirements, browsers might not support the Paste command when it
is initiated from the context menu or from the Toolbar. If you try to apply the command in
either of these ways, a popup message is displayed informing you about the limitation. Use
the keyboard navigation to achieve the desired result.
Formulas that are very deeply nested, such as =sin(cos(sin(cos(...)))) or
=A1+A2+A3+...+A200, might produce a stack overflow error. Even though the latter does
not seem nested, it is internally treated as =((((...(A1+A2)+A3)+A4)+...+)+A200)).
Solution
Use SUM when your case is similar to the second example of the nested formulas above. If to use
SUM is not possible, avoid nesting values more than 100 levels deep. Note that the maximum depth
depends on the browser, but one hundred is considered to be a safe limit.
See Also
List of Keyboard Shortcuts
List of Formulas and Functions
357
Telerik UI for ASP.NET Core
358
Telerik UI for ASP.NET Core
359
Telerik UI for ASP.NET Core
values
CLEAN Removes all nonprintable characters from a
text
CODE Return a numeric value corresponding to the
first character in a text string
COLUMN Returns the column number(s) of a reference
COLUMNS Returns the number of columns in a given
range
COMBIN Returns the number of combinations for a
given number of objects
COMBINA Returns the number of combinations with
repetitions for a given number of objects
CONCATENATE Joins a number of text strings into one text
string
CONFIDENCE.NORM Returns the confidence interval for a
population mean
CONFIDENCE.T Returns the confidence interval for a
population mean, using a Student's t
distribution
COS Returns the cosine of a number. The angle is
returned in radians.
COSH Returns the hyperbolic cosine of a number
COT Returns the cotangent of an angle, specified in
radians
COTH Returns the hyperbolic cotangent of a number
COUNT Counts the number of numbers in a list of
arguments
COUNTA Counts the number of values in a list of
arguments
COUNTBLANK Counts the number of blank cells in a range
COUNTIF Counts the number of cells in a range that
meet a criteria
COUNTIFS Counts the number of cells in a range that
meet multiple criteria
COVAR Calculates the covariance between two cell
ranges
COVARIANCE.P Returns covariance, the average of the
products of paired deviations
360
Telerik UI for ASP.NET Core
361
Telerik UI for ASP.NET Core
362
Telerik UI for ASP.NET Core
363
Telerik UI for ASP.NET Core
364
Telerik UI for ASP.NET Core
numbers
MDETERM Returns the determinant of a matrix
MEDIAN Returns the median (middle) value in a list of
numbers
MID Returns a specific number of characters from
a text string, starting at a specified position
MIN Returns the minimum value in a set of
numbers
MINUTE Converts a serial number into a minute
MINVERSE Returns the inverse of a matrix
MMULT Returns the matrix output of two arrays
MOD Returns the remainder when one number is
divided by another number
MODE.MULT Returns a vertical array of the most frequently
occurring, or repetitive values in an array or
range of data
MODE.SNGL Returns the most common value in a data set
MONTH Converts a serial number to a month
MROUND Rounds the number to the desired multiple
MULTINOMIAL Returns the multinomial for a given set of
values
MUNIT Creates a unit matrix of a specified dimension
N Returns the number of a value
NA Returns the error value #N/A
NEGBINOM.DIST Returns the negative binomial distribution
NEGBINOMDIST Returns the negative binomial distribution
NETWORKDAYS Returns the number of whole workdays
between two dates
NORM.DIST Returns the normal cumulative distribution
NORM.INV Returns the inverse of the normal cumulative
distribution
NORM.S.DIST Returns the standard normal cumulative
distribution
NORM.S.INV Returns the inverse of the standard normal
cumulative distribution
NOT Reverses the logic of its argument
365
Telerik UI for ASP.NET Core
366
Telerik UI for ASP.NET Core
367
Telerik UI for ASP.NET Core
368
Telerik UI for ASP.NET Core
369
Telerik UI for ASP.NET Core
an input date
YEAR Converts a serial number to a year
YEARFRAC Extracts the number of years (including
fractional part) between two dates
For more information on how to create formulas and what their syntax is, see the list of Excel
functions.
Array Formulas
Similar to Excel, the Spreadsheet supports array formulaswhich return a matrix of values. You have to
enter them in the same way as in Excel—by pre-selecting the target range and pressing
Ctrl+Shift+Enter to save the formula.
See Also
List of Keyboard Shortcuts
User Guide
370
Telerik UI for ASP.NET Core
Shortcuts Description
Ctrl + A Selects the whole worksheet
Ctrl + C Copies selected cells
Ctrl + P Displays the Print dialog box
Ctrl + S Saves the active spreadsheet file
Ctrl + V Inserts copied or cut cells to a selected
location within the worksheet
Ctrl + X Cuts selected cells
Ctrl + Y Repeats the last action, if possible by using the
Redo command
371
Telerik UI for ASP.NET Core
372
Telerik UI for ASP.NET Core
See Also
List of Formulas and Functions
373
Telerik UI for ASP.NET Core
User Guide
374
Telerik UI for ASP.NET Core
Troubleshooting
This article provides solutions for common issues you may encounter while working with the Telerik
UI Spreadsheet HtmlHelper for ASP.NET Core.
Solution Reset all cells outside the used range to the default borders, formatting and colors.
See Also
Basic Usage of the Spreadsheet HtmlHelper for ASP.NET Core (Demo)
API Reference of the Spreadsheet HtmlHelper for ASP.NET Core
375
Telerik UI for ASP.NET Core
The TreeList enables the display of self-referencing tabular data and allows sorting, filtering, and
data editing.
The TreeList HtmlHelper distinguishes the root items based on the ParentId field. If the ParentId
is set as .Nullable(true), root items with be items whose ParentId field values are null. If the
ParentId is not nullable (.Nullable(false)), root items will be items which have a default value
for their data type.
public class EmployeeViewModel
{
// The Id.
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// A nullable ParentId.
public int? ReportsTo { get; set; }
public string Address { get; set; }
// This is a case-sensitive property. Define it only if you want to use
lazy-loading.
// If it is not defined, the TreeList will calculate and assign its value on
the client.
public bool hasChildren { get; set; }
}
public JsonResult All([DataSourceRequest] DataSourceRequest request)
{
var result = GetDirectory().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => e
);
return Json(result, JsonRequestBehavior.AllowGet);
}
376
Telerik UI for ASP.NET Core
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.Columns(columns =>
{
columns.Add().Field(f => f.FirstName).Width(250).Title("First Name");
columns.Add().Field(e => e.LastName).Title("Last Name");
columns.Add().Field(e => e.Position);
columns.Add().Field(e => e.Extension).Title("Ext").Format("{0:#}");
})
.DataSource(dataSource => dataSource
.Read(read => read.Action("Index", "EmployeeDirectory"))
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo).Nullable(true);
m.Field(f => f.FirstName);
m.Field(f => f.LastName);
m.Field(f => f.ReportsTo);
})
)
)
Events
You can subscribe to all TreeList events. For a complete example on basic TreeList events, refer to
the demo on using the events of the TreeList.
@(Html.Kendo().TreeList<KendoTreeListBinding.Models.EmployeeViewModel>()
.Name("treelist")
/* Other configurations. */
.Events(events => {
events.DataBinding("onDataBinding");
events.DataBound("onDataBound");
})
)
<script>
function onDataBinding(e) {
// Handle the dataBinding event.
var treelist = this;
377
Telerik UI for ASP.NET Core
}
function onDataBound(e) {
// Handle the dataBound event.
var treelist = e.sender;
}
</script>
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
/* Other configurations. */
)
<script>
$(function() {
// The Name() of the TreeList is used to get its client-side instance.
var treelist = $("#treelist").data("kendoTreeList");
});
</script>
See Also
Basic Usage of the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
378
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Telerik UI TreeList for Ajax binding to make Ajax requests upon loading child
nodes, sorting, or filtering.
When configured for Ajax binding, the Telerik UI TreeList for ASP.NET Core makes Ajax requests
when doing sorting, filtering or when expanding a node.
The TreeList retrieves only the data (in JSON format) representing the current level items.
All column templates are executed client-side. They follow the Kendo UI for jQuery template
definition rules and may contain embedded JavaScript code.
1. Create a new ASP.NET Core web application. Follow the steps from the introductory articleto
add Telerik UI for ASP.NET Core to the application.
2. Open the HomeController.cs and add a new action method which will return the items as
JSON. The TreeList makes Ajax requests to this action.
public IActionResult TreeList_Read()
{
}
public IActionResult TreeList_Read([DataSourceRequest]DataSourceRequest request,
int? parentId)
{
}
public JsonResult Index([DataSourceRequest] DataSourceRequest request, int?
parentId)
379
Telerik UI for ASP.NET Core
{
var result = ((EmployeeDirectoryService)
employeeDirectory).GetAllRemote().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => id.HasValue ? e.ReportsTo == parentId : e.ReportsTo == null,
e => e
);
5. Return the TreeDataSourceResult as JSON. Configure the Telerik UI TreeList for Ajax
binding.
public JsonResult Index([DataSourceRequest] DataSourceRequest request, int?
parentId)
{
var result = ((EmployeeDirectoryService)
employeeDirectory).GetAllRemote().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => id.HasValue ? e.ReportsTo == parentId : e.ReportsTo == null,
e => e
);
return Json(result, JsonRequestBehavior.AllowGet);
}
6. In the view, configure the TreeList to use the action method created in the previous steps.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryRem
oteModel>()
.Name("treelist")
.Columns(columns =>
{
columns.Add().Field(f => f.FirstName).Width(250).Title("First Name");
columns.Add().Field(e => e.LastName).Title("Last Name");
columns.Add().Field(e => e.Position);
columns.Add().Field(e => e.Extension).Title("Ext").Format("{0:#}");
})
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Read(read => read.Action("Index", "EmployeeDirectory"))
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo).Nullable(true);
m.Field(f => f.FirstName);
m.Field(f => f.LastName);
m.Field(f => f.ReportsTo);
})
.Aggregates(x=> x.Add(y=> y.BirthDate).Count())
)
)
380
Telerik UI for ASP.NET Core
See Also
Binding to Remote Data by the TreeList HtmlHelper for ASP.NET Core (Demo)
Binding to OData by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
381
Telerik UI for ASP.NET Core
Editing Overview
The Telerik UI TreeList HtmlHelperprovides a built-in editing functionality.
The following example demonstrates how to use the nullable model—items with ParentId null will
be root items.
.DataSource(dataSource => dataSource
...
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo).Nullable(true);
public int? ReportsTo { get; set; }
public int EmployeeId { get; set; }
The following example demonstrates how to use the non-nullable model—items with ParentId
string.empty will be root items.
.DataSource(dataSource => dataSource
...
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo).Nullable(false);
public string ReportsTo { get; set; }
public string EmployeeId { get; set; }
382
Telerik UI for ASP.NET Core
from the service, which needs to return the manipulated records, so that the TreeList can apply the
changes to the DataSource accordingly. The new records also have to contain the newly assigned
within the service Id value.
.DataSource(dataSource => dataSource
.Create(create => create.Action("Create", "EmployeeDirectory"))
.Read(read => read.Action("All", "EmployeeDirectory"))
.Update(update => update.Action("Update", "EmployeeDirectory"))
.Destroy(delete => delete.Action("Destroy", "EmployeeDirectory"))
Edit Modes
The TreeList supports the following edit modes:
See Also
Editing by the TreeList HtmlHelper for ASP.NET Core (Demo)
Incell Editing by the TreeList HtmlHelper for ASP.NET Core (Demo)
Popup Editing by the TreeList HtmlHelper for ASP.NET Core (Demo)
Editing by Dragging and Dropping in the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
383
Telerik UI for ASP.NET Core
Incell Editing
The Telerik UI TreeList HtmlHelper for ASP.NET Core enables you to implement cell editing and
make and save batch updates.
For a runnable example, refer to the demo on incell (batch) editing of the TreeList.
1. Add a new class to the ~/Models folder. The following example uses the
EmployeeDirectoryModel name.
public class EmployeeDirectoryModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? ReportsTo { get; set; }
}
2. Open TreeListController.cs and add a new action method which will return the
Directories as JSON. The TreeList will make Ajax requests to this action.
public JsonResult All_InCell([DataSourceRequest] DataSourceRequest request)
{
var result = GetDirectory().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => e
);
return Json(result);
}
3. Add a new action method to TreeListController.cs. It will be responsible for saving the
new data items. Name the method Create_InCell.
public JsonResult Create_InCell([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<EmployeeDirectoryModel> employees)
{
if (ModelState.IsValid)
{
foreach (var employee in employees)
{
employeeDirectory.Insert(employee, ModelState);
}
}
return Json(employees.ToTreeDataSourceResult(request, ModelState));
384
Telerik UI for ASP.NET Core
4. Add a new action method to TreeListController.cs. It will be responsible for saving the
updated data items. Name the method Update_InCell.
public JsonResult Update_InCell([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<EmployeeDirectoryModel> employees)
{
if (ModelState.IsValid)
{
foreach (var employee in employees)
{
employeeDirectory.Update(employee, ModelState);
}
}
return Json(employees.ToTreeDataSourceResult(request, ModelState));
}
5. Add a new action method to TreeListController.cs. It will be responsible for saving the
deleted data items. Name the method Destroy_InCell.
public JsonResult Destroy_InCell([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<EmployeeDirectoryModel> employees)
{
if (ModelState.IsValid)
{
foreach (var employee in employees)
{
employeeDirectory.Delete(employee, ModelState);
}
}
return Json(employees.ToTreeDataSourceResult(request, ModelState));
}
6. In the view, configure the TreeList to use the action methods that were created in the
previous steps. The Create, Update, and Destroy action methods have to return a
collection with the modified or deleted records which will enable the DataSource to apply the
changes accordingly. The Create method has to return a collection of the created records
with the assigned ID field.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryMod
el>()
.Name("treelist")
.Toolbar(toolbar =>
{
toolbar.Create();
toolbar.Save();
toolbar.Cancel();
})
385
Telerik UI for ASP.NET Core
.Columns(columns =>
{
columns.Add().Field(e => e.FirstName).Title("First Name").Width(220);
columns.Add().Field(e => e.LastName).Title("Last Name").Width(100);
columns.Add().Command(c =>
{
c.CreateChild().Text("Add child");
c.Destroy();
}
).Width(240);
})
.Editable(e => e.Mode(TreeListEditMode.InCell).Move(false))
.DataSource(dataSource => dataSource
.Batch(true)
.Read(read => read.Action("All_InCell", "TreeList"))
.Create(create => create.Action("Create_InCell",
"TreeList").Type(HttpVerbs.Post))
.Update(update => update.Action("Update_InCell",
"TreeList").Type(HttpVerbs.Post))
.Destroy(delete => delete.Action("Destroy_InCell",
"TreeList").Type(HttpVerbs.Post))
.Model(m =>
{
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
})
)
)
See Also
Incell Editing by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
386
Telerik UI for ASP.NET Core
Inline Editing
You can define commands and set the edit mode to configure the Telerik UI TreeList for ASP.NET
Core for inline editing.
For runnable examples, refer to the demos on implementing the editing approaches in the TreeList .
1. Add a new class to the ~/Models folder. The following example uses the
EmployeeDirectoryModel name.
public class EmployeeDirectoryModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? ReportsTo { get; set; }
}
2. Open TreeListController.cs and add a new action method which will return the
Directories as JSON. The TreeList will make Ajax requests to this action.
public JsonResult All([DataSourceRequest] DataSourceRequest request)
{
var result = GetDirectory().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => e
);
return Json(result);
}
3. Add a new action method to TreeListController.cs. It will be responsible for saving the
new data items. Name the method Create.
public JsonResult Create([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Insert(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
387
Telerik UI for ASP.NET Core
4. Add a new action method to TreeListController.cs. It will be responsible for saving the
updated data items. Name the method Update.
public JsonResult Update([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Update(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
5. Add a new action method to TreeListController.cs. It will be responsible for saving the
deleted data items. Name the method Destroy.
public JsonResult Destroy([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Delete(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
6. In the view, configure the TreeList to use the action methods that were created in the
previous steps. The Create, Update, and Destroy action methods have to return a
collection with the modified or deleted records which will enable the DataSource to apply the
changes accordingly. The Create method has to return a collection of the created records
with the assigned ID field.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryMod
el>()
.Name("treelist")
.Toolbar(toolbar => toolbar.Create())
.Columns(columns =>
{
columns.Add().Field(e => e.FirstName).Title("First Name").Width(220);
columns.Add().Field(e => e.LastName).Title("Last Name").Width(100);
columns.Add().Field(e => e.Position);
columns.Add().Field(e => e.HireDate).Format("{0:MMMM d, yyyy}");
columns.Add().Field(e => e.Phone);
columns.Add().Field(e => e.Extension).Title("Ext").Format("{0:#}");
columns.Add().Width(300).Command(c =>
{
c.CreateChild().Text("Add child");
c.Edit();
c.Destroy();
})
.HtmlAttributes(new
{
388
Telerik UI for ASP.NET Core
style = "text-align: center;"
});
})
.Editable()
.DataSource(dataSource => dataSource
.Create(create => create.Action("Create", "TreeList"))
.Read(read => read.Action("All", "TreeList"))
.Update(update => update.Action("Update", "TreeList"))
.Destroy(delete => delete.Action("Destroy", "TreeList"))
.Model(m =>
{
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
})
)
)
See Also
Editing Approaches by the TreeList HtmlHelper for ASP.NET Core (Demos)
Server-Side API
389
Telerik UI for ASP.NET Core
Popup Editing
You can define commands and set the edit mode to configure the Telerik UI TreeList for ASP.NET
Core for popup editing.
For runnable examples, refer to the demos on implementing the editing approaches in the TreeList .
1. Add a new class to the ~/Models folder. The following example uses the
EmployeeDirectoryModelPopUp name.
public class EmployeeDirectoryModelPopUp
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? ReportsTo { get; set; }
}
2. Add an empty MVC Controller TreeListController.cs and add a new action method
ReadOrders which will return the Directories as JSON in the expected format. The TreeList
will make Ajax requests to this action.
public JsonResult All([DataSourceRequest] DataSourceRequest request)
{
var result = GetDirectory().ToTreeDataSourceResult(request,
e => e.EmployeeId,
e => e.ReportsTo,
e => e
);
return Json(result);
}
3. Add a new action method to TreeListController.cs. It will be responsible for saving the
new data items. Name the method Create. The Create method has to return a collection of
the created records with the assigned Id field.
public JsonResult Create([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Insert(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
390
Telerik UI for ASP.NET Core
4. Add a new action method to TreeListController.cs. It will be responsible for saving the
updated data items. Name the method Update.
public JsonResult Update([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Update(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
5. Add a new action method to TreeListController.cs. It will be responsible for saving the
deleted data items. Name the method Destroy.
public JsonResult Destroy([DataSourceRequest] DataSourceRequest request,
EmployeeDirectoryModel employee)
{
if (ModelState.IsValid)
{
employeeDirectory.Delete(employee, ModelState);
}
return Json(new[] { employee }.ToTreeDataSourceResult(request, ModelState));
}
6. In the view, configure the TreeList to use the action methods created in the previous steps.
The Create, Update, and Destroy action methods have to return a collection with the
modified or deleted records so the DataSource on the client is aware of the server-side
changes.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryMod
elPopUp>()
.Name("treelist")
.Toolbar(toolbar => toolbar.Create())
.Columns(columns =>
{
columns.Add().Field(e => e.FirstName).Width(220).Title("First Name");
columns.Add().Field(e => e.LastName).Width(100).Title("Last Name");
columns.Add().Width(300).Command(c =>
{
c.CreateChild().Text("Add child");
c.Edit();
c.Destroy();
});
})
.Editable(e => e.Mode("popup"))
.DataSource(dataSource => dataSource
.Create(create => create.Action("Create", "EmployeeDirectory"))
.Read(read => read.Action("All", "EmployeeDirectory"))
391
Telerik UI for ASP.NET Core
.Update(update => update.Action("Update", "EmployeeDirectory"))
.Destroy(delete => delete.Action("Destroy", "EmployeeDirectory"))
.Model(m =>
{
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
})
)
)
See Also
Editing Approaches by the TreeList HtmlHelper for ASP.NET Core (Demos)
Server-Side API
392
Telerik UI for ASP.NET Core
@(Html.Kendo().TreeList<EmployeeViewModel>()
.Name("treelist")
.Toolbar(t=>t.Save()) /* to batch save the new hierarchy */
.DataSource(dataSource => dataSource
.Batch(true) /* enable batch operations */
.Read(read => read.Action("Employees_Read", "TreeList"))
.Update(update => update.Action("Employees_Update", "TreeList"))
.Model(m =>
{
m.Id(f => f.OrderID);
m.ParentId(f => f.ParentOrderID).Nullable(true);
m.Expanded(true);
})
)
/* other TreeList settings */
)
// The TreeList sends the updated items with prefix "models".
// Remember to bind it in the controller so that the collection can be intercepted.
public JsonResult Update([DataSourceRequest] DataSourceRequest request,
[Bind(Prefix = "models")]IEnumerable<EmployeeDirectoryModel> employees).
{
if (ModelState.IsValid)
{
foreach (var employee in employees)
{
employeeDirectory.Update(employee, ModelState);
}
}
return Json(employees.ToTreeDataSourceResult(request, ModelState));
}
See Also
Editing by Dragging and Dropping in the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
393
Telerik UI for ASP.NET Core
Aggregates
The TreeList enables you to display aggregated number results when the user groups its data.
See Also
Aggregates by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
394
Telerik UI for ASP.NET Core
Paging
The TreeList supports client-side paging for large sets of data.
To enable the paging functionality of the TreeList, configure the Pageable settings.
Remember to set a PageSize. You can define a PageSize in the Pageable or in the
DataSource settings. If an already existing dataSource instance is passed to the TreeList,
then the PageSize option has to be set in the dataSource settings and not in the Pageable
settings.
By default, ServerOperations are enabled in the TreeList HtmlHelper. For client-side
paging you have to disable the server operations by setting the ServerOperations to
false.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.Columns(columns =>
{
columns.Add().Field(e => e.FirstName).Title("Name").Template("#: FirstName # #:
LastName #");
columns.Add().Field(e => e.Position);
columns.Add().Field(e => e.HireDate).Format("{0:MMMM d, yyyy}");
})
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.ServerOperation(false)
.Read(read => read.Action("All", "EmployeeDirectory"))
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
m.Field(f => f.ReportsTo);
m.Expanded(true);
})
)
.Height(540)
.Pageable(p => p.PageSize(15)
.PageSizes(true)
)
)
The root TreeList items have their parentId field set to the default value for no parent. By default,
the value is null and can be configured through the
dataSource.schema.model.fields[FIELD_NAME].defaultValue option.
If you use client-side paging together with editing, the user adds an item, and the id field of the
model has to be nullable (for example, int?), then you have to configure the model so that it
features a default id field value on the client side which is different from the default parentId field
value. In such cases, the default value of the id field (null) will equal the default parentId field
value (null) which creates a circular dependency. To avoid this issue, set the default id field to a
different value, for example, to zero.
395
Telerik UI for ASP.NET Core
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
...
.DataSource(dataSource => dataSource
.ServerOperation(false)
.Read(read => read.Action("All", "EmployeeDirectory"))
.Model(m => {
// Assuming the "EmployeeId" field is equal to null by default and
// the default value of the "ReportsTo" field is also null.
m.Field(f => f.EmployeeId).DefaultValue(0);
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
m.Field(f => f.ReportsTo);
m.Expanded(true);
})
)
.Height(540)
.Pageable(p => p.PageSize(15)
.PageSizes(true)
)
)
See Also
Client-Side paging by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
396
Telerik UI for ASP.NET Core
Search Panel
Out of the box, the TreeList enables the users to search through its data by using the search panel.
Under the hood, the search panel uses filtering to show only the relevant records in the TreeList.
Getting Started
To enable the search panel functionality, include the Search option to the toolbar configuration.
When the server operations are enabled, you can search only by using string fields. Using the
Contains filter operation is available only for string types.
@(Html.Kendo().TreeList<CustomerViewModel>()
.Name("treeList")
.ToolBar(t => t.Search()) // Enable the Search panel.
...
You can also customize which fields to search through the data when a value is entered in the
search input.
...
.Search(s=> { s.Field(c => c.ContactName); })
Known Limitations
When filtering is enabled in the filter textboxes for all TreeList columns will be populated with the
value entered in the search textbox.
See Also
Server-Side API
Knowledge Base Section
397
Telerik UI for ASP.NET Core
Export Overview
By default, the Telerik UI TreeList HtmlHelper for ASP.NET Core provides a PDF and Excel export
functionality.
For more information about the available export options of the TreeList, refer to the articles on:
Excel export
PDF export
Under the hood, most of the PDF export options use the Kendo UI for jQuery Drawing libraryand the
Excel export builds a kendo.ooxml.Workbook.
To enable the PDF and Excel Export functionality, add the following ToolBar configuration:
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.ToolBar(tools=>
{
tools.Pdf();
tools.Excel();
})
)
See Also
Server-Side API
398
Telerik UI for ASP.NET Core
Excel Export
The TreeList enables you to export its content to Excel.
For a runnable example, refer to the demo on Excel export by the TreeList.
Getting Started
To enable the Excel export option of the TreeList:
1. Include the corresponding toolbar command and set the export settings.
Toolbar configuration
Excel export configuration
2. To take full advantage of the Excel export feature, download the JSZip library and include the
file before the Kendo UI JavaScript files in the Layout.cshtml. For more information, refer
to the article with the requirements.
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.js"></script>
<script
src="http://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryMod
el>()
.Name("treelist")
.Toolbar(tools => tools.Excel())
.Excel(excel => excel.FileName("Kendo UI TreeList
Export.xlsx").ProxyURL(Url.Action("Excel_Export_Save")))
.DataSource(dataSource => dataSource
.Read(read => read.Action("All", "EmployeeDirectory"))
)
)
To initiate the Excel export, press the Toolbar button or use the TreeList client-side APIand call the
saveAsExcelmethod.
The TreeList uses the current column order, visibility, and dimensions to generate the Excel file. It
does not export the current CSS theme in the Excel file.
The TreeList exports only data-bound columns. Template and command columns are
ignored.
399
Telerik UI for ASP.NET Core
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.Toolbar(tools => tools.Excel())
.Excel(excel => excel.AllPages(true))
.DataSource(dataSource => dataSource
.Read(read => read.Action("All", "EmployeeDirectory"))
)
)
See Also
Excel Export by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
400
Telerik UI for ASP.NET Core
PDF Export
The UI for ASP.NET Core TreeList HtmlHelper provides a built-in PDF export functionality.
For a runnable example, refer to the demo on exporting the TreeList to PDF.
Getting Started
To enable PDF export:
1. Include the corresponding toolbar command and set the export settings.
Toolbar configuration
PDF export configuration
2. Include the Pako Deflate library in the page to enable compression.
To initiate the PDF export, press the Toolbar button or use the TreeList client-side APIand call the
saveAsPDFmethod.
The following example demonstrates how to enable the PDF export functionality of the TreeList.
<!-- Load Pako Deflate library to enable PDF compression -->
<script
src="http://kendo.cdn.telerik.com/2019.3.1023/js/pako_deflate.min.js"></script>
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.Toolbar(tools => tools.Pdf())
.DataSource(dataSource => dataSource
.Read(read => read.Action("All", "EmployeeDirectory"))
)
)
<style>
/*
Use the DejaVu Sans font for display and embedding in the PDF file.
The standard PDF fonts have no support for Unicode characters.
*/
.k-treelist {
font-family: "DejaVu Sans", "Arial", sans-serif;
401
Telerik UI for ASP.NET Core
}
</style>
<script>
// Import the DejaVu Sans font for embedding.
// NOTE: Only required if the Kendo UI stylesheets are loaded
// from a different origin, for example, kendo.cdn.telerik.com.
kendo.pdf.defineFont({
"DejaVu Sans" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans.ttf",
"DejaVu Sans|Bold" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Bold.ttf",
"DejaVu Sans|Bold|Italic" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Oblique.ttf",
"DejaVu Sans|Italic" : "https://kendo.cdn.telerik.com/2019.3.1023
/styles/fonts/DejaVu/DejaVuSans-Oblique.ttf"
});
</script>
<!-- Load Pako ZLIB library to enable PDF compression -->
<script src="//kendo.cdn.telerik.com/2019.3.1023/js/pako_deflate.min.js"></script>
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
.Toolbar(tools => tools.Pdf())
.DataSource(dataSource => dataSource
.Read(read => read.Action("All", "EmployeeDirectory"))
)
)
See Also
PDF Export by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
402
Telerik UI for ASP.NET Core
Locked Columns
Locked (frozen) columns enable you to display specific columns at all times while the user scrolls
the TreeList horizontally.
For a runnable example, refer to the demo on implementing locked columns in the TreeList.
For the feature to work properly, the following configuration settings has to be provided. They ensure
that at least one non-locked column is always visible and that it is possible to scroll the non-locked
columns horizontally. If the horizontal space intended for it is not enough, the horizontal scrollbar
does not appear.
Enable scrolling.
Lock at least one column initially.
Define the height of the TreeList.
Set explicit pixel widths to all columns to allow the TreeList to adjust the layout of the frozen
and non-frozen table parts.
Make sure that the total width of all locked columns is equal to or less than the width of the
TreeList minus three times the width of the scrollbar.
Make sure that the TreeList is not initialized inside a hidden container.
Locked columns cannot be scrolled on touch because they are wrapped in a container with an
overflow:hidden style. To work around this limitation on desktop devices, use the mousewheel
event. However, no workaround exists for touch devices.
Locked columns rely on synchronizing the row height of the frozen and non-frozen parts of the
TreeList. Some browsers, such as Internet Explorer 9 and Firefox, require a line-height style set in
pixels. Otherwise, the synchronization might not work properly because of sub-pixel issues.
div.k-treelist td
{
line-height: 18px;
}
When you implement custom code and rely on selectors or target the TreeList table, the TreeList
creates separate tables for its locked and scrollable sections. The locked columns are inside a
403
Telerik UI for ASP.NET Core
See Also
Implementing Locked Columns in the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
404
Telerik UI for ASP.NET Core
Column Menu
The TreeList provides a built-in option for triggering column operations through a menu.
To enable the column-menu implementation, set .ColumnMenu(). As a result, the column headers
of the TreeList will render a column menu which allows the user to sort, filter, or change the visibility
of the column. The column menu also detects when a specific column operation is disabled through
the column definition and excludes the corresponding UI from its rendering. For a runnable example,
refer to the demo on implementing a column menu in the TreeList.
See Also
Column Menu by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
405
Telerik UI for ASP.NET Core
Multi-Column Headers
The multi-column headers of the TreeList represent a tree-like structure where one or more columns
can be grouped together by a common header.
That common header in turn can be a child of another upper MultiColumn header which can also
span both columns and other headers. For a runnable example, refer to the demo on implementing
multi-column headers in the TreeList.
columns.Group(group => group
.Title("Personal Info")
.Columns(info =>
{
info.Add().Field(x => x.LastName).Width(120);
info.Group(g => g
.Title("Location")
.Columns(location =>
{
location.Add().Field(c => c.City).Width(140);
location.Add().Field(c => c.Country).Width(140);
})
);
info.Add().Field(x => x.Phone);
})
);
See Also
Implementing Multi-Column Headers in the TreeList HtmlHelper for ASP.NET Core
Server-Side API
406
Telerik UI for ASP.NET Core
Resizing of Columns
The resizing behavior of the TreeList columns depends on whether scrolling is enabled or disabled.
For a runnable example, refer to the demo on resizing columns in the TreeList.
When scrolling is disabled and a TreeList column is resized, other columns change their widths too,
so that the sum of all column widths remains constant. If both the columns and the TreeList <div>
already have their minimum possible widths applied, then the resizing of the columns stops working.
In such scenarios, use either of the following approaches:
When scrolling is enabled and a column is resized, all other columns maintain their widths. When
column resizing is applied, the following outcomes with regard to the sum of all column widths are
possible:
If the sum of all column widths is greater than the width of the TreeList, a horizontal scrollbar
appears.
If the sum of all column widths is equal to the width of the TreeList, no horizontal scrollbar
appears.
If the sum of all column widths is less than the width of the TreeList, an empty space after
the last column appears.
By design, the last column of the TreeList has no right border, so that no double border appears at
the right end of the TreeList if the TreeList table width matches the TreeList width. If needed, you
can apply a right border with the CSS code from the following example. The color value of the #ccc
border has to match the color of the cell border from the Kendo UI theme.
See Also
Column Resizing by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
407
Telerik UI for ASP.NET Core
Reordering of Columns
The TreeList provides options for reordering its columns.
To enable the user to reorder the columns of the TreeList by dragging, set the Reorderable()
method to true. For a runnable example, refer to the demo on implementing column reordering in the
TreeList.
.Reorderable(reorderable => reorderable.Columns(true))
See Also
Column Reordering by the TreeList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
408
Telerik UI for ASP.NET Core
Custom Commands
You can implement custom commands for handling the records of the TreeList.
To include a command column which will render a button for triggering the command in the column
cells:
.Columns(columns =>
{
columns.Add().Width(300).Command(c =>
{
c.Custom().Name("details").Text("View Details").Click("showDetails");
});
})
2. Wire the click event of the button to a JavaScript function which will receive the
corresponding TreeList data item as an argument. In the function definition, handle the
command.
<script type="text/javascript">
function showDetails(e) {
alert("Custom command button clicked!");
}
</script>
See Also
Server-Side API
409
Telerik UI for ASP.NET Core
Scrolling
By default, scrolling in the TreeList is enabled.
To achieve a maximum level of accessibility with assistive technologies for the TreeList, disable its
scrolling feature.
The enabled scrolling functionality does not guarantee the rendering of scrollbars because scrolling
requires you to define some of the TreeList dimensions:
To achieve vertical scrolling, set a height to the TreeList. If the height is not defined, the
TreeList will have to expand vertically to show all its rows.
To achieve horizontal scrolling, you have to explicitly define the widths of all columns in
pixels and their sum must exceed the width of the TreeList.
When scrolling is enabled, the TreeList renders two tables—one for the header area and one for the
scrollable data area. This ensures that the header area of the TreeList is always visible during
vertical scrolling. Take the two tables into account when you need to manually make JavaScript or
CSS updates to the Grid tables.
<div class="k-widget k-grid k-treelist">
<div class="k-grid-header">
<div class="k-grid-header-wrap">
<table>...</table>
</div>
</div>
<div class="k-grid-content">
<table>...</table>
</div>
</div>
See Also
Server-Side API
410
Telerik UI for ASP.NET Core
TreeList Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
The globalization functionality of the TreeList is enabled through the localization of its messages.
See Also
Globalization by Telerik UI for ASP.NET Core
Server-Side API
411
Telerik UI for ASP.NET Core
Localization
Localization is the process of adapting software to meet the requirements of local markets and
different languages.
To translate the messages of the TreeList, use either of the following approaches:
Register a script before the initialization of the TreeList itself, for example, <script
src="https://kendo.cdn.telerik.com/<version>/js/messages/kendo.messages
.es-ES.min.js"></script>.
Reference a file, for example, <script
src="~/lib/kendo-ui/js/cultures/kendo.messages.es-ES.min.js"></script>.
See Also
Localization by Telerik UI for ASP.NET Core
Server-Side API
412
Telerik UI for ASP.NET Core
TreeList Accessibility
The TreeList is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in UI for ASP.NET Core.
Section 508
The TreeList is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for jQuery.
WCAG 2.1
The TreeList supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1.
See Also
WCAG 2.1 Support by the TreeList HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the TreeList HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the TreeList HtmlHelper for ASP.NET Core
Accessibility Compliance in Telerik UI for ASP.NET Core
413
Telerik UI for ASP.NET Core
Keyboard Navigation
By default, the keyboard navigation of the TreeList is disabled.
For a complete example, refer to the demo on using the keyboard navigation of the TreeList.
The TreeList supports its keyboard navigation functionality through the Navigatable() method.
When enabled, you can initially select a row or cell and then move within the TreeList by using the
Arrow keys. The navigation occurs at a cell level regardless of what the Selectable() mode is. To
select the current row or cell, press Space.
The following example demonstrates how to enable the key navigation in the TreeList.
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryModel>()
.Name("treelist")
/* Other configuration. */
.Navigatable()
)
The keyboard navigation of the TreeList works by listening to the keydown events on the wrapper
element of the helper. Its behavior is based on the assumption that whatever the user does is in
accordance with the currently focused TreeList cell and not with the focused element of the
browser. If the data cells of the TreeList contain hyperlinks that have to be activated through the
keyboard:
To return the focus on the table cell, press Esc. In order for the hyperlinks to be inaccessible through
tabbing, set the tabindex="-1" attribute to the custom hyperlinks.
You can also avoid the procedure and bypass the keyboard navigation of the TreeList, access the
custom hyperlinks with tabbing, and activate them with Enter. To achieve this, prevent the keydown
event bubbling of the custom hyperlinks. As a result, the Enter key-presses will be unnoticed by the
TreeList.
See Also
Keyboard Navigation by the TreeList HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
414
Telerik UI for ASP.NET Core
The DataSource is an abstraction for using local data or remote data. In most cases, the DataSource
definition is declared as part of the configurations for the Telerik UI HTML Helpers. The standalone
DataSource HtmlHelper is suitable for scenarios that require a shared data source.
@(Html.Kendo().DataSource<OrderViewModel>()
.Name("myDataSource")
.Ajax(d=>d.Read(r => r.Action("ReadOrders", "Home")))
)
<script>
myDataSource.read(); // A POST request will be sent to the HomeController
ReadOrders action.
</script>
public IActionResult ReadOrders([DataSourceRequest]DataSourceRequest request)
{
// Orders can be IQueriable or IEnumerable.
return Json(orders.ToDataSourceResult(request));
}
Basic Configuration
You can declare the DataSource HtmlHelper configuration options by using the available
methods—for example, you can define the page size, page, sort order, filter, group, aggregates, and
the model. The configuration accepts the definition for all CRUD operations and facilitates the
sending of additional data such as the AntiForgeryTokens.
@(Html.AntiForgeryToken())
<script>
// Send the forgery tokens as additional data.
function forgeryTokens() {
return kendo.antiForgeryTokens();
}
</script>
@(Html.Kendo().DataSource<OrderViewModel>()
415
Telerik UI for ASP.NET Core
.Name("myDataSource")
.Ajax(dataSource =>
{
dataSource
.Read(read => read.Action("ReadOrders", "Home").Data("forgeryTokens"))
.Sort(sort => sort.Add(field => field.ShipCountry).Ascending())
.Filter(filter=>filter.Add(field=>field.ShipCountry).StartsWith("A"))
.Group(group=>group.Add(field=>field.OrderID))
.PageSize(20)
.ServerOperation(true)
.Model(model =>
{
model.Id(field => field.OrderID);
model.Field(field => field.OrderID).Editable(false);
model.Field(field => field.ShipCountry).DefaultValue("USA");
});
})
)
<script>
myDataSource.fetch();
</script>
See Also
Basic Usage of the DataSource HtmlHelper for ASP.NET Core (Demo)
Server-Side API
416
Telerik UI for ASP.NET Core
Types
The DataSource HtmlHelper supports built-in types of data binding.
Ajax
WebAPI
Custom
Ajax DataSource
The Ajax DataSource type of data binding is the most popular data source type and performs Ajax
requests to retrieve or update data. It formats the request filter, sort, group, page, page size, and
aggregates, and, out of the box, binds the model to a controller which expects a
[DataSourceRequest]DataSourceRequest requestparameter. This allows you to use the
ToDataSourceResult()extension method and to return a collection that corresponds to the
request without having to deal with data operations programmatically.
@(Html.Kendo().DataSource<OrderViewModel>()
.Name("myDataSource")
.Ajax(dataSource =>
{
dataSource
.Read(read => read.Action("ReadOrders", "Home"))
.Create(create => create.Action("CreateOrders", "Home"))
.Update(update => update.Action("UpdateOrders", "Home"))
.Destroy(destroy => destroy.Action("DestroyOrders", "Home"))
.Sort(sort => sort.Add(field => field.ShipCountry).Ascending())
.Filter(filter=>filter.Add(field=>field.ShipCountry).StartsWith("A"))
.Group(group=>group.Add(field=>field.OrderID))
.Aggregates(aggregates=>aggregates.Add(field=>field.ShipCountry).Count())
.PageSize(2)
.ServerOperation(true)
.Model(model =>
{
model.Id(field => field.OrderID);
model.Field(field => field.OrderID).Editable(false);
model.Field(field => field.ShipCountry).DefaultValue("USA");
});
})
)
<script>
myDataSource.read(); // A POST request will be sent to the HomeController
ReadOrders action
</script>
417
Telerik UI for ASP.NET Core
public IActionResult ReadOrders([DataSourceRequest]DataSourceRequest request)
{
// Orders can be IQueriable or IEnumerable.
// The result is a filtered, paged, grouped, and sorted collection.
var result = orders.ToDataSourceResult(request);
// response object : { AggregateResults: [], Data: [{},{}], Errors: null,
Total: 7 }
return Json(result);
}
WebAPI DataSource
The WebAPI DataSource type of data binding is designed for WebAPI projects and works in the
same way as the Ajax data source.
@(Html.Kendo().DataSource<OrderViewModel>()
.Name("myDataSource")
.WebApi(dataSource =>
{
dataSource
.Read(read => read.Action("Get", "Product"))
.Create(create => create.Action("Post", "Product"))
.Update(update => update.Action("Put", "Product", new { id = "{0}"} ))
.Destroy(destroy => destroy.Action("DELETE", "Product", new { id = "{0}" }))
.PageSize(2)
.ServerOperation(true)
.Model(model =>
{
model.Id(field => field.OrderID);
model.Field(field => field.OrderID).Editable(false);
});
})
)
<script>
myDataSource.read(); // A GET request will be sent to the ProductController Get
action
</script>
[HttpGet]
public DataSourceResult Get([DataSourceRequest]DataSourceRequest request)
{
// Orders can be IQueriable or IEnumerable.
// The result is a filtered, paged, grouped, and sorted collection.
var result = orders.ToDataSourceResult(request);
// response object : { AggregateResults: [], Data: [{},{}], Errors: null,
Total: 7 }
return Json(result);
}
Custom DataSource
418
Telerik UI for ASP.NET Core
The Custom DataSource type of data binding is the default type of binding and provides full control
over the client-side API options of the Kendo UI for jQuery DataSource . For example, instead of using
the serverOperation property, which is only applicable for the Ajax and WebApi types of data
binding, you have to separately state the server operations (server-filtering, server-sorting,
server-paging, server-grouping, and server-aggregates).
The custom DataSource type of data binding is suitable for working with the oData and oData-v4
services because of the typeproperty and of the usage of predefined transport and schema settings
for consuming such services. Since the custom type binding is the default type, you can omit it in the
DataSource declaration.
The following example demonstrates how to consume an OData service.
@(Html.Kendo().DataSource<AspNetCoreGrid.Models.OrderViewModel>()
.Name("myDataSource")
.Custom(dataSource =>
{
dataSource
.Type("odata")
.ServerPaging(true)
.ServerFiltering(true)
.ServerSorting(true)
.Transport(transport => {
transport.Read(read => {
read.Url("https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders")
.DataType("jsonp");
});
});
})
)
<script>
myDataSource.fetch();
</script>
See Also
Server-Side API
419
Telerik UI for ASP.NET Core
Headers
As of the Telerik UI for ASP.NET Core R3 2019 release, you can set request headers by using the
Headers configuration option of the DataSource.
The following example demonstrates how to use the Headers option to set a request header.
@(Html.Kendo().DataSource<OrderViewModel>()
.Name("myDataSource")
.Ajax(d => d.Read(r => r.Action("ReadOrders", "Home").Headers(new { header1 =
"test" })))
)
<script>
myDataSource.read(); // The header will be set in the request that is sent to
the HomeController ReadOrders action.
</script>
public IActionResult ReadOrders([DataSourceRequest]DataSourceRequest request)
{
// Orders can be IQueriable or IEnumerable.
return Json(orders.ToDataSourceResult(request));
}
See Also
Server-Side API
420
Telerik UI for ASP.NET Core
The Diagram represents information in a schematic way and according to particular visualization
techniques.
Basic Configuration
1. Return the data as JSON.
public ActionResult _OrgChart()
{
return Json(DiagramDataRepository.OrgChart(), JsonRequestBehavior.AllowGet);
}
2. In the view, configure the Diagram to use the action method that was created in the previous
step.
@(Html.Kendo().Diagram()
.Name("diagram")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("_OrgChart", "Diagram") // Specify the action method and
controller names.
)
.Model(m => m.Children("Items"))
)
.Layout(l => l.Type(DiagramLayoutType.Layered))
)
Events
421
Telerik UI for ASP.NET Core
You can subscribe to all Diagram events. For a complete example on basic Diagram events, refer to
the demo on using the events of the Diagram.
// Place the following after the Diagram for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the Diagram is used to get its client-side instance.
var diagram = $("#diagram").data("kendoDiagram");
});
</script>
See Also
Basic Usage of the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
422
Telerik UI for ASP.NET Core
Remote Binding
The Telerik UI Diagram for ASP.NET Core provides a templating engine and a built-in DataSource
which allow you to quickly set up and implement the data-binding functionality.
Getting Started
To bind the Diagram to remote data, specify the DataSource option. You can either create the data
source outside the Diagram, or pass it in it. If multiple Diagrams are bound to the same data set, you
have to create the data source as an object to which you can refer in the different helpers. If the
Diagram is the only item that is bound to the data, create it inline.
@(Html.Kendo().Diagram()
.Name("diagram")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("_OrgChart", "Diagram")
)
.Model(m => m.Children("Items"))
)
.ShapeDefaults(sd => sd
.Visual("visualTemplate")
)
// Other configuration.
)
public ActionResult _OrgChart()
{
return Json(DiagramDataRepository.OrgChart(), JsonRequestBehavior.AllowGet);
// The returned data from the remote endpoint has to be in JSON format.
}
@(Html.Kendo().Diagram()
.Name("diagram")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("_OrgChart", "Diagram")
)
.Model(m => m.Children("Items"))
)
.Editable(false)
.Layout(l => l.Type(DiagramLayoutType.Layered))
.ShapeDefaults(sd => sd
.Visual("visualTemplate")
)
.ConnectionDefaults(cd => cd
423
Telerik UI for ASP.NET Core
.Stroke(s => s
.Color("#979797")
.Width(2)
)
)
.Events(events => events.DataBound("onDataBound"))
)
<script>
function visualTemplate(options) {
var dataviz = kendo.dataviz;
var g = new dataviz.diagram.Group();
var dataItem = options.dataItem;
g.append(new dataviz.diagram.Rectangle({
width: 210,
height: 75,
stroke: {
width: 0
},
fill: {
gradient: {
type: "linear",
stops: [{
color: dataItem.ColorScheme,
offset: 0,
opacity: 0.5
}, {
color: dataItem.ColorScheme,
offset: 1,
opacity: 1
}]
}
}
}));
g.append(new dataviz.diagram.TextBlock({
text: dataItem.FirstName + " " + dataItem.LastName,
x: 85,
y: 20,
color: "#fff"
}));
g.append(new dataviz.diagram.TextBlock({
text: dataItem.Title,
x: 85,
y: 40,
color: "#fff"
}));
g.append(new dataviz.diagram.Image({
source: "@Url.Content("~/shared/dataviz/diagram/people/")" + dataItem.Image,
x: 3,
y: 3,
width: 68,
height: 68
}));
return g;
}
function onDataBound() {
this.bringIntoView(this.shapes);
}
</script>
424
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
425
Telerik UI for ASP.NET Core
Editing
The Diagram provides editing options which enable you to add tools and shapes to it, and use its
layout options.
Getting Started
To enable the editing functionality of the Diagram:
1. Configure the DataSource for remote CRUD operations. You have to include the model
declaration. The Id is mandatory to indicate which of the fields is the unique identifier.
.DataSource(d => d .ShapeDataSource() .Model(m => { m.Id(s => s.Id); m.Field(s =>
s.Id).Editable(false); m.Field(s => s.JobTitle); m.Field(s => s.Color); }) .Read("ReadShapes",
"DiagramData") .Create("CreateShape", "DiagramData") .Destroy("DestroyShape",
"DiagramData") .Update("UpdateShape", "DiagramData") )
2. Configure the ConnectionsDataSource for remote CRUD operations. Without setting the
ConnectionsDataSource, editing is disabled.
Model Fields
The shape model provides the following fields:
id (Number)—A mandatory field. Represents the unique identifier of the shape. A shape
without an id field will not be connected.
type (String)—The shape type.
text (String)—The shape text.
x (Number)—The x position of the shape.
y (Number)—The y position of the shape.
width (Number)—The shape width.
height (Number)—The shape height.
See Also
Editing in the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
426
Telerik UI for ASP.NET Core
Layout
The layout of the Diagram is its automatic organization based on the way its shapes are connected.
Getting Started
The Layout() method is the gateway to a variety of layout algorithms.
The following example demonstrates how the Layout method generates a Diagram with a tree-like
layout.
@(Html.Kendo().Diagram()
.Name("diagram")
.DataSource(dataSource => dataSource
.Read(read => read.Action("_DiagramTree", "Diagram")).Model(m =>
m.Children("Items"))
)
.Layout(l => l
.Type(DiagramLayoutType.Tree) // Set the Layout type.
.Subtype(DiagramLayoutSubtype.Down)
.HorizontalSeparation(30)
.VerticalSeparation(20)
)
.ShapeDefaults(sd => sd
.Width(40)
.Height(40)
)
)
Layout Types
The Diagram supports the following predefined layout types:
427
Telerik UI for ASP.NET Core
minimizes the crossing between layers of shapes. This layout works well when few components
are present and a top-down flow is present. The concept of "flow" in this context refers to a clear
direction of the connections with a minimum of cycles (connections flowing back upstream).
The layered graph layout is a type of graph layout in which the nodes of a directed graph are
drawn in horizontal or vertical layers with the links directed in the complementary direction. It is
also known as Sugiyama or hierarchical graph layout. When the graph is a tree, the layout shrinks
to a standard tree layout and, in this way, can be considered as an extension to the classic tree
layout.
See Also
Editing in the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
428
Telerik UI for ASP.NET Core
Shapes
The Diagram enables you to add various shapes by using its API reference on shapes.
Getting Started
To add a rectangular shape to the Diagram, call the diagram.addShape(); method which renders
a rectangle in the upper-left corner of the Diagram surface. To change the initial position, call the
addShape() method with an additional Point parameter.
var Point = kendo.dataviz.diagram.Point;
diagram.addShape(new Point(100,220));
To specify additional properties for the Diagram, use the options parameter. The following example
demonstrates how to set the background color of the shape.
diagram.addShape(new Point(100,220), { background: "red" });
The addShape() method also accepts a shape instance and enables you to add a new shape.
var Point = kendo.dataviz.diagram.Point;
var shapeInstance = new kendo.diagram.Shape();
var shape = diagram.addShape(shape);
shape.position(new Point(100,220));
Adding Connections
To connect the shapes, use the connect() method.
var Point = kendo.dataviz.diagram.Point;
var shape1 = diagram.addShape(new Point(100,100));
var shape2 = diagram.addShape(new Point(300,100));
var connection = diagram.connect(shape1, shape2);
See Also
Using the API of the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
429
Telerik UI for ASP.NET Core
PDF Export
The Diagram provides a built-in PDF export functionality.
For a runnable example, refer to the demo on exporting the Diagram to PDF.
Getting Started
To enable PDF export in the Diagram:
1. Introduce a button and handle its click event. Export the Diagram within the handler.
<button class='export-pdf k-button'>Save as PDF</button>
<script>
$(".export-pdf").click(function () {
$("#diagram").getKendoDiagram().saveAsPDF();
});
</script>
To enable PDF export in the Diagram through code, call the saveAsPdfmethod.
<button class='export-pdf k-button'>Save as PDF</button>
@(Html.Kendo().Diagram()
.Name("diagram")
.Pdf(pdf => pdf
.FileName("Kendo UI Diagram Export.pdf")
.ProxyURL(Url.Action("Pdf_Export_Save", "Diagram"))
)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Pdf_Export_Read", "Diagram")
)
.Model(m => m.Children("Items"))
)
.Editable(false)
.Layout(l => l.Type(DiagramLayoutType.Layered))
.ShapeDefaults(sd => sd
.Visual("visualTemplate")
)
.ConnectionDefaults(cd => cd
.Stroke(s => s
.Color("#979797")
.Width(2)
)
)
430
Telerik UI for ASP.NET Core
.Events(events => events.DataBound("onDataBound"))
)
<script>
$(".export-pdf").click(function () {
$("#diagram").getKendoDiagram().saveAsPDF();
});
function visualTemplate(options) {
var dataviz = kendo.dataviz;
var g = new dataviz.diagram.Group();
var dataItem = options.dataItem;
g.append(new dataviz.diagram.Rectangle({
width: 210,
height: 75,
stroke: {
width: 0
},
fill: dataItem.ColorScheme
}));
/*
Use the DejaVu Sans font for display and embedding in the PDF file.
The standard PDF fonts have no support for Unicode characters.
*/
g.append(new dataviz.diagram.TextBlock({
text: dataItem.FirstName + " " + dataItem.LastName,
fontFamily: "DejaVu Sans",
fontSize: "14px",
x: 85,
y: 20,
fill: "#fff"
}));
g.append(new dataviz.diagram.TextBlock({
text: dataItem.Title,
fontFamily: "DejaVu Sans",
fontSize: "14px",
x: 85,
y: 40,
fill: "#fff"
}));
g.append(new dataviz.diagram.Image({
source: "@Url.Content("~/content/dataviz/diagram/people/")" + dataItem.Image,
x: 3,
y: 3,
width: 68,
height: 68
}));
return g;
}
function onDataBound() {
this.bringIntoView(this.shapes);
}
</script>
431
Telerik UI for ASP.NET Core
See Also
PDF Export of the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
432
Telerik UI for ASP.NET Core
Advanced Export
The Telerik UI Diagram for ASP.NET Core provides options for exporting its content to PDF and SVG,
and as an Image.
<button class='export-pdf k-button'>Export as PDF</button>
<button class='export-img k-button'>Export as Image</button>
<button class='export-svg k-button'>Export as SVG</button>
@(Html.Kendo().Diagram()
.Name("diagram")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Export_Read", "Diagram")
)
.Model(m => m.Children("Items"))
)
.Editable(false)
.Layout(l => l.Type(DiagramLayoutType.Layered))
.ShapeDefaults(sd => sd
.Visual("visualTemplate")
)
.ConnectionDefaults(cd => cd
.Stroke(s => s
.Color("#979797")
.Width(2)
)
)
.Events(events => events.DataBound("onDataBound"))
)
<script>
$(".export-pdf").click(function () {
var diagram = $("#diagram").getKendoDiagram();
diagram.exportPDF({ paperSize: "auto", margin: { left: "1cm", top: "1cm",
right: "1cm", bottom: "1cm" } }).done(function (data) {
kendo.saveAs({
dataURI: data,
fileName: "diagram.pdf",
proxyURL: "@Url.Action("Export_Save", "Diagram")"
});
});
});
$(".export-img").click(function () {
var diagram = $("#diagram").getKendoDiagram();
diagram.exportImage().done(function (data) {
kendo.saveAs({
dataURI: data,
fileName: "diagram.png",
proxyURL: "@Url.Action("Export_Save", "Diagram")"
});
});
});
$(".export-svg").click(function () {
var diagram = $("#diagram").getKendoDiagram();
diagram.exportSVG().done(function (data) {
kendo.saveAs({
433
Telerik UI for ASP.NET Core
dataURI: data,
fileName: "diagram.svg",
proxyURL: "@Url.Action("Export_Save", "Diagram")"
});
});
});
</script>
<script>
function visualTemplate(options) {
var dataviz = kendo.dataviz;
var g = new dataviz.diagram.Group();
var dataItem = options.dataItem;
g.append(new dataviz.diagram.Rectangle({
width: 210,
height: 75,
stroke: {
width: 0
},
fill: dataItem.ColorScheme
}));
g.append(new dataviz.diagram.TextBlock({
text: dataItem.FirstName + " " + dataItem.LastName,
x: 85,
y: 20,
color: "#fff"
}));
g.append(new dataviz.diagram.TextBlock({
text: dataItem.Title,
x: 85,
y: 40,
color: "#fff"
}));
g.append(new dataviz.diagram.Image({
source: "@Url.Content("~/content/dataviz/diagram/people/")" + dataItem.Image,
x: 3,
y: 3,
width: 68,
height: 68
}));
return g;
}
function onDataBound() {
this.bringIntoView(this.shapes);
}
</script>
See Also
Advanced Export of the Diagram HtmlHelper for ASP.NET Core (Demo)
Server-Side API
434
Telerik UI for ASP.NET Core
The Map displays geospatial information organized in layers and is supported for both desktop and
mobile devices. It also provides tile layers, shape (vector) layers, and marker layers.
@(Html.Kendo().Map()
.Name("map")
.Center(35.268107, -95.744821)
.Zoom(2)
.Layers(layers =>
{
layers.Add()
.Type(MapLayerType.Tile)
.UrlTemplate("http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#=
y #.png")
.Subdomains("a", "b", "c")
.Attribution("© <a href='http://osm.org/copyright'>OpenStreetMap
contributors</a>");
})
.Markers(markers =>
{
markers.Add()
.Location(30.268107, -97.744821)
.Shape(MapMarkersShape.PinTarget)
.Tooltip(tooltip => tooltip.Content("Austin, TX"));
})
)
public partial class MapController : BaseController
{
[Demo]
public IActionResult Index()
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration for the Map HtmlHelper.
435
Telerik UI for ASP.NET Core
<input id="zoomLevel"/>
<button id="zoom" class="k-button">zoom()</button>
@(Html.Kendo().Map()
.Name("map")
.Center(30.268107, -97.744821)
.Zoom(3)
.Layers(layers =>
{
layers.Add()
.Type(MapLayerType.Tile)
.UrlTemplate("http://tile2.opencyclemap.org/transport/#= zoom #/#= x #/#= y
#.png")
.Subdomains("a", "b", "c")
.Attribution("© <a href='http://osm.org/copyright'>OpenStreetMap
contributors</a>." +
"Tiles courtesy of <a href='http://www.opencyclemap.org/'>Andy Allan</a>");
})
)
<script>
$("#zoom").click(function (e) {
var map = $("#map").data("kendoMap")
map.zoom(
parseInt($("#zoomLevel").val(), 10)
);
});
</script>
Events
For a complete example on basic Map events, refer to the demo on using the events of the Map.
See Also
Basic Usage of the Map HtmlHelper for ASP.NET Core (Demo)
Server-Side API
436
Telerik UI for ASP.NET Core
The AutoComplete provides suggestions depending on the typed text and allows multiple value
entries.
@(Html.Kendo().AutoComplete()
.Name("autocomplete")
.DataTextField("ProductName")
.Filter("contains")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read", "AutoComplete")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
<script type="text/javascript">
function onAdditionalData() {
return {
text: $("#autocomplete").val()
};
}
</script>
public class AutoCompleteController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult Products_Read(string text)
{
var result = GetProducts();
if (!string.IsNullOrEmpty(text))
{
result = result.Where(p => p.ProductName.Contains(text)).ToList();
}
437
Telerik UI for ASP.NET Core
return Json(result);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var result = Enumerable.Range(0, 50).Select(i => new ProductViewModel
{
ProductID = "" + i,
ProductName = "Product " + i
});
return result;
}
}
Basic Configuration
The following example demonstrates the basic configuration of the AutoComplete HtmlHelper.
@(Html.Kendo().AutoComplete()
.Name("autocomplete")
.DataTextField("ProductName")
.Placeholder("Type a product name")
.Template("#= ProductID # | For: #= ProductName #")
.HeaderTemplate("<div class=\"dropdown-header k-widget k-header\">" +
"<span>Products</span>" +
"</div>")
.FooterTemplate("Total <strong>#: instance.dataSource.total() #</strong> items
found")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.Height(520)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read", "Home")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
<script type="text/javascript">
function onAdditionalData() {
return {
text: $("#autocomplete").val()
};
}
</script>
438
Telerik UI for ASP.NET Core
Templates
Virtualization
Accessibility
Events
For a complete example on basic AutoComplete events, refer to the demo on using the events of the
AutoComplete.
// Place the following after your Telerik UI AutoComplete for ASP.NET Core
declaration.
<script>
$(document).ready(function() {
// The Name() of the AutoComplete is used to get its client-side instance.
var autocomplete = $("#autocomplete").data("kendoAutoComplete");
});
</script>
See Also
Basic Usage of the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Using the API of the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Server-Side API
439
Telerik UI for ASP.NET Core
Data Binding
The AutoComplete provides a set of options for binding it to data.
Ajax binding
Server binding
Custom binding
Model binding
See Also
Server-Side API
440
Telerik UI for ASP.NET Core
Ajax Binding
The AutoComplete provides support for remote data binding by using a DataSource configuration
object. You can configure the AutoComplete to get its data from a remote source by making an
AJAX request.
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products);
}
2. Add the AutoComplete to the view and configure its DataSource to use remote data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().AutoCompleteFor(m => m.ProductName)
.Filter("contains")
.DataTextField("ProductName")
.Placeholder("Select product...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Local Data Binding
Server-Side API
441
Telerik UI for ASP.NET Core
Server Binding
Local data is the data that is available on the client when the AutoComplete is initialized.
You can bind the AutoComplete locally on the server by passing the appropriate collection to the
HTML helper BindTo() method.
public IActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the AutoComplete to the view and bind it to the data that is saved in ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().AutoCompleteFor(m => m.ProductName)
.DataTextField("ProductName")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
See Also
Ajax Data Binding
Ajax Data Binding by the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Server-Side API
442
Telerik UI for ASP.NET Core
Custom Binding
You can use a custom DataSource and bind the AutoComplete to a ToDataSourceResult instance.
public ActionResult Index()
{
return View();
}
3. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts([DataSourceRequest] DataSourceRequest request)
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products.ToDataSourceResult(request));
}
@(Html.Kendo().AutoComplete()
.Name("productAutoComplete")
.DataTextField("ProductName") // Specify which property of the Product to
be used by the autocomplete as a text.
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.Type("aspnetmvc-ajax") // Set this type if you want to use
DataSourceRequest and ToDataSourceResult instances.
.Transport(transport =>
{
transport.Read("GetProducts", "Home");
})
.Schema(schema =>
{
schema.Data("Data") // Define the
[data](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configur
ation-schema.data) option.
.Total("Total"); // Define the
[total](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configu
ration-schema.total) option.
});
443
Telerik UI for ASP.NET Core
})
)
@(Html.Kendo().AutoComplete()
.Name("productAutoComplete")
.DataTextField("ProductName") // Specify which property of the Product will be
used by the AutoComplete.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "Home")
.Data("onAdditionalData");
});
})
)
<script>
function onAdditionalData() {
return {
text: $("#productAutoComplete").val()
};
}
</script>
public JsonResult GetProducts(string text)
{
var northwind = new SampleEntities();
var products = northwind.Products.Select(product => new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitPrice = product.UnitPrice ?? 0,
UnitsInStock = product.UnitsInStock ?? 0,
UnitsOnOrder = product.UnitsOnOrder ?? 0,
Discontinued = product.Discontinued
});
if (!string.IsNullOrEmpty(text))
{
products = products.Where(p => p.ProductName.Contains(text));
}
return Json(products, JsonRequestBehavior.AllowGet);
}
444
Telerik UI for ASP.NET Core
See Also
Custom Binding by the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Server-Side API
445
Telerik UI for ASP.NET Core
Model Binding
You can implement model binding both with local dataand remote data.
Local Data
Local data is the data that is available on the client when the AutoComplete is initialized.
public ActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the AutoComplete to the view and bind it to the data that is saved in ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().AutoCompleteFor(m => m.ProductName)
.DataTextField("ProductName")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Remote Data
You can configure the AutoComplete to get its data from a remote source by making an AJAX
request.
446
Telerik UI for ASP.NET Core
public ActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products, JsonRequestBehavior.AllowGet);
}
2. Add the AutoComplete to the view and configure its DataSource to use remote data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().AutoCompleteFor(m => m.ProductName)
.Filter("contains")
.DataTextField("ProductName")
.Placeholder("Select product...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Server-Side API
447
Telerik UI for ASP.NET Core
Grouping Overview
The AutoComplete enables you to bind it to a grouped data source.
To group the data, define a group datasource expression which uses a custom DataSource
configuration, and specify the field by which the AutoComplete will be grouped. For a runnable
example, refer to the demo on grouping in the AutoComplete.
The data source sorts the grouped data either in ascending or descending order. To persist a
specific group order, use the server grouping feature. To define the serverGrouping option, use the
ServerGrouping method of the DataSource.
The following example demonstrates how to group the data in the AutoComplete by country.
```
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataSource(source => source
.Custom()
.Group(g => g.Add("Country", typeof(string)))
.Transport(transport => transport
.Read(read =>
{
read.Action("Grouping_GetCustomers", "Home");
}))
)
.DataTextField("ContactName")
)
```
See Also
Grouping by the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Server-Side API
448
Telerik UI for ASP.NET Core
Templates
The AutoComplete provides full control over the way an item, the popup header and the popup footer
is rendered through the Kendo UI for jQuery templates.
For more information on the capabilities and syntax of the templates, refer to this documentation
article. For a runnable example, refer to the demo on customizing the templates in the AutoComplete .
Basic Usage
The following example demonstrates how to customize the AutoComplete by declaring an inline
string.
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.Template("<span><h3>#: data.ContactName #</h3><p>#: data.CompanyName
#</p></span>")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "Home");
});
})
)
The following example demonstrates how to customize the DropDownList by referencing a script
tag by its id.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- AutoComplete initialization -->
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.TemplateId("itemTemplate") //Reference to the template
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "Home");
});
})
)
Item Template
449
Telerik UI for ASP.NET Core
The item template manages the way the list items of a AutoComplete are rendered.
The following example demonstrates how to define an item template and how to evaluate it against
the dataItem.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- AutoComplete initialization -->
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.TemplateId("itemTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "Home");
});
})
)
Header Template
The header template manages the way the popup header of a AutoComplete is rendered.
<!-- Template -->
<script id="headerTemplate" type="text/x-kendo-template">
<strong>Header</strong>
</script>
<!-- AutoComplete initialization -->
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.HeaderTemplateId("headerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Footer Template
The footer template manages the way the popup footer of a AutoComplete is rendered. The footer is
re-rendered on every change of the Data Source. The context of the template is the widget itself.
<!-- Template -->
<script id="footerTemplate" type="text/x-kendo-template">
450
Telerik UI for ASP.NET Core
Total <strong>#: instance.dataSource.total() #</strong> items found
</script>
<!-- AutoComplete initialization -->
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.FooterTemplateId("footerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "Home");
});
})
)
No-Data Templates
The AutoComplete displays noDataTemplate in the popup when the data source is empty.
<!-- Template -->
<script id="noDataTemplate" type="text/x-kendo-template">
<strong>No Data!</strong>
</script>
<!-- AutoComplete initialization -->
@(Html.Kendo().AutoComplete()
.Name("customers")
.DataTextField("ContactName")
.NoDataTemplateId("noDataTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "Home");
});
})
)
See Also
Customizing Templates in the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Server-Side API
451
Telerik UI for ASP.NET Core
Virtualization
You can configure an AutoComplete to use virtualization.
The value to which the AutoComplete will be bound on the server can only be of a primitive type or
an enum value.
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
[HttpPost]
public IActionResult ProductsVirtualization_Read([DataSourceRequest]
DataSourceRequest request)
{
return Json(GetProducts().ToDataSourceResult(request));
}
public IActionResult Products_ValueMapper(int[] values)
{
var indices = new List<int>();
if (values != null && values.Any())
{
var index = 0;
foreach (var product in GetProducts())
{
if (values.Contains(product.ProductID))
{
indices.Add(index);
}
index += 1;
}
}
return Json(indices);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
452
Telerik UI for ASP.NET Core
}
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().AutoCompleteFor(m => m.ProductName)
.Filter("contains")
.DataTextField("ProductName")
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("ProductsVirtualization_Read", "Home");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
)
<script>
function valueMapper(options) {
$.ajax({
url: "@Url.Action("Products_ValueMapper", "Home")",
data: convertValues(options.value),
success: function (data) {
options.success(data);
}
});
}
function convertValues(value) {
var data = {};
value = $.isArray(value) ? value : [value];
for (var idx = 0; idx < value.length; idx++) {
data["values[" + idx + "]"] = value[idx];
}
return data;
}
</script>
See Also
Virtualization by the AutoComplete HtmlHelper for ASP.NET Core (Demo)
453
Telerik UI for ASP.NET Core
Server-Side API
454
Telerik UI for ASP.NET Core
AutoComplete Accessibility
The AutoComplete is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The AutoComplete is compliant with the Section 508 requirements. For more information, refer to
the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The AutoComplete supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the AutoComplete HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
455
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the AutoComplete is always available.
For a complete example, refer to the demo on keyboard navigation of the AutoComplete.
See Also
Keyboard Navigation in the AutoComplete HtmlHelper for ASP.NET Core (Demo)
Accessibility in the AutoComplete HtmlHelper for ASP.NET Core
456
Telerik UI for ASP.NET Core
The ColorPalette provides suggestions depending on the typed text and allows multiple value
entries.
@(Html.Kendo().ColorPalette()
.Name("colorpalette") // The name of the ColorPalette is mandatory. It
specifies the "id" attribute of the widget.
.Value("#ff0000") // Set the value of the ColorPalette.
)
Events
You can subscribe to all ColorPalette events.
@(Html.Kendo().ColorPalette()
.Name("colorpalette")
.Events(e => e
.Change("colorpalette_change")
)
)
<script>
function colorpalette_change(e) {
// Handle the change event.
var colorpalette = this;
console.log(colorpalette.value());
}
</script>
457
Telerik UI for ASP.NET Core
@(Html.Kendo().ColorPalette()
.Name("colorpalette")
.Events(e => e
.Change(@<text>
function(e) {
// Handle the change event inline.
console.log(e.sender.value());
}
</text>)
)
)
// Place the following after your Telerik UI ColorPalette for ASP.NET Core
declaration.
<script>
$(function() {
// The Name() of the ColorPalette is used to get its client-side instance.
var colorpalette = $("#colorpalette").data("kendoColorPalette");
});
</script>
See Also
Basic Usage of the ColorPalette HtmlHelper for ASP.NET Core (Demo)
Using the Palette Presets in the ColorPalette HtmlHelper for ASP.NET Core (Demo)
Server-Side API
458
Telerik UI for ASP.NET Core
@(Html.Kendo().ColorPicker()
.Name("colorpicker") // The name of the ColorPicker is mandatory. It specifies
the "id" attribute of the widget.
.Value("#ff0000") // Set the value of the ColorPicker.
)
Events
You can subscribe to all ColorPicker events. For a complete example on basic ColorPicker events,
refer to the demo on using the events of the ColorPicker.
@(Html.Kendo().ColorPicker()
.Name("colorpicker")
.Events(e => e
.Open("colorpicker_open")
.Close("colorpicker_close")
.Select("colorpicker_select")
.Change("colorpicker_change")
)
)
<script>
// The ColorPicker instance is available as an e.sender or this.
function colorpicker_open(e) {
// Handle the open event.
}
function colorpicker_close(e) {
// Handle the close event.
}
function colorpicker_select(e) {
// Handle the select event.
459
Telerik UI for ASP.NET Core
}
function colorpicker_change(e) {
// Handle the change event.
}
</script>
@(Html.Kendo().ColorPicker()
.Name("colorpicker")
.Events(e => e
.Open(@<text>
function(e) {
//Handle the open event inline.
}
</text>)
.Close(@<text>
function(e) {
//Handle the close event inline.
}
</text>)
.Select(@<text>
function(e) {
//Handle the select event inline.
}
</text>)
.Change(@<text>
function(e) {
//Handle the change event inline.
}
</text>)
)
)
// Place the following after the ColorPicker for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the ColorPicker is used to get its client-side instance.
var colorpicker = $("#colorpicker").data("kendoColorPicker");
});
</script>
See Also
Basic Usage of the ColorPicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
460
Telerik UI for ASP.NET Core
The ComboBox displays a list of values and allows for a single selection from the list.
@(Html.Kendo().ComboBox()
.Name("combobox")
.DataTextField("ProductName")
.DataValueField("ProductID")
.DataSource(source => {
source.Read(read =>
{
read.Action("Products_Read", "ComboBox");
});
})
)
public class ComboBoxController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult Products_Read()
{
var result = Enumerable.Range(0, 50).Select(i => new ProductViewModel
{
ProductID = "" + i,
ProductName = "Product " + i
});
return Json(result);
}
}
Basic Configuration
The following example demonstrates the basic configuration of the ComboBox HtmlHelper.
@(Html.Kendo().ComboBox()
461
Telerik UI for ASP.NET Core
.Name("combobox")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%" })
.Filter("contains")
.MinLength(3)
.Height(290)
.HeaderTemplate(
"<div class=\"dropdown-header k-widget k-header\">" +
"<span>Products</span>" +
"</div>")
.FooterTemplate("Total <strong>#: instance.dataSource.total() #</strong> items
found")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read2", "DropDownList");
})
.ServerFiltering(false);
})
.Events(e => e
.Change("onChange")
.Select("onSelect")
.Open("onOpen")
.Close("onClose")
.DataBound("onDataBound")
.Filtering("onFiltering")
)
)
<script type="text/javascript">
$(function () {
// The Name() of the ComboBox is used to get its client-side instance.
var combobox = $("#combobox").data("kendoComboBox");
console.log(combobox);
});
</script>
Events
You can subscribe to all ComboBox events. For a complete example on basic ComboBox events,
refer to the demo on using the events of the ComboBox.
462
Telerik UI for ASP.NET Core
@(Html.Kendo().ComboBox()
.Name("combobox")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("combobox_select")
.Change("combobox_change")
)
)
<script>
function combobox_select() {
// Handle the select event.
}
function combobox_change() {
// Handle the change event.
}
</script>
@(Html.Kendo().ComboBox()
.Name("combobox")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select(@<text>
function() {
// Handle the select event inline.
}
</text>)
.Change(@<text>
function() {
// Handle the change event inline.
}
</text>)
)
)
See Also
Basic Usage of the ComboBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the ComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
463
Telerik UI for ASP.NET Core
Data Binding
The ComboBox provides a set of options for binding it to data.
Ajax binding
Server binding
Custom data binding
Model binding
1. Local binding
2. Remote binding
See Also
Server-Side API
464
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Telerik UI ComboBox for Ajax binding to the Northwind Products table which
uses Linq to SQL.
The ToDataSourceResult() extension method modifies the structure of the result and the widget
is not able to bind to it. In this case, return a simple array of data.
public ActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products, JsonRequestBehavior.AllowGet);
}
@(Html.Kendo().ComboBox()
.Name("productDropDownList") // The name of the ComboBox is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the ComboBox as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the ComboBox as a value.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "Home"); // Set the Action and Controller
names.
})
.ServerFiltering(true); // If true, the DataSource will not filter the
data on the client.
})
.SelectedIndex(0) // Select the first item.
)
465
Telerik UI for ASP.NET Core
See Also
Server-Side API
466
Telerik UI for ASP.NET Core
Server Binding
You can configure the Telerik UI ComboBox for server binding to the Northwind Products table which
uses Linq to SQL.
1. Create a new action method and pass the Products table as the model.
public IActionResult Index()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return View(northwind.Products);
}
@model IEnumerable<MvcApplication1.Models.Product>
@(Html.Kendo().ComboBox()
.Name("productComboBox") // The name of the ComboBox is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the ComboBox as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the ComboBox as a value.
.BindTo(Model) // Pass the list of Products to the ComboBox.
.SelectedIndex(10) // Select an item with index 10. Note that the indexes
are zero-based.
)
See Also
Server-Side API
467
Telerik UI for ASP.NET Core
For a runnable example, refer to the demo on customizing the data source of the ComboBox.
public IActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts([DataSourceRequest] DataSourceRequest request)
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products.ToDataSourceResult(request));
}
@(Html.Kendo().ComboBox()
.Name("productComboBox") // The name of the ComboBox is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the ComboBox as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the ComboBox as a value.
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.Type("aspnetmvc-ajax") // Set this type if you want to use
DataSourceRequest and ToDataSourceResult instances.
.Transport(transport =>
{
transport.Read("GetProducts", "Home");
})
.Schema(schema =>
{
schema.Data("Data") // Define the
[data](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configur
ation-schema.data) option.
.Total("Total"); // Define the
[total](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configu
ration-schema.total) option.
468
Telerik UI for ASP.NET Core
});
})
)
See Also
Customizing the Data Source of the ComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
469
Telerik UI for ASP.NET Core
Model Binding
You can implement model binding in the ComboBox with both local dataand remote data.
Local Data
Local data is the data that is available on the client when the ComboBox is initialized.
public IActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the ComboBox to the view and bind it to the data that is saved in the ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().ComboBoxFor(m => m.ProductID)
.DataValueField("ProductID")
.DataTextField("ProductName")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Remote Data
You can configure the ComboBox to get its data from a remote source by making an AJAX request.
470
Telerik UI for ASP.NET Core
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products, JsonRequestBehavior.AllowGet);
}
2. Add the ComboBox to the view and configure its DataSource to use remote data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().ComboBoxFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Placeholder("Select product...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Server-Side API
471
Telerik UI for ASP.NET Core
Grouping Overview
The ComboBox enables you to bind it to a grouped data source.
To group the data, define a group datasource expression which uses a custom DataSource
configuration, and specify the field by which the ComboBox will be grouped. For a runnable example,
refer to the demo on grouping in the ComboBox.
The data source sorts the grouped data either in ascending or descending order. To persist a
specific group order, use the server grouping feature. To define the serverGrouping option, use the
ServerGrouping method of the DataSource.
The following example demonstrates how to group the ComboBox data by country.
@(Html.Kendo().ComboBox()
.Name("customers")
.DataSource(source => source
.Custom()
.Group(g => g.Add("Country", typeof(string)))
.Transport(transport => transport
.Read(read =>
{
read.Action("Grouping_GetCustomers", "ComboBox");
}))
)
.DataTextField("ContactName")
.DataValueField("CustomerID")
)
See Also
Grouping by the ComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
472
Telerik UI for ASP.NET Core
Templates
The ComboBox provides full control over the way an item, a selected value, or a pop-up header is
rendered through the Kendo UI for jQuery templates.
For more information on the capabilities and syntax of the templates, refer to this documentation
article. For a runnable example, refer to the demo on customizing the templates in the ComboBox.
Basic Usage
The following example demonstrates how to customize the ComboBox by referencing a script tag by
its id.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- ComboBox initialization -->
@(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("itemTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
The following example demonstrates how to customize the ComboBox by declaring an inline string.
@(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.Template("<span><h3>#: data.ContactName #</h3><p>#: data.CompanyName
#</p></span>")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Item Template
473
Telerik UI for ASP.NET Core
The item template manages the way the list items of a ComboBox are rendered.
The following example demonstrates how to define an item template and how to evaluate it against
the dataItem.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("itemTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Header Templates
The header template manages the way the popup header of a ComboBox is rendered.
<!-- Template -->
<script id="headerTemplate" type="text/x-kendo-template">
<strong>Header</strong>
</script>
@(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.HeaderTemplateId("headerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Footer Templates
The footer template manages the way the popup footer of a ComboBox is rendered. The footer is
re-rendered on every change of the Data Source. The context of the template is the widget itself.
<!-- Template -->
<script id="footerTemplate" type="text/x-kendo-template">
474
Telerik UI for ASP.NET Core
Total <strong>#: instance.dataSource.total() #</strong> items found
</script>
@(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.FooterTemplateId("footerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
No-Data Templates
The ComboBox displays noDataTemplate in the popup when the data source is empty.
<!-- Template -->
<script id="noDataTemplate" type="text/x-kendo-template">
<strong>No Data!</strong>
</script>
@(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.NoDataTemplateId("noDataTemplate") //Reference to the template
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
See Also
Customizing Templates in the ComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
475
Telerik UI for ASP.NET Core
Virtualization
Virtualization is useful for displaying large data sets.
The UI virtualization technique uses a fixed amount of list items in the popup list of the widget
regardless of the dataset size. When the list is scrolled, the widget reuses the existing items to
display the relevant data instead of creating new ones. For a runnable example, refer to the demo on
virtualization in the ComboBox.
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
[HttpPost]
public IActionResult ProductsVirtualization_Read([DataSourceRequest]
DataSourceRequest request)
{
return Json(GetProducts().ToDataSourceResult(request));
}
public IActionResult Products_ValueMapper(int[] values)
{
var indices = new List<int>();
if (values != null && values.Any())
{
var index = 0;
foreach (var product in GetProducts())
{
if (values.Contains(product.ProductID))
{
indices.Add(index);
}
index += 1;
}
}
return Json(indices);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
476
Telerik UI for ASP.NET Core
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().ComboBoxFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Placeholder("Select product...")
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("ProductsVirtualization_Read", "Home");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
)
<script>
function valueMapper(options) {
$.ajax({
url: "@Url.Action("Products_ValueMapper", "Home")",
data: convertValues(options.value),
success: function (data) {
options.success(data);
}
});
}
function convertValues(value) {
var data = {};
value = $.isArray(value) ? value : [value];
for (var idx = 0; idx < value.length; idx++) {
data["values[" + idx + "]"] = value[idx];
}
return data;
}
</script>
477
Telerik UI for ASP.NET Core
3. If the AutoBind option of the ComboBox is set to false and you need the widget to display
the model value as selected, set the Text configuration option by passing the field set as
DataTextField to the Text option.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().ComboBoxFor(m => m.ProductID)
.AutoBind(false)
.Text(Model.ProductName)
.DataTextField("ProductName")
// Additional configuration.
)
See Also
Virtualization by the ComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
478
Telerik UI for ASP.NET Core
ComboBox Accessibility
The ComboBox is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The ComboBox is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The ComboBox supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the ComboBox HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the ComboBox HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
479
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the ComboBox is always available.
For a complete example, refer to the demo on keyboard navigation of the ComboBox.
See Also
Keyboard Navigation in the ComboBox HtmlHelper for ASP.NET Core (Demo)
Accessibility in the ComboBox HtmlHelper for ASP.NET Core
480
Telerik UI for ASP.NET Core
The DateInput represents an input field that recognizes and formats scheduling values such as
dates. It provides separate sections for days, months, years, hours, and minutes, and also supports
the customization of date and time formats.
Basic Configuration
The following example demonstrates the basic configuration for the DateInput.
@(Html.Kendo().DateInput()
.Name("dateinput") // The name of the DateInput is mandatory. It specifies the
"id" attribute of the widget.
.Value(DateTime.Today) // Set the value of the DateInput.
)
Events
You can subscribe to all DateInput events. For a complete example on basic DateInput events, refer
to the demo on using the events of the DateInput.
@(Html.Kendo().DateInput()
.Name("dateinput")
.Events(e => e
.Change("dateInput_change")
)
)
<script>
function dateInput_change() {
// Handle the change event.
}
</script>
// Place the following after your Telerik UI DateInput for ASP.NET Core declaration.
<script>
481
Telerik UI for ASP.NET Core
$(function() {
// The Name() of the DateInput is used to get its client-side instance.
var dateInput = $("#dateinput").data("kendoDateInput");
});
</script>
See Also
Basic Usage of the DateInput HtmlHelper for ASP.NET Core (Demo)
Using the API of the DateInput HtmlHelper for ASP.NET Core (Demo)
Server-Side API
482
Telerik UI for ASP.NET Core
The DatePicker enables the user to select a date from a calendar or through a direct input. It
provides options for using custom templates for its Month view, setting minimum and maximum
dates, a start view, and a depth for navigation.
Basic Configuration
The following example demonstrates the basic configuration for the DatePicker HtmlHelper.
@(Html.Kendo().DatePicker()
.Name("datepicker") // The name of the DatePicker is mandatory. It specifies
the "id" attribute of the widget.
.Min(new DateTime(1900, 1, 1)) // Sets the min date of the DatePicker.
.Max(new DateTime(2099, 12, 31)) // Sets the max date of the DatePicker.
.Value(DateTime.Today) // Sets the value of the DatePicker.
)
Events
You can subscribe to all DatePicker events. For a complete example on DatePicker events, refer to
the demo on handling DatePicker events.
@(Html.Kendo().DatePicker()
.Name("datepicker")
.Events(e => e
.Open("datepicker_open")
483
Telerik UI for ASP.NET Core
.Close("datepicker_close")
.Change("datepicker_change")
)
)
<script>
function datepicker_open() {
// Handle the open event.
}
function datepicker_close() {
// Handle the close event.
}
function datepicker_change() {
// Handle the change event.
}
</script>
// Place the following after your Telerik UI DatePicker for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the DatePicker is used to get its client-side instance.
var datepicker = $("#datepicker").data("kendoDatePicker");
});
</script>
See Also
Basic Usage of the DatePicker HtmlHelper for ASP.NET Core (Demo)
Using the API of the DatePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
484
Telerik UI for ASP.NET Core
Disabled Dates
The DatePicker allows you to disable specific days which are not intended to be selected by the end
user such as weekends and national holidays.
For a complete example, refer to the demo on disabling dates in the DatePicker.
@(Html.Kendo().DatePicker()
.Name("weekend-date-picker")
.DisableDates(DayOfWeek.Saturday, DayOfWeek.Sunday)
)
Adding a Function
To disable dates through using a function, set the return value for the date that will be disabled to
true.
@(Html.Kendo().DatePicker()
.Name("national-date-picker")
.DisableDates("disableDates")
)
<script>
function disableDates(date) {
var dates = [
new Date("1/1/2019"),
new Date("1/21/2019"),
new Date("2/18/2019"),
new Date("5/27/2019"),
new Date("7/4/2019"),
new Date("9/2/2019"),
new Date("10/14/2019"),
new Date("11/11/2019"),
new Date("11/28/2019"),
new Date("12/25/2019")
];
if (date && compareDates(date, dates)) {
return true;
} else {
485
Telerik UI for ASP.NET Core
return false;
}
}
function compareDates(date, dates) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getDate() == date.getDate() &&
dates[i].getMonth() == date.getMonth() &&
dates[i].getYear() == date.getYear()) {
return true
}
}
}
</script>
See Also
Disabling Dates in the DatePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
486
Telerik UI for ASP.NET Core
Selected Dates
The DatePicker allows you to render a pre-selected date and also define the minimum and maximum
dates it displays.
For a complete example on how to select ranges using DatePicker, refer to the demo on range
selection.
Telerik UI for ASP.NET Core includes the DateRangePickercomponent that can be used for selecting
date ranges.
The following example demonstrates how to render a DatePicker with an initially selected date and
defined min and max dates. The DatePicker sets the value only if the entered date is within the
defined range and is valid.
@(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(new DateTime(2019, 5, 15))
.Min(new DateTime(2019, 5, 10))
.Min(new DateTime(2019, 6, 18))
)
See Also
Selecting Date Ranges in the DatePicker HtmlHelper for ASP.NET Core (Demo)
Selecting Date Ranges in the DateRangePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
487
Telerik UI for ASP.NET Core
To define the initially rendered view, use the Startoption. To control the navigation depth, use the
Depthoption.
The following example demonstrates how to create a DatePicker that allows the user to select a
month.
@(Html.Kendo().DatePicker()
.Name("datepicker")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
)
See Also
Specifying the Start View and Selection Depth in the DatePicker HtmlHelper for ASP.NET Core
(Demo)
Server-Side API
488
Telerik UI for ASP.NET Core
Validation
The DatePicker is designed to keep its input value unchanged even when the typed date is invalid.
The DatePicker allows you to use different formats for date parsing which require
unrestricted user input. For more information, refer to the ParseFormatsoption.
The DatePicker does not automatically update the typed text when the typed text is invalid.
Such a change in the input value may lead to unexpected behavior.
To validate the input value of the DatePicker on the client, use a client-validation framework such as
the Kendo UI Validator for jQuery. In this way, you can provide an error message to end users which
prompts them to do the right actions for them to resolve the issue. For more details, refer to the
demo on custom validation.
See Also
Server-Side API
489
Telerik UI for ASP.NET Core
Calendar Types
By default, the DatePicker works with JavaScript Date objects which support only the Gregorian
calendar.,
As a result, the DatePicker does not support other calendar types such as Lunar.
To work around the default behavior of the DatePicker and simulate a different calendar type, use
either of the following approaches:
In both cases, the DatePicker uses the Gregorian calendar date. The second component only
displays the Gregorian date with the Lunar year.
@(Html.Kendo().DatePicker()
.Name("gregorian")
.Value(new DateTime(2000, 11, 10))
)
@(Html.Kendo().DatePicker()
.Name("lunar")
.Min(new DateTime(1400,1,1))
.Value(new DateTime(1497, 11, 10))
)
See Also
Server-Side API
490
Telerik UI for ASP.NET Core
@(Html.Kendo().DatePicker()
.Name("datepicker")
.WeekNumber(true)
.Value("10/10/2019")
)
See Also
Showing the Week Column in the DatePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
491
Telerik UI for ASP.NET Core
DateInput Integration
The DatePicker provides integration options with the Telerik UI for ASP.NET Core DateInputfor the
input element it renders.
To use the DateInput as the input element in a DatePicker, enable the DateInputproperty of the
DatePicker.
@(Html.Kendo().DatePicker()
.Name("datepicker")
.DateInput()
.Value("10/10/2019")
)
See Also
Basic Usage of the DatePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
492
Telerik UI for ASP.NET Core
Templates
The DatePicker provides options for using and customizing its templates.
To customize the cell template in the Month view, use the MonthTemplateproperty. The calendar of
the DatePicker loops over each cell and sets its HTML by using the month content template. You can
implement a dynamic template by using the Datesoption which is passed as an argument to the
month template. For the complete example, refer to the demo on customizing the templates of the
DatePicker.
To modify the footer template of the DatePicker calendar, use the Footerproperty. To remove the
footer, set it to false.
The dates which are out of the Min and Max range are rendered as empty. To change their template,
use the month.emptyoption.
For more information on customizing the aria-label text, refer to the article on accessibility.
See Also
Customizing Templates in the DatePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
493
Telerik UI for ASP.NET Core
DatePicker Accessibility
The DatePicker is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
To customize the aria-label text of the currently focused cell in the calendar, use the
ARIATemplateconfiguration option.
Section 508
The DatePicker is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The DatePicker supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in Telerik UI for ASP.NET Core
See Also
Keyboard Navigation by the DatePicker HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the DatePicker HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
494
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the DatePicker is always available.
For a complete example, refer to the demo on keyboard navigation of the DatePicker.
See Also
Keyboard Navigation in the DatePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in the DatePicker HtmlHelper for ASP.NET Core
495
Telerik UI for ASP.NET Core
The DateRangePicker is a container for holding start and end date inputs. It allows the user to select
a date range from a calendar or through a direct input. The helper also supports custom templates
for its month view, configuration options for minimum and maximum dates, a start view, and a depth
for navigation.
Basic Configuration
The following example demonstrates the basic configuration for the DateRangePicker.
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker") // The name of the DateRangePicker is mandatory. It
specifies the "id" attribute of the DateRangePicker.
.Min(new DateTime(1900, 1, 1)) // Sets the min date of the DateRangePicker.
.Max(new DateTime(2099, 12, 31)) // Sets the min date of the DateRangePicker.
.Range(r => r.Start(DateTime.Now).End(DateTime.Now.AddDays(10))) // Sets the
range of the DateRangePicker.
)
Events
You can subscribe to all DateRangePicker events. For a complete example on basic
DateRangePicker events, refer to the demo on using the events of the DateRangePicker.
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
496
Telerik UI for ASP.NET Core
.Events(e => e
.Open("daterangepicker_open")
.Close("daterangepicker_close")
.Change("daterangepicker_change")
)
)
<script>
function daterangepicker_open() {
// Handle the open event.
}
function daterangepicker_close() {
// Handle the close event.
}
function daterangepicker_change() {
// Handle the change event.
}
</script>
// Place the following after the DateRangePicker for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the DateRangePicker is used to get its client-side instance.
var daterangepicker = $("#daterangepicker").data("kendoDateRangePicker");
});
</script>
See Also
Basic Usage of the DateRangePicker HtmlHelper for ASP.NET Core (Demo)
Using the API of the DateRangePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
497
Telerik UI for ASP.NET Core
Disable Dates
The DateRangePicker allows you to disable specific days which are not intended to be selected by
the end user such as weekends and national holidays.
Setting an Array
To disable dates by setting an array, list the names of the days that will be disabled by using the first
letters from their names in English.
@(Html.Kendo().DateRangePicker()
.Name("dateRangePicker")
.DisableDates(new[] {"we", "th" })
)
Adding a Function
To disable dates by using a function, set the return value for the date that will be disabled to true.
@(Html.Kendo().DateRangePicker()
.Name("dateRangePicker")
.DisableDates("disableDatesHandler")
)
<script type="text/javascript">
function disableDatesHandler(date) {
var disabled = [13, 14, 20, 21];
if (date && disabled.indexOf(date.getDate()) > -1) {
return true;
} else {
return false;
}
}
</script>
See Also
Server-Side API
498
Telerik UI for ASP.NET Core
Selected Dates
The DateRangePicker allows you to define the minimum and maximum dates it displays and also
render a pre-selected date range.
For a complete example on how to select ranges by using the DateRangePicker, refer to the demo on
range selection.
The following example demonstrates how to render a DateRangePicker with an initially selected
range and defined min and max dates.
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker") // The name of the DateRangePicker is mandatory. It
specifies the "id" attribute of the widget.
.Min(new DateTime(2019, 9, 4)) // Sets the min date of the DateRangePicker.
.Max(new DateTime(2099, 12, 31)) // Sets the min date of the DateRangePicker.
.Range(r => r.Start(DateTime.Now).End(DateTime.Now.AddDays(10))) // Sets the range
of the DateRangePicker.
)
See Also
Selecting Date Ranges by Using the DateRangePicker (Demo)
Server-Side API
499
Telerik UI for ASP.NET Core
To define the initially rendered view, use the Start option. To control the navigation depth, use the
Depth option.
The following example demonstrates how to create a DateRangePicker that sets the start of a year
and the navigation depth of a month.
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
.Start(CalendarView.Year)
.Depth(CalendarView.Month)
)
See Also
Server-Side API
500
Telerik UI for ASP.NET Core
Validation
The DateRangePicker is designed to keep its input value unchanged even when the typed date is
invalid.
This behavior is set because the DateRangePicker does not automatically update the typed text
when the typed text is invalid. Such a change in the input value may lead to unexpected behavior.
To validate the input value of the DateRangePicker, use a client-validation framework such as the
Kendo UI Validator for jQuery. In this way, you can provide an error message to end users which
prompts them to do the right actions for them to resolve the issue.
See Also
Server-Side API
501
Telerik UI for ASP.NET Core
Date Formatting
The DateRangePicker allows you to define its date formatting.
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
.Format("{0:dd/MM/yyyy}")
)
See Also
Server-Side API
502
Telerik UI for ASP.NET Core
Calendar Types
By default, the DateRangePicker works with Date objects which support only the Gregoriancalendar.
As a result, the DateRangePicker does not support other calendar types such as Lunar.
To work around the default behavior of the DateRangePicker and simulate a different calendar type,
use either of the following approaches:
See Also
Server-Side API
503
Telerik UI for ASP.NET Core
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
.WeekNumber(true)
.HtmlAttributes(new { style = "width: 100%" })
)
See Also
Server-Side API
504
Telerik UI for ASP.NET Core
DatePicker Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
Localization of messages
Right-to-left support
See Also
Server-Side API
505
Telerik UI for ASP.NET Core
Localization
The DateRangePicker provides options for localizing its user interface by utilizing its Culture
property.
To enable the desired culture, add a reference to the script file before the DateRangePicker is
initialized and include the desired culture in the settings of the helper.
<script
src="https://kendo.cdn.telerik.com/2019.2.619/js/cultures/kendo.culture.de-DE.min.js">
</script>
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
.Culture("de-DE")
)
See Also
Server-Side API
506
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
The following example demonstrates how to set the basic right-to-left configuration for the
DateRangePicker.
@using Kendo.Mvc.UI
<div class="demo-section">
<div class="k-rtl">
@(Html.Kendo().DateRangePicker()
.Name("daterangepicker")
)
</div>
<style>
.demo-section {
width: 400px;
text-align: center;
margin: 50px auto;
padding-top: 50px;
padding-bottom: 50px;
}
</style>
</div>
See Also
Server-Side API
507
Telerik UI for ASP.NET Core
DateRangePicker Accessibility
The DateRangePicker is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG
2.1, and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
To customize the aria-label text of the currently focused cell in the calendar, use the
ARIATemplateconfiguration option.
Section 508
The DateRangePicker is compliant with the Section 508 requirements. For more information, refer to
the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The DateRangePicker supports the standards for providing accessible web content which are set by
the Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the DateRangePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
508
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the DateRangePicker is always available.
For a complete example, refer to the demo on keyboard navigation of the DateRangePicker.
See Also
Keyboard Navigation by the DateRangePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in the DateRangePicker HtmlHelper for ASP.NET Core
509
Telerik UI for ASP.NET Core
The DateTimePicker allows the user to select a value from a calendar, a time drop-down list, or
through direct input.
The DateTimePicker copies any styles and CSS classes from the input element to the wrapper
element.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
)
Events
You can subscribe to all DateTimePicker events. For a complete example on basic DateTimePicker
events, refer to the demo on using the events of the DateTimePicker.
@(Html.Kendo().DateTimePicker()
.Name("datetimepicker")
510
Telerik UI for ASP.NET Core
.Events(e => e
.Open("datetimepicker_open")
.Close("datetimepicker_close")
.Change("datetimepicker_change")
)
)
<script>
function datetimepicker_open() {
// Handle the open event.
}
function datetimepicker_close() {
// Handle the close event.
}
function datetimepicker_change() {
// Handle the change event.
}
</script>
// Place the following after your DateTimePicker for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the DateTimePicker is used to get its client-side instance.
var datetimepicker = $("#datetimepicker").data("kendoDateTimePicker");
});
</script>
See Also
Basic Usage of the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Using the API of the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
511
Telerik UI for ASP.NET Core
Disabled Dates
The DateTimePicker allows you to disable specific days which are not intended to be selected by the
end user such as weekends and national holidays.
For a complete example, refer to the demo on disabling dates in the DateTimePicker.
Setting an Array
To disable dates by setting an array, list the names of days that will be disabled by using the first
letters from their names in English.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.DisableDates(new[] {"we", "th" })
)
Adding a Function
To disable dates by using a function, set the return value for the date that will be disabled to true.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.DisableDates("disableDatesHandler")
)
<script type="text/javascript">
function disableDatesHandler(date){
var disabled = [13,14,20,21];
if (date && disabled.indexOf(date.getDate()) > -1 ) {
return true;
} else {
return false;
}
}
</script>
See Also
Disabling Dates in the DateTimePicker (Demo)
Server-Side API
512
Telerik UI for ASP.NET Core
Selected Dates
The DateTimePicker allows you to render a pre-selected date and also define the minimum and
maximum dates it displays.
For a complete example on how to select ranges by using the DateTimePicker, refer to the demo on
range selection.
Telerik UI for ASP.NET Core includes the DateRangePickercomponent that can be used for selecting
date ranges.
The following example demonstrates how to render a DateTimePicker with an initially selected date
and defined min and max dates. The DateTimePicker sets the value only if the entered date is within
the defined range and is valid.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.Min(new DateTime(1950, 1, 1, 10, 0, 0))
.Max(new DateTime(2050, 1, 1, 20, 0, 0))
)
See Also
Selecting Date Ranges by Using the DateTimePicker (Demo)
Selecting Date Ranges by Using the DateRangePicker (Demo)
Server-Side API
513
Telerik UI for ASP.NET Core
To define the initially rendered view, use the Start option. To control the navigation depth, use the
Depth option.
The following example demonstrates how to create a DateTimePicker that allows the user to select
a month.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
)
See Also
Server-Side API
514
Telerik UI for ASP.NET Core
Validation
The DateTimePicker is designed to keep its input value unchanged even when the typed date is
invalid.
The DateTimePicker allows you to use different formats for date parsing which require
unrestricted user input. For more information, refer to the ParseFormatsoption.
The DateTimePicker does not automatically update the typed text when the typed text is
invalid. Such a change in the input value may lead to unexpected behavior.
To validate the input value of the DateTimePicker, use a client-validation framework such as the
Kendo UI Validator for jQuery. In this way, you can provide an error message to end users which
prompts them to do the right actions for them to resolve the issue.
See Also
Server-Side API
515
Telerik UI for ASP.NET Core
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.Format("{0:dd/MM/yyyy hh:mm tt}")
)
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.TimeFormat("hh:mm:ss tt") // This format will be used to format the predefined
values in the time list.
)
The following example demonstrates how to define the interval (in minutes) between values in the
drop-down list with time slots.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Value(DateTime.Now)
.Interval(15)
)
See Also
Server-Side API
516
Telerik UI for ASP.NET Core
Calendar Types
By default, the DatePicker works with Date objects which support only the Gregoriancalendar.
As a result, the DateTimePicker does not support other calendar types such as Lunar.
To work around the default behavior of the DateTimePicker and simulate a different calendar type,
use either of the following approaches:
See Also
Server-Side API
517
Telerik UI for ASP.NET Core
@(Html.Kendo().DateTimePicker()
.Name("datetimepicker")
.WeekNumber(true)
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width: 100%" })
)
See Also
Rendering Week Number Columns in the DateTimePicker (Demo)
Server-Side API
518
Telerik UI for ASP.NET Core
DateInput Integration
The DatePicker provides integration options with the Telerik UI DateInput for ASP.NET Corefor the
input element it renders.
To use the DateInput as the input element in a DateTimePicker, enable the DateInputproperty of
the DateTimePicker.
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.DateInput(true)
)
See Also
Server-Side API
519
Telerik UI for ASP.NET Core
Templates
The DatePicker provides options for using and customizing its templates.
To customize the cell template in the Month view, use the MonthTemplateproperty. The calendar of
the DateTimePicker loops over each cell and sets its HTML by using the month template. You can
implement a dynamic template by using the Datesoption which is passed as an argument to the
MonthTemplate.Content template. For the complete example, refer to the demo on customizing the
templates of the DateTimePicker.
To modify the footer template of the DatePicker calendar, use the Footerproperty.
For more information on customizing the aria-label text, refer to the article on accessibility.
See Also
Customizing Templates in the DateTimePicker (Demo)
Server-Side API
520
Telerik UI for ASP.NET Core
DatePicker Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
Localization of messages
Right-to-left support
See Also
Globalization Support by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
RTL Support by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
521
Telerik UI for ASP.NET Core
Localization
The DateTimePicker provides options for localizing its user interface by utilizing its Culture
property.
To enable the desired culture, add a reference to the script file before the DateTimePicker is
initialized and include the desired culture in the settings of the helper.
<script
src="https://kendo.cdn.telerik.com/2019.2.619/js/cultures/kendo.culture.de-DE.min.js">
</script>
@(Html.Kendo().DateTimePicker()
.Name("dateTimePicker")
.Culture("de-DE")
)
See Also
Globalization Support by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
522
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the DateTimePicker.
See Also
RTL Support by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
523
Telerik UI for ASP.NET Core
DateTimePicker Accessibility
The DateTimePicker is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
To customize the aria-label text of the currently focused cell in the calendar, use the
ARIATemplateconfiguration option.
Section 508
The DateTimePicker is compliant with the Section 508 requirements. For more information, refer to
the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The DateTimePicker supports the standards for providing accessible web content which are set by
the Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
524
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the DateTimePicker is always available.
For a complete example, refer to the demo on keyboard navigation of the DateTimePicker.
See Also
Keyboard Navigation by the DateTimePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in the DateTimePicker HtmlHelper for ASP.NET Core
525
Telerik UI for ASP.NET Core
The DropDownList displays a list of values and allows for a single selection from the list. The user
input is restricted within the predefined options.
@(Html.Kendo().DropDownList()
.Name("dropdownlist")
.DataTextField("ProductName")
.DataValueField("ProductID")
.DataSource(source => {
source.Read(read =>
{
read.Action("Products_Read", "DropDownList");
});
})
)
public class DropDownListController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult Products_Read()
{
var result = Enumerable.Range(0, 50).Select(i => new ProductViewModel
{
ProductID = "" + i,
ProductName = "Product " + i
});
return Json(result);
}
}
Basic Configuration
The following example demonstrates the basic configuration of the DropDownList HtmlHelper and
how to get the DropDownList instance.
526
Telerik UI for ASP.NET Core
@(Html.Kendo().DropDownList()
.Name("dropdownlist")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%" })
.Filter("contains")
.MinLength(3)
.Height(290)
.HeaderTemplate(
"<div class=\"dropdown-header k-widget k-header\">" +
"<span>Products</span>" +
"</div>")
.FooterTemplate("Total <strong>#: instance.dataSource.total() #</strong> items
found")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read2", "DropDownList");
})
.ServerFiltering(false);
})
.Events(e => e
.Change("onChange")
.Select("onSelect")
.Open("onOpen")
.Close("onClose")
.DataBound("onDataBound")
.Filtering("onFiltering")
)
)
<script type="text/javascript">
$(function () {
// The Name() of the DropDownList is used to get its client-side instance.
var dropdownlist = $("#dropdownlist").data("kendoDropDownList");
console.log(dropdownlist);
});
</script>
Events
You can subscribe to all DropDownList events. For a complete example on basic DropDownList
events, refer to the demo on using the events of the DropDownList.
527
Telerik UI for ASP.NET Core
@(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("dropdownlist_select")
.Change("dropdownlist_change")
)
)
<script>
function dropdownlist_select() {
// Handle the select event.
}
function dropdownlist_change() {
// Handle the change event.
}
</script>
@(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select(@<text>
function() {
// Handle the select event inline.
}
</text>)
.Change(@<text>
function() {
// Handle the change event inline.
}
</text>)
)
)
// Place the following after your Telerik UI DropDownList for ASP.NET Core
declaration.
<script>
$(function() {
// The Name() of the DropDownList is used to get its client-side instance.
var dropdownlist = $("#productDropDownList").data("kendoDropDownList");
});
</script>
528
Telerik UI for ASP.NET Core
See Also
Basic Usage of the DropDownList HtmlHelper for ASP.NET Core (Demo)
Using the API of the DropDownList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
529
Telerik UI for ASP.NET Core
Data Binding
The DropDownList provides a set of options for binding it to data.
Ajax binding
Server binding
Custom data binding
Model binding
1. Local binding
2. Remote binding
See Also
Server-Side API
530
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Telerik UI DropDownList for Ajax binding to the Northwind Products table
which uses Linq to SQL.
The ToDataSourceResult() extension method modifies the structure of the result and the widget
is not able to bind to it. In this case, return a simple array of data.
public ActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products, JsonRequestBehavior.AllowGet);
}
@(Html.Kendo().DropDownList()
.Name("productDropDownList") // The name of the DropDownList is mandatory.
It specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the DropDownList as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the DropDownList as a value.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "Home"); // Set the Action and Controller
names.
})
.ServerFiltering(true); // If true, the DataSource will not filter the
data on the client.
})
.SelectedIndex(0) // Select the first item.
)
531
Telerik UI for ASP.NET Core
See Also
Server-Side API
532
Telerik UI for ASP.NET Core
Server Binding
You can configure the Telerik UI DropDownList for server binding to the Northwind Products table
which uses Linq to SQL.
1. Create a new action method and pass the Products table as the model.
public ActionResult Index()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return View(northwind.Products);
}
@model IEnumerable<MvcApplication1.Models.Product>
@(Html.Kendo().DropDownList()
.Name("productDropDownList") // The name of the DropDownList is mandatory.
It specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the DropDownList as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the DropDownList as a value.
.BindTo(Model) // Pass the list of Products to the DropDownList.
.SelectedIndex(10) // Select an item with index 10. Note that the indexes
are zero-based.
)
See Also
Server-Side API
533
Telerik UI for ASP.NET Core
public ActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts([DataSourceRequest] DataSourceRequest request)
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products.ToDataSourceResult(request));
}
@(Html.Kendo().DropDownList()
.Name("productDropDownList") // The name of the DropDownList is mandatory.
It specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the DropDownList as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the DropDownList as a value.
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.Type("aspnetmvc-ajax") // Set this type if you want to use
DataSourceRequest and ToDataSourceResult instances.
.Transport(transport =>
{
transport.Read("GetProducts", "Home");
})
.Schema(schema =>
{
schema.Data("Data") // Define the
[data](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configur
ation-schema.data) option.
.Total("Total"); // Define the
[total](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configu
ration-schema.total) option.
});
})
)
534
Telerik UI for ASP.NET Core
See Also
Customizing the Data Source of the DropDownList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
535
Telerik UI for ASP.NET Core
Model Binding
You can implement model binding in the DropDownList with both local dataand remote data.
Local Data
Local data is the data that is available on the client when the DropDownList is initialized.
public ActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the DropDownList to the view and bind it to the data that is saved in the ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().DropDownListFor(m => m.ProductID)
.DataValueField("ProductID")
.DataTextField("ProductName")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Remote Data
You can configure the DropDownList to get its data from a remote source by making an AJAX
request.
536
Telerik UI for ASP.NET Core
public ActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products, JsonRequestBehavior.AllowGet);
}
2. Add the DropDownList to the view and configure its DataSource to use remote data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().DropDownListFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.OptionLabel("Select product...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Server-Side API
537
Telerik UI for ASP.NET Core
Grouping Overview
The DropDownList enables you to bind it to a grouped data source.
To group the data, define a group datasource expression which uses a custom DataSource
configuration, and specify the field by which the DropDownList will be grouped. For a runnable
example, refer to the demo on grouping in the DropDownList.
The data source sorts the grouped data either in ascending or descending order. To persist a
specific group order, use the server grouping feature. To define the serverGrouping option, use the
ServerGrouping method of the DataSource.
The following example demonstrates how to group the data in the DropDownList by country.
```
@(Html.Kendo().DropDownList()
.Name("customers")
.DataSource(source => source
.Custom()
.Group(g => g.Add("Country", typeof(string)))
.Transport(transport => transport
.Read(read =>
{
read.Action("Grouping_GetCustomers", "DropDownList");
}))
)
.DataTextField("ContactName")
.DataValueField("CustomerID")
)
```
See Also
Grouping by the DropDownList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
538
Telerik UI for ASP.NET Core
Templates
The DropDownList provides full control over the way an item, a selected value, or a pop-up header is
rendered through the Kendo UI for jQuery templates.
For more information on the capabilities and syntax of the templates, refer to this documentation
article. For a runnable example, refer to the demo on customizing the templates in the DropDownList .
Basic Usage
The following example demonstrates how to customize the DropDownList by declaring an inline
string.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("itemTemplate") //Reference to the template
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
The following example demonstrates how to customize the DropDownList by referencing a script
tag by its id.
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.Template("<span><h3>#: data.ContactName #</h3><p>#: data.CompanyName
#</p></span>")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
539
Telerik UI for ASP.NET Core
Item Template
The item template manages the way the list items of a DropDownList are rendered.
The following example demonstrates how to define an item template and how to evaluate it against
the dataItem.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("itemTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Value Templates
The value template manages the way the selected value of a DropDownList is rendered.
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.ValueTemplateId("valueTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
540
Telerik UI for ASP.NET Core
Header Templates
The header template manages the way the pop-up header of a DropDownList is rendered.
<!-- Template -->
<script id="headerTemplate" type="text/x-kendo-template">
<strong>Header</strong>
</script>
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.HeaderTemplateId("headerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
Footer Templates
The footer template manages the way the pop-up footer of a DropDownList is rendered. The footer is
re-rendered on every change of the Data Source. The context of the template is the widget itself.
<!-- Template -->
<script id="footerTemplate" type="text/x-kendo-template">
Total <strong>#: instance.dataSource.total() #</strong> items found
</script>
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.FooterTemplateId("footerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
No-Data Templates
The DropDownList displays noDataTemplate in the popup when the data source is empty.
541
Telerik UI for ASP.NET Core
When the noDataTemplate option is defined, the DropDownList always opens the popup element.
<!-- Template -->
<script id="noDataTemplate" type="text/x-kendo-template">
<strong>No Data!</strong>
</script>
<!-- DropDownList initialization -->
@(Html.Kendo().DropDownList()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.NoDataTemplateId("noDataTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Template_GetCustomers", "ComboBox");
});
})
)
See Also
Customizing Templates in the DropDownList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
542
Telerik UI for ASP.NET Core
Virtualization
Virtualization is useful for displaying large data sets.
The UI virtualization technique uses a fixed amount of list items in the popup list of the widget
regardless of the dataset size. When the list is scrolled, the widget reuses the existing items to
display the relevant data instead of creating new ones. For a runnable example, refer to the demo on
virtualization in the DropDownList.
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
[HttpPost]
public IActionResult ProductsVirtualization_Read([DataSourceRequest]
DataSourceRequest request)
{
return Json(GetProducts().ToDataSourceResult(request));
}
public IActionResult Products_ValueMapper(int[] values)
{
var indices = new List<int>();
if (values != null && values.Any())
{
var index = 0;
foreach (var product in GetProducts())
{
if (values.Contains(product.ProductID))
{
indices.Add(index);
}
index += 1;
}
}
return Json(indices);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
543
Telerik UI for ASP.NET Core
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().DropDownListFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.OptionLabel("Select product...")
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("ProductsVirtualization_Read", "Home");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
)
<script>
function valueMapper(options) {
$.ajax({
url: "@Url.Action("Products_ValueMapper", "Home")",
data: convertValues(options.value),
success: function (data) {
options.success(data);
}
});
}
function convertValues(value) {
var data = {};
value = $.isArray(value) ? value : [value];
for (var idx = 0; idx < value.length; idx++) {
data["values[" + idx + "]"] = value[idx];
}
return data;
}
</script>
544
Telerik UI for ASP.NET Core
3. If the AutoBind option of the DropDownList is set to false and you need the widget to
display the model value as selected, set the Text configuration option by passing the field
set as DataTextField to the Text option.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().DropDownListFor(m => m.ProductID)
.AutoBind(false)
.Text(Model.ProductName)
.DataTextField("ProductName")
// Additional configuration.
)
See Also
Virtualization by the DropDownList HtmlHelper for ASP.NET Core (Demo)
Server-Side API
545
Telerik UI for ASP.NET Core
DropDownList Accessibility
The DropDownList is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The DropDownList is compliant with the Section 508 requirements. For more information, refer to
the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The DropDownList supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the DropDownList HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the DropDownList HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
546
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the DropDownList is always available.
For a complete example, refer to the demo on keyboard navigation of the DropDownList.
See Also
Keyboard Navigation in the DropDownList HtmlHelper for ASP.NET Core (Demo)
Accessibility in the DropDownList HtmlHelper for ASP.NET Core
547
Telerik UI for ASP.NET Core
The DropDownTree represents an editor of hierarchical data, rendered in a tree-like structure, which
provides multiple selection option and custom nodes.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.DataTextField("Name")
.DataValueField("id")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_DropDownTreeData", "Home")
)
)
)
public static IList<HierarchicalViewModel> GetHierarchicalData()
{
var result = new List<HierarchicalViewModel>()
{
new HierarchicalViewModel() { ID = 1, ParentID = null, HasChildren = true, Name
= "Parent item" },
new HierarchicalViewModel() { ID = 2, ParentID = 1, HasChildren = true, Name =
"Parent item" },
new HierarchicalViewModel() { ID = 3, ParentID = 1, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 4, ParentID = 2, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 5, ParentID = 2, HasChildren = false, Name =
"Item" }
};
return result;
}
public IActionResult Read_DropDownTreeData(int? id)
{
var result = GetHierarchicalData()
.Where(x => id.HasValue ? x.ParentID == id : x.ParentID == null)
.Select(item => new {
id = item.ID,
Name = item.Name,
hasChildren = item.HasChildren
});
548
Telerik UI for ASP.NET Core
return Json(result);
}
Basic Configuration
The following example demonstrates the basic configuration of the DropDownTree HtmlHelper.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.Checkboxes(true)
.Filter(FilterType.Contains)
.DataTextField("Name")
.DataTextField("ID")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Employees", "Home")
)
)
)
Events
The following example demonstrates the available DropDownTree events and how an event handler
could be implemented for each of them.
For an example on basic DropDownTree events, refer to the demo on using the events of the
DropDownTree.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Employees", "Home")
)
)
.Events(events => events
.DataBound("onDataBound")
.Change("onChange")
.Select("onSelect")
.Close("onClose")
549
Telerik UI for ASP.NET Core
.Open("onOpen")
.Filtering("onFiltering")
)
)
<script type="text/javascript">
function onDataBound(e) {
console.log('DropDownTree instance:', e.sender);
}
function onChange(e) {
console.log('Selected node changed to:', e.sender.select());
}
function onSelect(e) {
console.log('Selected node:', e.node);
}
function onClose(e) {
console.log('DropDownTree instance:', e.sender);
}
function onOpen(e) {
console.log('DropDownTree instance:', e.sender);
}
function onFiltering(e) {
console.log('Folter:', e.filter);
}
</script>
// Place the following after your Telerik UI DropDownTree for ASP.NET Core
declaration.
<script>
$(document).ready(function() {
// The Name() of the DropDownTree is used to get its client-side instance.
var dropdowntree = $("#dropdowntree").data("kendoDropDownTree");
});
</script>
See Also
Basic Usage of the TreeView HtmlHelper for ASP.NET Core (Demo)
Using the API of the TreeView HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
550
Telerik UI for ASP.NET Core
Data Binding
The DropDownTree HTML helper provides support for declaratively defining its items and for local
(on the server) and remote (using a DataSource configuration object) binding.
The following example demonstrates how to configure a DropDownTree with three levels of
hierarchy.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.Items(dropdowntree =>
{
dropdowntree.Add().Text("My Documents")
.Expanded(true)
.Items(root =>
{
root.Add().Text("Kendo UI Project")
.Expanded(true)
.Items(project =>
{
project.Add().Text("about.html");
project.Add().Text("index.html");
project.Add().Text("logo.png");
});
root.Add().Text("New Web Site");
root.Add().Text("Reports");
});
})
)
DropDownTree Binding
The DropDownTree supports the following data-binding approaches:
Server binding
Ajax binding
See Also
Local Data Binding by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Ajax Data Binding by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
551
Telerik UI for ASP.NET Core
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.DataTextField("Name")
.DataValueField("id")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_DropDownTreeData", "Home")
)
)
)
public static IList<HierarchicalViewModel> GetHierarchicalData()
{
var result = new List<HierarchicalViewModel>()
{
new HierarchicalViewModel() { ID = 1, ParentID = null, HasChildren = true, Name
= "Parent item" },
new HierarchicalViewModel() { ID = 2, ParentID = 1, HasChildren = true, Name =
"Parent item" },
new HierarchicalViewModel() { ID = 3, ParentID = 1, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 4, ParentID = 2, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 5, ParentID = 2, HasChildren = false, Name =
"Item" }
};
return result;
}
public IActionResult Read_DropDownTreeData(int? id)
{
var result = GetHierarchicalData()
.Where(x => id.HasValue ? x.ParentID == id : x.ParentID == null)
.Select(item => new {
id = item.ID,
Name = item.Name,
hasChildren = item.HasChildren
});
return Json(result);
}
See Also
Local Data Binding by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
552
Telerik UI for ASP.NET Core
Server Binding
Local data is the data that is available on the client when the DropDownTree is initialized.
You can bind the DropDownTree locally on the server by passing the appropriate collection to the
HTML helper BindTo() method.
public IActionResult Index()
{
ViewBag.dropdowntreeData = GetData();
return View();
}
private IEnumerable<DropDownTreeItemModel> GetData()
{
List<DropDownTreeItemModel> data = new List<DropDownTreeItemModel>
{
new DropDownTreeItemModel
{
Text = "Furniture",
Items = new List<DropDownTreeItemModel>
{
new DropDownTreeItemModel()
{
Text = "Tables & Chairs"
},
new DropDownTreeItemModel
{
Text = "Sofas"
},
new DropDownTreeItemModel
{
Text = "Occasional Furniture"
}
}
},
new DropDownTreeItemModel
{
Text = "Decor",
Items = new List<DropDownTreeItemModel>
{
new DropDownTreeItemModel()
{
Text = "Bed Linen"
},
new DropDownTreeItemModel
{
Text = "Curtains & Blinds"
},
new DropDownTreeItemModel
{
Text = "Carpets"
}
}
}
};
553
Telerik UI for ASP.NET Core
return data;
}
2. Add the DropDownTree to the view and bind it to the data that is saved in the ViewData.
@using Kendo.Mvc.UI.Fluent
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.BindTo((IEnumerable<DropDownTreeItemModel>)ViewBag.dropdowntreeData)
)
See Also
Ajax Data Binding by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
554
Telerik UI for ASP.NET Core
Checkboxes
The checkboxes functionality in the DropDownTree provides various configuration options.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.DataTextField("Name")
.Checkboxes(true)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_DropDownTreeData", "Home")
)
)
)
See Also
Checkboxes in the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Server-Side API
555
Telerik UI for ASP.NET Core
Filtering
The built-in filtering functionality enables the user to filter the displayed DropDownTree items by their
text value.
By default, filtering is disabled and can be performed over string values using the field set as
DataTextField.
StartsWith
EndsWith
Contains
The following example demonstrates how to set the filter of the DropDownTree.
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.DataTextField("Name")
.Filter(FilterType.Contains)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_DropDownTreeData", "Home")
)
)
)
See Also
Ajax Data Binding by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Server-Side API
556
Telerik UI for ASP.NET Core
Items
When you bind the DropDownTree through the DataSource() configuration option, each item can
acquire specific properties.
The following JSON example demonstrates how to pass item properties to the DropDownTree. You
can configure the text, value, imageUrl, spriteCssClass, and url fields through the
DataTextField, DataValueField, DataImageUrlField, DataSpriteCssClassField, and
DataUrlFieldoptions respectively.
{
"text":"Item text",
"value":"1",
// If specified, renders the item as a link (<a href=""></a>)
"url":"/",
// Renders a <img class="k-image" src="/images/icon.png" />
"imageUrl":"/images/icon.png",
// Renders a <span class="k-sprite icon save" />
"spriteCssClass":"icon save",
// Specifies whether the text of the node in the treeview embedded in the
DropDownTree should be encoded or not.
// Useful when rendering node-specific HTML.
"encoded":false,
// Specifies whether the item is initially expanded.
// Applicable when the item has child nodes.
"expanded":true,
// Specifies whether the item checkbox is initially checked.
// Applicable for items with checkboxes using the default checkbox template.
"checked":true,
// Specifies whether the item is initially selected.
"selected":true,
// Indicates the sub-items of the item.
"items":[{
"text":"Subitem text"
}]
}
See Also
Server-Side API
557
Telerik UI for ASP.NET Core
Templates
The DropDownTree provides full control over the way a node, a selected value, a pop-up header, or
footer is rendered through the Kendo UI for jQuery templates.
For more information on the capabilities and syntax of the templates, refer to this documentation
article. For a runnable example, refer to the dem on using templates in the DropDownTree.
Basic Usage
The following example demonstrates how to customize the DropDownTree by declaring an inline
string.
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.Template("<span><h3>#: data.text #</h3></span>")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
The following example demonstrates how to customize the DropDownTree by referencing a script
tag by its id.
<!-- Template -->
<script id="dropdowntree-template" type="text/kendo-ui-template">
#: item.text #
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.TemplateId("dropdowntree-template")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
Item Template
The item template manages the way the nodes in the DropDownTree are rendered.
The following example demonstrates how to define an item template and how to evaluate it against
the dataItem.
<!-- Template -->
558
Telerik UI for ASP.NET Core
<script id="dropdowntree-template" type="text/kendo-ui-template">
#: item.text #
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.TemplateId("dropdowntree-template")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
Value Template
The value template manages the way the selected items in the input area of the DropDownTree are
rendered.
<!-- Template -->
<script id="dropdowntree-value-template" type="text/kendo-ui-template">
<span class="k-sprite #: spriteCssClass #"></span>
<span> #: data.text # </span>
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.ValueTemplateId("dropdowntree-value-template")
.DataSpriteCssClassField("spriteCssClass")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
Header Template
The header template manages the way the pop-up header of a DropDownTree is rendered.
<!-- Template -->
<script id="dropdowntree-header-template" type="text/kendo-ui-template">
<strong>Header</strong>
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.HeaderTemplateId("dropdowntree-header-template")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
559
Telerik UI for ASP.NET Core
Footer Template
The footer template manages the way the pop-up footer of a DropDownList is rendered. The footer is
re-rendered on every change of the Data Source. The context of the template is the widget itself.
<!-- Template -->
<script id="dropdowntree-footer-template" type="text/x-kendo-template">
Total <strong>#: instance.dataSource.total() #</strong> items found
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.FooterTemplateId("dropdowntree-footer-template")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
No-Data Templates
The DropDownList displays noDataTemplate in the popup when the data source is empty.
<!-- Template -->
<script id="dropdowntree-nodata-template" type="text/x-kendo-template">
<strong>No Data!</strong>
</script>
<!-- DropDownTree initialization -->
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.Filter(FilterType.Contains)
.NoDataTemplateId("dropdowntree-nodata-template")
.DataSource(source =>
{
source.Read(read => read.Action("Read_TemplateData", "DropDownTree"));
})
)
See Also
Templates in the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Server-Side API
560
Telerik UI for ASP.NET Core
DropDownTree Accessibility
The DropDownTree is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The DropDownTree is compliant with the Section 508 requirements. For more information, refer to
the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The DropDownTree supports the standards for providing accessible web content which are set by
the Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the DropDownTree HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
561
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the DropDownTree is always available.
For a complete example, refer to the demo on keyboard navigation of the DropDownTree.
See Also
Keyboard Navigation in the DropDownTree HtmlHelper for ASP.NET Core (Demo)
Accessibility in the DropDownTree HtmlHelper for ASP.NET Core
562
Telerik UI for ASP.NET Core
The Editor allows you to create rich textual content through a What-You-See-Is-What-You-Get
(WYSIWYG) interface and generate widget value as an XHTML markup.
@(Html.Kendo().Editor()
.Name("editor")
.Value(@<text>
<p>
Kendo UI Editor allows your users to edit HTML in a familiar, user-friendly
way.
</p>
</text>)
)
Basic Configuration
The following example demonstrates the basic configuration of the Editor HtmlHelper.
@(Html.Kendo().Editor()
.Name("editor")
.Encoded(true)
.HtmlAttributes(new { style = "width: 100%;height:440px" })
.Value(@<text>
<p>
Kendo UI Editor allows your users to edit HTML in a familiar, user-friendly
way.
</p>
</text>)
)
<script type="text/javascript">
$(function() {
// The Name() of the Editor is used to get its client-side instance.
var editor = $("#editor").data("kendoEditor");
});
</script>
563
Telerik UI for ASP.NET Core
Modes of operation
Tools
Pasting content
Serializing and deserializing content
Image browser
Immutable elements
CRUD operations
Styling the content
Accessibility
Events
The following example demonstrates Editor HTML helper events, which could be handled on the
client-side. For a complete example on basic Editor events, refer to the demo on using the events of
the Editor.
@(Html.Kendo().Editor()
.Name("editor")
.Events(e => e
.Change("onChange")
.Execute("onExecute")
.Keydown("onKeydown")
.Keyup("onKeyup")
.Paste("onPaste")
.PdfExport("onPdfExport")
.Select("onSelect")
)
)
<script>
function onChange(e) {
kendoConsole.log("value change");
}
function onExecute(e) {
kendoConsole.log("command :: " + e.name);
}
function onKeydown(e) {
kendoConsole.log("key down");
}
function onKeyup(e) {
kendoConsole.log("key up");
}
function onPaste(e) {
kendoConsole.log("paste :: " + kendo.htmlEncode(e.html));
}
function onPdfExport(e) {
kendoConsole.log("PDF export");
}
function onSelect(e) {
kendoConsole.log("selection change");
}
</script>
564
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Editor HtmlHelper for ASP.NET Core (Demo)
Using the API of the Editor HtmlHelper for ASP.NET Core (Demo)
Server-Side API
565
Telerik UI for ASP.NET Core
Modes of Operation
Depending on the element from which the Editor is initiated, it provides two types of operation
modes—the classicand the inlinemode.
Classic Mode
If you use the default <textarea> element for initializing the Editor, the Editor assumes its classic
mode. The textarea is not visible and is used to hold the value of the widget. You can type in the
contenteditable iframe that is created.
The classic Editor posts its value automatically because it is based on a form element. The tools of
the Editor are always visible. Its content does not reside on the main web page and the styling of the
page does not influence the editable content. To apply custom styles to the editable content, inject
them through the configuration of the Editor. For more information, refer to the demo on the classic
Editor mode.
@(Html.Kendo().Editor()
.Name("editor")
.HtmlAttributes(new { style = "width: 100%;height:440px" })
)
Inline Mode
If you use the Tag() method of the Editor HTML helper with a "div" parameter, the Editor assumes
its inline mode. The <div> element is content-editable and is used by the widget to return its value.
For a runnable example, refer to the demo on inline editing by the Editor.
@(Html.Kendo().Editor()
.Name("editor")
.Tag("div")
.HtmlAttributes(new { style = "width: 100%;height:440px" })
)
With the previous configuration, the tools of the Editor are only visible when the widget is focused.
Its content resides on the main web page and the styling of the page influences the editable content.
While it is possible to initialize an inline Editor from a non- div element, such as p or h1, it is strongly
recommended that you use the <div> one. Do not use <table> elements for creating inline Editors
because of Internet Explorer browser limitations.
Editors that are instantiated from a contentEditable element will not post their value to the server
when the value was submitted within a form. For more information, refer to the demo on the inline
Editor mode.
Because of the limited iframe support by the iOS Safari browser, it is recommended to use the
566
Telerik UI for ASP.NET Core
See Also
Inline Mode by the Editor HtmlHelper for ASP.NET Core (Demo)
Server-Side API
567
Telerik UI for ASP.NET Core
Tools
The Editor provides a predefined collection of tools that are used to interact with the control.
You can enable any of these tools by using the Tools() HtmlHelper method and configure it with
the specific tool method. Custom tools and tools that require configuration are defined using inner
methods for the tool.
Default Tools
The default tools in the Editor are included in the toolbar of the Editor upon setting the respective
tool method. For a runnable example, refer to the demo on the built-in tools in the Editor.
The following example demonstrates the default tool methods of the Editor.
@(Html.Kendo().Editor()
.Name("editor")
.Tools(tools => tools
.Clear()
.Bold()
.Italic()
.Underline()
.Strikethrough()
.JustifyLeft()
.JustifyCenter()
.JustifyRight()
.JustifyFull()
.InsertUnorderedList()
.InsertOrderedList()
.Outdent()
.Indent()
.CreateLink()
.Unlink()
.InsertImage()
.InsertFile()
.SubScript()
.SuperScript()
.TableEditing()
.ViewHtml()
.Formatting()
.CleanFormatting()
.FontName()
.FontSize()
.ForeColor()
.BackColor()
.Pdf()
.Print()
.Snippets(snippets => snippets
.Add("Signature", "<p>Regards,<br /> John Doe,<br /><a
href='mailto:[email protected]'>[email protected]</a></p>")
.Add("Kendo online demos", " <a href='http://demos.telerik.com/kendo-ui'>Kendo
online demos</a> ")
)
)
)
568
Telerik UI for ASP.NET Core
Custom Tools
To define the custom tools of the Editor, use the CustomButton() and CustomTemplate()
methods. You can use CustomButton() for scenarios where only a single action has to be executed
upon a button click. The custom template allows you to define a more complicated tool and also
embed other widgets within the Editor toolbar. You can use CustomTemplate() for creating a
DropDownList which changes the background color for the editable area of the Editor.
The following example demonstrates these scenarios. Note the Name() method that is used for the
CustomButton() configuration. The passed string value will be later used to populate the class for
the <span> element for whose tool icon the :before pseudo element is used. In this case, the final
result for that class will be k-i-custom. As the k-i-custom class is used by one of the Kendo UI
for jQuery icons, the respective icon will be displayed for the tool button. Note that the undo and
redo tool names are reserved (forbidden). For a runnable example, refer to the demo on custom tools
in the Editor.
@(Html.Kendo().Editor()
.Name("editor")
.Tools(t => t
.CustomTemplate(x => x
.Template("<label for='templateTool'
style='vertical-align:middle;'>Background:</label>" +
"<select id='templateTool'>" +
"<option value=''>none</option>" +
"<option value='\\#ff9'>yellow</option>" +
"<option value='\\#dfd'>green</option>"+
"</select>")
)
.CustomButton(x => x
.Name("custom")
.Tooltip("Insert a horizontal rule")
.Exec("onCustomButtonExec")
)
)
)
<script>
function onCustomButtonExec(e) {
var editor = $(this).data("kendoEditor");
editor.exec("inserthtml", { value: "<hr />" });
}
$(document).ready(function () {
$("#templateTool").kendoDropDownList({
change: function (e) {
var editor = $("#editor").data("kendoEditor")
editor.body.style.backgroundColor = e.sender.value();
}
});
});
</script>
See Also
569
Telerik UI for ASP.NET Core
570
Telerik UI for ASP.NET Core
Pasting Content
Pasting content from HTML and Microsoft (MS) Word documents to the Editor is essential for the
end-user experience.
Basic Concepts
The Editor facilitates the DOM clipboard events. Any content that is pasted is first processed by the
browser. After the browser processes the content, the Editor applies the PasteCleanup()options
which help control the content that will be pasted.
None()—Disables all options which means that none of the pasteCleanup options will be
executed. Disabled by default.
All()—Strips all HTML tags and leaves only plain text. Disabled by default.
KeepNewLines()—Removes all HTML elements, such as the all option, but preserves new
lines. Disabled by default.
Span()—Removes the span elements from the copied content. Disabled by default.
Css()—Removes the style and class attributes out of all HTML elements from the copied
content. Disabled by default.
MsTags()—Strips the MS Word specific tags when pasting content and cleans up extra
metadata. Enabled by default.
MsAllFormatting()—Strips the MS Word specific tags and removes the font-name and
font-size decoration derived from MS Word. Disabled by default.
MsConvertLists()—Converts MS Word lists to HTML lists. Enabled by default.
Custom()—Uses a callback function to create a custom pasteCleanup option.
The following example demonstrates how to copy the HTML content above the Editor and paste it in
the content area. Because of the enabled Span() option, the span tags are removed.
<p>
Copy this is a paragraph that has some
<span style="font-family:Impact, Charcoal, sans-serif;">
inline
</span>
<span style="font-family:Impact, Charcoal,
sans-serif;color:#ffffff;background-color:#3366ff;">
styles
</span>
and paste it in the Editor.
</p>
<hr />
@(Html.Kendo().Editor()
.Name("editor")
.PasteCleanup(p => p
571
Telerik UI for ASP.NET Core
.Span()
)
)
The MsTags() and the MsAllFormatting() options strip MS Word specific tags. MS Word specific
tags are some valid XML nodes that MS Word uses to render text formatting and decoration. Some
browsers do not translate these tags and they are just inserted into the content area on pasting. This
makes the HTML invalid. Additionally, the MsAllFormatting() option removes the font-name and
font-size stylization.
The MsConvertLists() is an option that enables the end user to successfully paste MS Word lists
and convert them to proper HTML lists on pasting. Only few browsers support this feature and lists
are pasted as plain <p> tags.
The following example demonstrates how to adjust the MS Word specific options. To see the result,
paste some content from MS Word.
@(Html.Kendo().Editor()
.Name("editor")
.PasteCleanup(p => p
.MsTags(true)
.MsAllFormatting(false)
.MsConvertLists(true)
)
)
The following example demonstrates a simple logic to strip the <strong> tags from the pasted
HTML content.
<p>some text with <strong>bold text</strong> inside.</p>
<hr />
@(Html.Kendo().Editor()
.Name("editor")
.PasteCleanup(p => p
.Custom("customPasteCleanUp")
572
Telerik UI for ASP.NET Core
)
)
<script>
function customPasteCleanUp(html) {
return html.replace(/<\/?strong[^>]*>/, "");
}
</script>
See Also
Server-Side API
573
Telerik UI for ASP.NET Core
Serializing
The Editor provides the following configuration options:
Entities()—Indicates whether the characters outside the ASCII range will be encoded as
HTML entities. By default, they are encoded (true).
Scripts()—Indicates whether inline scripts will be serialized and posted to the server. By
default, scripts will be removed (false).
Semantic()—Indicates whether the font styles will be saved as semantic tags ( strong, em,
span) or as presentational tags (b, i, u, font). By default, the Editor uses semantic tags
(true).
Custom()—Allows you to define custom serialization for the editable content. The
JavaScript handler will receive the Editor content and will return its serialized version.
@(Html.Kendo().Editor()
.Name("editor")
.Serialization(s => s
.Entities(true)
.Scripts(true)
.Semantic(true)
.Custom("serializeHandler")
)
)
<script>
function serializeHandler(html) {
return html.replace(/(<\/?)b(\s?)/, "$1strong$2");
}
</script>
Deserializing
Deserialization is the process of parsing the HTML string input from the value() method or from
the viewHtml dialog into editable content. The deserialization configuration method allows you
to use a custom JavaScript handler, as demonstrated in the following example.
@(Html.Kendo().Editor()
.Name("editor")
.Deserialization(ds => ds
.Custom("deserializeHandler")
)
}
<script>
function deserializeHandler(html) {
574
Telerik UI for ASP.NET Core
return html.replace(/(<\/?)b(\s?)/, "$1strong$2")
}
</script>
See Also
Server-Side API
575
Telerik UI for ASP.NET Core
Image Browser
By default, the Insert Image tool opens a simple dialog that allows you to type in or paste the URL of
an image and, optionally, specify a tooltip.
The Editor also supports another way of picking an image by browsing a list of predefined files and
directories. Uploading new images is also supported. For a runnable example, refer to the demo on
file and image browser in the Editor.
To retrieve and upload the files and directories, the image browser needs a server-side
implementation. To configure the image browser tool, use the ImageBrowser()method.
@(Html.Kendo().Editor()
.Name("editor")
.ImageBrowser(imageBrowser => imageBrowser
.Image("~/Content/UserFiles/Images/{0}")
.Read("Read", "ImageBrowser")
.Create("Create", "ImageBrowser")
.Destroy("Destroy", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
.Thumbnail("Thumbnail", "ImageBrowser")
)
)
The following list provides information about the default requests and responses for the Create(),
Read(), Destroy(), and Upload() operations.
Create()—Makes a POST request for the creation of a directory with the following
parameters and does not expect a response.
{ "name": "New folder name", "type": "d", "path": "foo/" }
Read()—Makes a POST request that contains the path parameter which specifies the path
that is browsed and expects a file listing in the following format.
[
{ "name": "foo.png", "type": "f", "size": 73289 },
{ "name": "bar.jpg", "type": "f", "size": 15289 },
...
]
name from the previous example is the name of the file or directory, type is either an f for a
file or a d for a directory, and size is the file size (optional).
576
Telerik UI for ASP.NET Core
{ "name": "foo.png", "type": "f", "size": 12345 }
Image()—Used by the Editor to generate the src attribute of the original image when the
image is inserted. It results in a GET request generated by the browser for each inserted
image. The URL can point to a file system or to a service and is parameterized—the {0}
placeholder denotes the path and fileName as received from the Read() service.
You can update all of these requests and responses through the ImageBrowser()configuration.
Each of them exposes more options that you can tweak.
See Also
File and Image Browser by the Editor HtmlHelper for ASP.NET Core (Demo)
Server-Side API
577
Telerik UI for ASP.NET Core
Immutable Elements
The immutable feature enables you to add HTML elements that cannot be edited by the user.
For a runnable example, refer to the demo on immutable elements in the Editor.
@(Html.Kendo().Editor()
.Name("editor")
.Immutables(true)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
mutable</div>")
)
Serializing Immutables
The Serialization()method enables you to control the HTML representation of the immutable
elements in the viewHtml dialog.
String—A plain string. Implements an opening and a closing tag of the display
representation in the ViewHtml dialog.
@(Html.Kendo().Editor()
.Name("editor")
.Immutables(i => i
.Serialization("<div></div>")
)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
mutable</div>")
)
(Html.Kendo().Editor()
.Name("editor")
.Immutables(i => i
.Serialization("<#= data.nodeName # data=\"immutable-element\"></#=
data.nodeName #>")
)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
578
Telerik UI for ASP.NET Core
mutable</div>")
)
Function—A callback function. Exposes the immutable DOM element in the overload and is
expected to return a string.
(Html.Kendo().Editor()
.Name("editor")
.Immutables(i => i
.SerializationHandler("immutablesSerializationHandler")
)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
mutable</div>")
)
<script>
function immutablesSerializationHandler(node) {
var tagName = node.tagName;
return "<" + tagName + ">" + "</" + tagName + ">";
}
</script>
Deserializing Immutables
The Deserialization()method does the opposite of the Serialization() one.
Deserialization() takes the HTML representation from the ViewHtml dialog and alters the
immutable DOM element based on the implemented logic in the callback function.
The following example demonstrates how to use the Serialization() and Deserialization()
options to expose the CSS text-align property in the ViewHtml dialog so that the user is able to
change it from the HTML code.
@(Html.Kendo().Editor()
.Name("editor")
.Immutables(i => i
.Serialization("<immutable style='# if(data.style.textAlign){#text-align:
#=data.style.textAlign##}#'></immutable>")
.Deserialization("immutablesDeserializationHandler")
)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
mutable</div>")
)
<script>
function immutablesDeserializationHandler(node, immutable) {
immutable.style.textAlign = node.style.textAlign;
}
</script>
579
Telerik UI for ASP.NET Core
To decorate all contenteditable="false" elements and improve user experience (UX), use a CSS
rule.
If you use the classic mode, add the CSS rule to an external CSS file that is adjoined to the
stylesheet collectionof the Editor.
If you use the inline mode, place the CSS rule on the page as demonstrated in the following
example.
<style>
.k-editor [contenteditable='false']{
opacity: 0.5;
}
</style>
@(Html.Kendo().Editor()
.Name("editor")
.Tag("div")
.Immutables(true)
.Value("<div contenteditable='false'>this is immutable</div><div>this is
mutable</div>")
)
See Also
Immutable Elements by the Editor HtmlHelper for ASP.NET Core (Demo)
Server-Side API
580
Telerik UI for ASP.NET Core
CRUD Operations
The following example demonstrates how to save, read, update and delete a text data content in a
local database using the Editor component.
For a runnable project, refer to this GitHub repository. The previously linked example assumes you
have a Telerik UI for ASP.NET Core and Entity framework installed and a local database set up.
This code has no applied XSS attack prevention and it is the responsibility of the developer to
manage these security risks. For more information, refer to the article on preventing cross-site
scripting.
The following example demonstrates how to define the database model.
public class EditorDataContext : DbContext
{
public EditorDataContext(DbContextOptions<EditorDataContext> options)
: base(options)
{ }
public DbSet<EditorData> EditorData { get; set; }
}
public class EditorData
{
[Key]
public int ContentId { get; set; }
public string EditorContent { get; set; }
}
The following example demonstrates how to define the Index page of your application.
<h1>Index</h1>
<p>
<a asp-action="Create" class="k-button">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.EditorContent)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EditorContent)
</td>
581
Telerik UI for ASP.NET Core
<td>
<a asp-action="Edit" asp-route-id="@item.ContentId" class="k-button
k-primary">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ContentId"
class="k-button">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ContentId"
class="k-button">Delete</a>
</td>
</tr>
}
</tbody>
</table>
public async Task<IActionResult> Index()
{
return View(await _context.EditorData.ToListAsync());
}
The following example demonstrates how to add the content of the Editor to the database.
<h1>Create</h1>
<h4>EditorData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" id="EditorDataForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EditorContent"></label>
@Html.Kendo().EditorFor(m => m.EditorContent)
<span asp-validation-for="EditorContent" class="text-danger k-invalid-msg"
data-for="EditorContent"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="k-button k-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="k-button">Back to List</a>
</div>
<h1>Create</h1>
<h4>EditorData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" id="EditorDataForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EditorContent"></label>
582
Telerik UI for ASP.NET Core
<kendo-editor for="EditorContent">
</kendo-editor>
<span asp-validation-for="EditorContent" class="text-danger k-invalid-msg"
data-for="EditorContent"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="k-button k-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="k-button">Back to List</a>
</div>
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ContentId,EditorContent")] EditorData
editorData)
{
if (ModelState.IsValid)
{
_context.Add(editorData);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(editorData);
}
The following example demonstrates how to read the stored data in the database.
<h1>Details</h1>
<div>
<h4>EditorData</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.EditorContent)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.EditorContent)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.ContentId" class="k-button
k-primary">Edit</a> |
<a asp-action="Index" class="k-button">Back to List</a>
</div>
583
Telerik UI for ASP.NET Core
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var editorData = await _context.EditorData
.FirstOrDefaultAsync(m => m.ContentId == id);
if (editorData == null)
{
return NotFound();
}
return View(editorData);
}
<h1>Edit</h1>
<h4>EditorData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit" id="EditorDataForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ContentId" />
<div class="form-group">
<label asp-for="EditorContent"></label>
@Html.Kendo().EditorFor(m => m.EditorContent)
<span asp-validation-for="EditorContent" class="text-danger k-invalid-msg"
data-for="EditorContent"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="k-button k-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="k-button">Back to List</a>
</div>
<h1>Edit</h1>
<h4>EditorData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit" id="EditorDataForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ContentId" />
<div class="form-group">
<label asp-for="EditorContent"></label>
584
Telerik UI for ASP.NET Core
<kendo-editor for="EditorContent">
</kendo-editor>
<span asp-validation-for="EditorContent" class="text-danger k-invalid-msg"
data-for="EditorContent"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="k-button k-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="k-button">Back to List</a>
</div>
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var editorData = await _context.EditorData.FindAsync(id);
if (editorData == null)
{
return NotFound();
}
return View(editorData);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ContentId,EditorContent")]
EditorData editorData)
{
if (id != editorData.ContentId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(editorData);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EditorDataExists(editorData.ContentId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
585
Telerik UI for ASP.NET Core
}
return View(editorData);
}
The following example demonstrates how to delete records from the database.
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var editorData = await _context.EditorData
.FirstOrDefaultAsync(m => m.ContentId == id);
if (editorData == null)
{
return NotFound();
}
return View(editorData);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var editorData = await _context.EditorData.FindAsync(id);
_context.EditorData.Remove(editorData);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
See Also
Server-Side API
586
Telerik UI for ASP.NET Core
Styling of Content
The Editor HtmlHelper provides default and custom options for styling its content.
Default Options
When the classic modeis enabled, the Editor uses an iframe and applies some default CSS styles to
its content. This behavior overrides the default browser styling.
The following example targets mainly headings, paragraphs, links, lists, and tables. All tables inside
the Editor obtain a k-table class which is not included in the value of the widget.
html,
body {
padding: 0;
margin: 0;
height: 100%;
min-height: 100%;
}
body {
font-size: 12px;
font-family: Verdana,Geneva,sans-serif;
margin-top: -1px;
padding: 1px .2em 0;
word-wrap: break-word;
}
h1 {
font-size: 2em;
margin: .67em 0;
}
h2 {
font-size: 1.5em;
}
h3 {
font-size: 1.16em;
}
h4 {
font-size: 1em;
}
h5 {
font-size: .83em;
}
h6 {
font-size: .7em;
}
587
Telerik UI for ASP.NET Core
p {
margin: 0 0 1em;
}
ul, ol {
padding-left: 2.5em;
}
a {
color: #00a;
}
code {
font-size: 1.23em;
}
.k-table {
table-layout: fixed;
width: 100%;
border-spacing: 0;
margin: 0 0 1em;
}
.k-table td {
min-width: 1px;
padding: .2em .3em;
}
.k-table,
.k-table td {
outline: 0;
border: 1px dotted #ccc;
}
.k-table p {
margin: 0;
padding: 0;
}
To avoid the default content styles from the previous example, remove or override them after the
Editor is initialized by executing the following code.
@(Html.Kendo().Editor()
.Name("editor")
.Value(@<text>
<p>
The Editor allows your users to edit HTML in a familiar, user-friendly way.
</p>
</text>)
)
<script type="text/javascript">
$(document).ready(function() {
var editor = $("#editor").data("kendoEditor");
var styleTag = editor.body.parentNode.getElementsByTagName("style")[0];
styleTag.parentNode.removeChild(styleTag);
});
</script>
588
Telerik UI for ASP.NET Core
Custom Styles
You can also use custom styles with higher specificityselectors and inject those custom styles in an
Editor stylesheet. In such cases, you do not have to customize the Formatting tool of the Editor.
See Also
Styles in the Editor HtmlHelper for ASP.NET Core (Demo)
Server-Side API
589
Telerik UI for ASP.NET Core
Editor Accessibility
The Editor is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Editor is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Editor supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Editor HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Editor HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
590
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Editor is always available.
For a complete example, refer to the demo on keyboard navigation of the Editor.
See Also
Keyboard Navigation in the Editor HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Editor HtmlHelper for ASP.NET Core
591
Telerik UI for ASP.NET Core
The FlatColorPicker is the HSV color selector which is used by default in the
kendo.ui.ColorPicker popup when no palette is set.
@(Html.Kendo().FlatColorPicker()
.Name("flatcolorpicker") // The name of the FlatColorPicker is mandatory. It
specifies the "id" attribute of the widget.
.Value("#ff0000") // Set the value of the FlatColorPicker.
)
Events
You can subscribe to all FlatColorPicker events.
@(Html.Kendo().FlatColorPicker()
.Name("flatcolorpicker")
.Events(e => e
.Change("flatcolorpicker_change")
)
)
<script>
function flatcolorpicker_change(e) {
//Handle the change event.
}
</script>
@(Html.Kendo().FlatColorPicker()
.Name("flatcolorpicker")
592
Telerik UI for ASP.NET Core
.Events(e => e
.Change(@<text>
function(e) {
// Handle the change event inline.
}
</text>)
)
)
// Place the following after your Telerik UI FlatColorPicker for ASP.NET Core
declaration.
<script>
$(function() {
// The Name() of the FlatColorPicker is used to get its client-side instance.
var flatcolorpicker = $("#flatcolorpicker").data("kendoFlatColorPicker");
});
</script>
See Also
Basic Usage of the FlatColorPicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
593
Telerik UI for ASP.NET Core
The ListBox provides suggestions depending on the typed text and allows multiple value entries. It
displays a list of data that is contained in a box and allows single or multiple selection, reordering of
selected items, and deleting items and features keyboard navigation as well as the dragging and
dropping of items. You can also connect the ListBox with another list-box and customize the widget
with the use of templates, toolbar positioning, placeholder and hint, and localization of its command
buttons messages.
@(Html.Kendo().ListBox()
.Name("optional")
.Toolbar(toolbar =>
{
toolbar.Position(Kendo.Mvc.UI.Fluent.ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.MoveUp()
.MoveDown()
);
})
.BindTo(ViewBag.Attendees)
)
public ActionResult Index()
{
ViewBag.Attendees = new List<string>
{
"Steven White",
"Nancy King",
"Nancy Davolio",
"Robert Davolio",
"Michael Leverling",
"Andrew Callahan",
"Michael Suyama"
};
return View();
}
594
Telerik UI for ASP.NET Core
Events
For a complete example on basic ListBox events, refer to the demo on using the events of the ListBox.
// Place the following after your ListBox for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the ListBox is used to get its client-side instance.
var listbox = $("#listbox").getKendoListBox();
});
</script>
See Also
Basic Usage of the ListBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
595
Telerik UI for ASP.NET Core
Immediately after the ListBox loads, the DataSourcesends a query and the data is loaded to the
helper. To disable this behavior, set the AutoBind option of the ListBox to false.
@(Html.Kendo().ListBox()
.Name("optional")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox"))
)
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("selected")
.ConnectWith("selected")
.AutoBind(false) // Prevent data binding during the initialization of the
widget
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.TransferTo()
.Remove());
})
.BindTo(new List<CustomerViewModel>())
)
For more information about binding the ListBox to data, refer to the articles on:
See Also
Basic Usage of the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
596
Telerik UI for ASP.NET Core
Local Binding
The Telerik UI ListBox for ASP.NET Core enables you to bind it to local arrays of data.
When you use complex data objects, use the DataTextField and DataValueField properties to
notify the ListBox about your preferred binding behavior.
@(Html.Kendo().ListBox()
.Name("optional")
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.MoveUp()
.MoveDown()
.TransferTo()
.TransferFrom()
.TransferAllTo()
.TransferAllFrom()
.Remove()
);
})
.ConnectWith("selected")
.BindTo(ViewBag.Attendees) // Bind the ListBox to a collection
)
@(Html.Kendo().ListBox()
.Name("selected")
.BindTo(new List<string>())
.Selectable(ListBoxSelectable.Multiple)
)
using System;
using System.Collections.Generic;
using System.Linq;
using Kendo.Mvc.Examples.Models;
using Microsoft.AspNetCore.Mvc;
namespace Kendo.Mvc.Examples.Controllers
{
public partial class ListBoxController : BaseController
{
public IActionResult Index()
{
ViewBag.Attendees = new List<string>
{
"Steven White",
"Nancy King",
"Nancy Davolio",
"Robert Davolio",
"Michael Leverling",
"Andrew Callahan",
"Michael Suyama"
};
return View();
}
597
Telerik UI for ASP.NET Core
}
}
See Also
Local Data Binding of the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
598
Telerik UI for ASP.NET Core
Remote Binding
The Telerik UI ListBox for ASP.NET Core enables you to bind it to a remote data source.
When you use complex data objects, use the DataTextField and DataValueField properties to
notify the ListBox about your preferred binding behavior.
@(Html.Kendo().ListBox()
.Name("optional")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox")) // Configure the data
source for remote data binding
)
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("selected")
.ConnectWith("selected")
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.MoveUp()
.MoveDown()
.TransferTo()
.TransferFrom()
.TransferAllTo()
.TransferAllFrom()
.Remove());
})
.BindTo(new List<CustomerViewModel>())
)
@(Html.Kendo().ListBox()
.Name("selected")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("optional")
.ConnectWith("optional")
.BindTo(new List<CustomerViewModel>())
)
using System;
using System.Collections.Generic;
using System.Linq;
using Kendo.Mvc.Examples.Models;
using Microsoft.AspNetCore.Mvc;
namespace Kendo.Mvc.Examples.Controllers
{
public partial class ListBoxController : BaseController
{
private IProductService productService;
599
Telerik UI for ASP.NET Core
public ListBoxController(
IProductService service)
{
productService = service;
}
[Demo]
public IActionResult Index()
{
return View();
}
public IActionResult GetCustomers()
{
var customers = Enumerable.Empty<CustomerViewModel>();
using (var northwind = GetContext())
{
customers = northwind.Customers.Select(customer => new CustomerViewModel
{
CustomerID = customer.CustomerID,
CompanyName = customer.CompanyName,
ContactName = customer.ContactName,
ContactTitle = customer.ContactTitle,
Address = customer.Address,
City = customer.City,
Region = customer.Region,
PostalCode = customer.PostalCode,
Country = customer.Country,
Phone = customer.Phone,
Fax = customer.Fax,
Bool = customer.Bool
}).ToList();
}
return Json(customers);
}
}
}
See Also
Remote Data Binding of the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
600
Telerik UI for ASP.NET Core
Item Templates
The ListBox provides templates for its items that are passed as а function or string.
@(Html.Kendo().ListBox()
.Name("optional")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox")) // Configure the data
source for remote data binding
)
.TemplateId("customer-item-template") // Configure the item template
.Draggable(draggable => draggable.Placeholder("customPlaceholder")) // Create a
custom placeholder
.DropSources("selected")
.ConnectWith("selected")
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.MoveUp()
.MoveDown()
.TransferTo()
.TransferFrom()
.TransferAllTo()
.TransferAllFrom()
.Remove());
})
.BindTo(new List<CustomerViewModel>())
)
@(Html.Kendo().ListBox()
.Name("selected")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("optional")
.ConnectWith("optional")
.BindTo(new List<CustomerViewModel>())
)
<script id="customer-item-template" type="text/x-kendo-template">
<span class="k-state-default" style="background-image:
url(@Url.Content("~/shared/web/Customers/")#:data.CustomerID#.jpg);"></span>
<span class="k-state-default"><h3>#: data.ContactName #</h3><p>#:
data.CompanyName #</p></span>
</script>
<script>
function customPlaceholder(draggedItem) {
return draggedItem
.clone()
.addClass("custom-placeholder")
.removeClass("k-ghost");
}
601
Telerik UI for ASP.NET Core
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using Kendo.Mvc.Examples.Models;
using Microsoft.AspNetCore.Mvc;
namespace Kendo.Mvc.Examples.Controllers
{
public partial class ListBoxController : BaseController
{
private IProductService productService;
public ListBoxController(
IProductService service)
{
productService = service;
}
[Demo]
public IActionResult Index()
{
return View();
}
public IActionResult GetCustomers()
{
var customers = Enumerable.Empty<CustomerViewModel>();
using (var northwind = GetContext())
{
customers = northwind.Customers.Select(customer => new CustomerViewModel
{
CustomerID = customer.CustomerID,
CompanyName = customer.CompanyName,
ContactName = customer.ContactName,
ContactTitle = customer.ContactTitle,
Address = customer.Address,
City = customer.City,
Region = customer.Region,
PostalCode = customer.PostalCode,
Country = customer.Country,
Phone = customer.Phone,
Fax = customer.Fax,
Bool = customer.Bool
}).ToList();
}
return Json(customers);
}
}
}
See Also
Templates in the Telerik UI ListBox for ASP.NET Core (Demo)
Server-Side API
602
Telerik UI for ASP.NET Core
You can also customize the drag-and-drop appearance of the ListBox by using its
Draggable.Placeholder and Draggable.Hint options.
@(Html.Kendo().ListBox()
.Name("listbox1")
.DataValueField("ProductID")
.DataTextField("ProductName")
.Draggable(true) // Enable drag and drop
.DropSources("listbox2") // Specify the drop target
.Events(ev=>ev
.Add("function(e){setDiscontinued(e, true)}")
.Remove("function(e){setDiscontinued(e, false)}"))
.ConnectWith("listbox2")
.BindTo(new List<string>())
.Selectable(ListBoxSelectable.Single)
)
@(Html.Kendo().ListBox()
.Name("listbox2")
.Draggable(true)
.DropSources("listbox1")
.DataValueField("ProductID")
.DataTextField("ProductName")
.ConnectWith("listbox1")
.BindTo(new List<string>())
.Selectable(ListBoxSelectable.Single)
)
See Also
Dragging and Dropping by the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
603
Telerik UI for ASP.NET Core
Selection
By default, the ListBox is set into a single-selection mode.
@(Html.Kendo().ListBox()
.Name("optional")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox"))
)
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("selected")
.ConnectWith("selected")
.Selectable(ListBoxSelectable.Single) // Enable single selection
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.TransferTo()
.Remove());
})
.BindTo(new List<CustomerViewModel>())
)
@(Html.Kendo().ListBox()
.Name("selected")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("optional")
.ConnectWith("optional")
.Selectable(ListBoxSelectable.Multiple) // Enable multi selection
.BindTo(new List<CustomerViewModel>())
)
Reordering of Selections
The ListBox allows you to reorder the selected items by using any of the following approaches:
604
Telerik UI for ASP.NET Core
Currently, the ListBox does not support the drag-and-drop feature for multiple selected items.
See Also
Server-Side API
605
Telerik UI for ASP.NET Core
ListBox Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support). More information
could be found here:
Localization of messages
Right-to-left support
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core HTML Helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
RTL Support by the ListBox HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
Server-Side API
606
Telerik UI for ASP.NET Core
Localization
You can customize the Messages() for each toolbar command button of the ListBox.
These messages serve as tooltip text when the user hovers over the buttons.
@(Html.Kendo().ListBox()
.Name("optional")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox"))
)
.Messages(m=>m.Tools(tools=>
{
tools.MoveUp("Promote");
tools.MoveDown("Demote");
tools.Remove("Remove Employee");
tools.TransferTo("Transfer To");
tools.TransferAllTo("Transfer All To");
tools.TransferFrom("Transfer From");
tools.TransferAllFrom("Transfer All From");
})
)
.TemplateId("customer-item-template")
.Draggable(draggable => draggable.Placeholder("customPlaceholder"))
.DropSources("selected")
.ConnectWith("selected")
.Selectable(ListBoxSelectable.Single)
.Toolbar(toolbar =>
{
toolbar.Position(ListBoxToolbarPosition.Right);
toolbar.Tools(tools => tools
.TransferTo()
.Remove());
})
.BindTo(new List<CustomerViewModel>())
)
See Also
RTL Support by the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
607
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the ListBox.
See Also
RTL Support by the ListBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
608
Telerik UI for ASP.NET Core
ListBox Accessibility
The ListBox is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on accessibility support in Telerik UI for ASP.NET Core.
Section 508
The ListBox is compliant with the Section 508 requirements. For more information, refer to the
article on accessibility support in Telerik UI for ASP.NET Core.
WCAG 2.1
The ListBox supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on accessibility support
in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the ListBox HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the ListBox HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
609
Telerik UI for ASP.NET Core
Keyboard Navigation
By default, the keyboard navigation of the ListBox HtmlHelper is disabled.
The ListBox supports its keyboard navigation functionality through the Navigatable option. When
set to true, you can initially select an item and then move within the ListBox by using the Arrow
keys. The navigation occurs at item level regardless of what the selectable mode is. To select the
current item, press Space.
The following example demonstrates how to enable the key navigation in the ListBox.
@(Html.Kendo().ListBox()
.Name("listbox")
.ConnectWith("listbox2")
.Selectable(ListBoxSelectable.Multiple)
.DataValueField("ProductID")
.DataTextField("ProductName")
.DataSource(source => source
.Read(read => read.Action("GetProducts", "ListBox"))
)
.Navigatable(true) // Enable the keyboard navigation
)
@(Html.Kendo().ListBox()
.Name("listbox2")
.BindTo(new List<ProductViewModel>())
.DataValueField("ProductID")
.DataTextField("ProductName")
.Selectable(ListBoxSelectable.Single)
.Navigatable(true) // Enable the keyboard navigation
)
See Also
Keyboard Navigation by the ListBox HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
610
Telerik UI for ASP.NET Core
The MaskedTextBox enables a controlled text input that is based on a specific format. The helper
enables you to define its value and mask value, and set custom mask rules, prompt characters, and
culture names. Each mask can contain mask rules and mask literals. The mask literals are
automatically entered for the user and cannot be removed. You can also use the MaskedTextBox
predefined rules which specify the required or optional digit, letter, or character input.
Basic Configuration
The following example demonstrates the basic configuration for the MaskedTextBox.
@(Html.Kendo().MaskedTextBox()
.Name("maskedtextbox") // The name of the MaskedTextBox is mandatory. It
specifies the "id" attribute of the MaskedTextBox.
.Mask("(000) 000-0000") // Set the mask value of the MaskedTextBox.
.Value("(123) 345-6789") // Set the value of the MaskedTextBox.
)
Events
You can subscribe to all MaskedTextBox events. For a complete example on basic MaskedTextBox
events, refer to the demo on using the events of the MaskedTextBox.
@(Html.Kendo().MaskedTextBox()
.Name("maskedtextbox")
.Events(e => e
.Change("maskedtextbox_change")
)
)
<script>
function maskedtextbox_change() {
// Handle the change event.
}
</script>
611
Telerik UI for ASP.NET Core
// Place the following after your Telerik UI MaskedTextBox for ASP.NET Core
declaration.
<script>
$(function() {
// The Name() of the MaskedTextBox is used to get its client-side instance.
var maskedtextbox = $("#maskedtextbox").data("kendoMaskedTextBox");
});
</script>
See Also
Basic Usage of the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
612
Telerik UI for ASP.NET Core
Validation
The MaskedTextBox provides a set of predefined mask rules and enables you to modify them.
Predefined Masks
The MaskedTextBox has a list of predefined mask ruleswhich can be used to validate its user input.
@(Html.Kendo().MaskedTextBox()
.Name("maskedtextbox")
.Mask("00000-9999") // Set the zip code.
)
Custom Masks
The MaskedTextBox enables you to define custom mask rules if none of the predefined ones is
suitable. To add a custom rule, use the Rules method.
@(Html.Kendo().MaskedTextBox()
.Name("maskedtextbox")
.Rules(rules => {
rules.Add('~', "/[+-]/");
})
.Mask("~0000") // Set a mask with a custom rule.
)
See Also
Validation by the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
613
Telerik UI for ASP.NET Core
MaskedTextBox Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
To determine the currency symbol and other culture-specific properties, the MaskedTextBox uses
the kendo.culture.current culture.
The globalization functionality of the MaskedTextBox is enabled through its right-to-left support. For
a complete example, refer to the demo on globalization of the MaskedTextBox.
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core HTML Helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
RTL Support by the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Globalization by the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Globalization in Telerik UI for ASP.NET Core
Server-Side API
614
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the MaskedTextBox.
See Also
RTL Support by the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
615
Telerik UI for ASP.NET Core
MaskedTextBox Accessibility
The MaskedTextBox is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
For more information, refer to the article on accessibility in Telerik UI for ASP.NET Core.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers.
Section 508
The MaskedTextBox is compliant with the Section 508 requirements.
WCAG 2.1
The MaskedTextBox supports the standards for providing accessible web content which are set by
the Web Content Accessibility Guidelines 2.1.
See Also
Basic Usage of the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the MaskedTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
616
Telerik UI for ASP.NET Core
MultiColumnComboBox HtmlHelper
Overview
The Telerik UI MultiColumnComboBox HtmlHelper for ASP.NET Core is a server-side wrapper for the
Kendo UI MultiColumnComboBox widget.
@(Html.Kendo().MultiColumnComboBox()
.Name("multicolumncombobox")
.Placeholder("Select product")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.Filter(FilterType.StartsWith)
.DataSource(source => {
source.Read(read =>
{
read.Action("Products_Read", "MultiColumnComboBox");
})
.ServerFiltering(true);
})
)
public class MultiColumnComboBoxController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult Products_Read(string text)
{
var result = GetProducts();
if (!string.IsNullOrEmpty(text))
{
result = result.Where(p => p.ProductName.Contains(text)).ToList();
}
return Json(result);
617
Telerik UI for ASP.NET Core
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var result = Enumerable.Range(0, 50).Select(i => new ProductViewModel
{
ProductID = "" + i,
ProductName = "Product " + i
});
return result;
}
}
Basic Configuration
The following example demonstrates the basic configuration of the MultiColumnComboBox
HtmlHelper.
@(Html.Kendo().MultiColumnComboBox()
.Name("multicolumncombobox")
.Placeholder("Select product")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.HtmlAttributes(new { style = "width:100%;" })
.Filter("contains")
.AutoBind(true)
.MinLength(3)
.Height(400)
.DataSource(source => source
.Read(read => read.Action("Products_Read", "MultiColumnComboBox"))
.ServerFiltering(true)
)
)
Events
For a complete example on basic MultiColumnComboBox events, refer to the demo on using the
events of the MultiColumnComboBox.
618
Telerik UI for ASP.NET Core
// Place the following after your Telerik UI MultiColumnComboBox for ASP.NET Core
declaration.
<script>
$(document).ready(function() {
// The Name() of the MultiColumnComboBox is used to get its client-side
instance.
var mccombobox = $("#multicolumncombobox").data("kendoMultiColumnComboBox");
});
</script>
See Also
Basic Usage of the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
619
Telerik UI for ASP.NET Core
Data Binding
The MultiColumnComboBox provides a set of options for binding it to data.
Ajax binding
Server binding
Custom binding
Model binding/
See Also
Server-Side API
620
Telerik UI for ASP.NET Core
Ajax Binding
The MultiColumnComboBox provides support for remote data binding by using a DataSource
configuration object. You can configure the MultiColumnComboBox to get its data from a remote
source by making an AJAX request.
public IActionResult Index()
{
return View();
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products);
}
2. Add the MultiColumnComboBox to the view and configure its DataSource to use remote
data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBox()
.Name("multicolumncombobox")
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Placeholder("Select product...")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
621
Telerik UI for ASP.NET Core
See Also
Local Data Binding
Server-Side API
622
Telerik UI for ASP.NET Core
Server Binding
Local data is the data that is available on the client when the MultiColumnComboBox is initialized.
You can bind the MultiColumnComboBox locally on the server by passing the appropriate collection
to the HTML helper BindTo() method.
public IActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the MultiColumnComboBox to the view and bind it to the data that is saved in the
ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBoxFor(m => m.ProductID)
.DataValueField("ProductID")
.DataTextField("ProductName")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
See Also
Ajax Data Binding by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
623
Telerik UI for ASP.NET Core
Server-Side API
624
Telerik UI for ASP.NET Core
Custom Binding
You can use a custom DataSource and bind the MultiColumnComboBox to a ToDataSourceResult
instance.
public ActionResult Index()
{
return View();
}
3. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts([DataSourceRequest] DataSourceRequest request)
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products.ToDataSourceResult(request));
}
@(Html.Kendo().MultiColumnComboBox()
.Name("productMultiColumnComboBox")
.DataTextField("ProductName") // Specify which property of the Product to
be used by the MultiColumnComboBox as a text.
.DataValueField("ProductID") // Specify which property of the Product to
be used by the MultiColumnComboBox as a value.
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.Type("aspnetmvc-ajax") // Set this type if you want to use
DataSourceRequest and ToDataSourceResult instances.
.Transport(transport =>
{
transport.Read("GetProducts", "Home");
})
.Schema(schema =>
625
Telerik UI for ASP.NET Core
{
schema.Data("Data") // Define the
[data](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configur
ation-schema.data) option.
.Total("Total"); // Define the
[total](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configu
ration-schema.total) option.
});
})
)
@(Html.Kendo().MultiColumnComboBox()
.Name("productMultiColumnComboBox") // The name of the MultiColumnComboBox is
mandatory. It specifies the "id" attribute of the MultiColumnComboBox.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the MultiColumnComboBox as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the MultiColumnComboBox as a value.
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "Home") // Set the Action and Controller names.
.Data("onAdditionalData");
});
})
.SelectedIndex(0) // Select the first item.
)
<script>
function onAdditionalData() {
return {
text: $("#productMultiColumnComboBox").data("kendoMultiColumnComboBox").text()
};
}
</script>
public JsonResult GetProducts(string text)
{
var northwind = new SampleEntities();
var products = northwind.Products.Select(product => new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitPrice = product.UnitPrice ?? 0,
UnitsInStock = product.UnitsInStock ?? 0,
UnitsOnOrder = product.UnitsOnOrder ?? 0,
626
Telerik UI for ASP.NET Core
Discontinued = product.Discontinued
});
if (!string.IsNullOrEmpty(text))
{
products = products.Where(p => p.ProductName.Contains(text));
}
return Json(products, JsonRequestBehavior.AllowGet);
}
The MultiColumnComboBox has a default event handler for the Data callback of the DataSource
which is used when no event handler is defined. The MultiColumnComboBox sends the value of the
input only if the end user starts to type in it.
function requestData(selector) {
var multicolumncombobox = $(selector).data("kendoMultiColumnComboBox"),
filters = multicolumncombobox.dataSource.filter(),
value = multicolumncombobox.input.val();
if (!filter || !filter.filters.length) {
value = "";
}
return { text: value };
}
See Also
Basic Usage of the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
MultiColumnComboBoxBuilder Server-Side API
MultiColumnComboBox Server-Side API
627
Telerik UI for ASP.NET Core
Model Binding
You can implement model binding both with local dataand remote data.
Local Data
Local data is the data that is available on the client when the MultiColumnComboBox is initialized.
public ActionResult Index()
{
ViewData["products"] = GetProducts();
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return products;
}
2. Add the MultiColumnComboBox to the view and bind it to the data that is saved in the
ViewData.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBoxFor(m => m.ProductID)
.DataValueField("ProductID")
.DataTextField("ProductName")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Remote Data
628
Telerik UI for ASP.NET Core
You can configure the MultiColumnComboBox to get its data from a remote source by making an
AJAX request.
public ActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
public JsonResult GetProductsAjax()
{
var products = Enumerable.Range(0, 500).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
return Json(products, JsonRequestBehavior.AllowGet);
}
2. Add the MultiColumnComboBox to the view and configure its DataSource to use remote
data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBoxFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.Placeholder("Select product...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProductsAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Basic Usage of the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
MultiColumnComboBoxBuilder Server-Side API
629
Telerik UI for ASP.NET Core
630
Telerik UI for ASP.NET Core
Columns
The MultiColumnComboBox allows you to predefine the columns that will be rendered in its
drop-down list through the dropDownWidth option.
If the widths of all columns are defined in pixels through their width option, the
dropDownWidth value (if set) is overridden.
In all other cases when the widths of all columns are not set, the dropDownWidth value is
applied to the element.
You can also define which dataItem field will be populated and also set a title, a template, and a
headerTemplate.
@(Html.Kendo().MultiColumnComboBox()
.Name("multicolumncombobox")
.Columns(columns =>
{
columns.Add().Field("ContactName").Title("Contact Name").Width("200px")
columns.Add().Field("ContactTitle").Title("Contact Title").Width("200px");
columns.Add().Field("CompanyName").Title("Company Name").Width("200px");
columns.Add().Field("Country").Title("Country").Width("200px");
})
.DataSource(source => source
.Read(read => read.Action("Products_Read", "MultiColumnComboBox"))
.ServerFiltering(true)
)
)
See Also
Server-Side API
631
Telerik UI for ASP.NET Core
Grouping
The MultiColumnComboBox supports binding to a grouped data source.
To group the data by using the custom DataSource configuration, define a datasource group
expression. For more information, refer to the demo on grouping the data in the
MultiColumnComboBox.
The data source sorts the grouped data either in ascending or descending order. To persist a
specific group order, use the server grouping feature. To define the serverGrouping option, use the
DataSource ServerGrouping method.
See Also
Grouping by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
MultiColumnComboBoxBuilder Server-Side API
MultiColumnComboBox Server-Side API
632
Telerik UI for ASP.NET Core
Filtering
Apart from the standard filter options, the MultiColumnComboBox allows you to set fields against
which the data will be filtered.
@(Html.Kendo().MultiColumnComboBox()
.Name("multicolumncombobox")
.Filter("contains")
.FilterFields(new string[] { "ContactName", "ContactTitle" })
.Columns(columns =>
{
columns.Add().Field("ContactName").Title("Contact Name").Width("200px")
columns.Add().Field("ContactTitle").Title("Contact Title").Width("200px");
columns.Add().Field("CompanyName").Title("Company Name").Width("200px");
columns.Add().Field("Country").Title("Country").Width("200px");
})
.DataSource(source => source
.Read(read => read.Action("Products_Read", "MultiColumnComboBox"))
.ServerFiltering(true)
)
)
See Also
Server Filtering by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Client Filtering by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
633
Telerik UI for ASP.NET Core
Virtualization
You can configure a MultiColumnComboBox to use virtualization.
For the virtualization to work properly, define the widths of all columns in pixels.
The MultiColumnComboBox supports server binding to primitive or an enum value types
only.
public IActionResult Index()
{
return View(new ProductViewModel
{
ProductID = 4,
ProductName = "ProductName4"
});
}
[HttpPost]
public IActionResult ProductsVirtualization_Read([DataSourceRequest]
DataSourceRequest request)
{
return Json(GetProducts().ToDataSourceResult(request));
}
public IActionResult Products_ValueMapper(int[] values)
{
var indices = new List<int>();
if (values != null && values.Any())
{
var index = 0;
foreach (var product in GetProducts())
{
if (values.Contains(product.ProductID))
{
indices.Add(index);
}
index += 1;
}
}
return Json(indices);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var products = Enumerable.Range(0, 2000).Select(i => new ProductViewModel
{
ProductID = i,
ProductName = "ProductName" + i
});
634
Telerik UI for ASP.NET Core
return products;
}
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBoxFor(m => m.ProductID)
.Filter("contains")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Columns(columns =>
{
columns.Add().Field("ProductName").Title("Product Name").Width("200px")
columns.Add().Field("ProductID").Title("Product ID").Width("200px");
})
.Placeholder("Select product...")
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("ProductsVirtualization_Read", "Home");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
<script>
function valueMapper(options) {
$.ajax({
url: "@Url.Action("Products_ValueMapper", "Home")",
data: convertValues(options.value),
success: function (data) {
options.success(data);
}
});
}
function convertValues(value) {
var data = {};
value = $.isArray(value) ? value : [value];
for (var idx = 0; idx < value.length; idx++) {
data["values[" + idx + "]"] = value[idx];
}
return data;
}
</script>
635
Telerik UI for ASP.NET Core
If the AutoBind option of the MultiColumnComboBox is set to false and you need the widget to
display the model value as selected, set the Text configuration option by passing the field set as
DataTextField to the Text option.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiColumnComboBoxFor(m => m.ProductID)
.AutoBind(false)
.Text(Model.ProductName)
.DataTextField("ProductName")
// Additional configuration.
)
See Also
Virtualization by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
636
Telerik UI for ASP.NET Core
MultiColumnComboBox Accessibility
The MultiColumnComboBox is accessible by screen readers and provides WAI-ARIA, Section 508,
WCAG 2.1, and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The MultiColumnComboBox is compliant with the Section 508 requirements. For more information,
refer to the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The MultiColumnComboBox supports the standards for providing accessible web content which are
set by the Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG
2.1 compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the MultiColumnComboBox HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
637
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the MultiColumnComboBox is always available.
For a complete example, refer to the demo on keyboard navigation of the MultiColumnComboBox.
See Also
Keyboard Navigation in the MultiColumnComboBox HtmlHelper for ASP.NET Core (Demo)
Accessibility in the MultiColumnComboBox HtmlHelper for ASP.NET Core
638
Telerik UI for ASP.NET Core
The MultiSelect displays a list of options and allows multiple selections from this list. The widget
represents a richer version of the <select> element and provides support for local and remote data
binding, item and tag templates, and configurable options for controlling the list behavior.
@(Html.Kendo().MultiSelect()
.Name("multiselect")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Value(new[] { 2, 7 })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read", "Home");
})
.ServerFiltering(true);
})
)
public class MultiSelectController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult Products_Read(string text)
{
var result = GetProducts();
if (!string.IsNullOrEmpty(text))
{
result = result.Where(p => p.ProductName.Contains(text)).ToList();
}
return Json(result);
}
private static IEnumerable<ProductViewModel> GetProducts()
{
var result = Enumerable.Range(0, 50).Select(i => new ProductViewModel
639
Telerik UI for ASP.NET Core
{
ProductID = "" + i,
ProductName = "Product " + i
});
return result;
}
}
Basic Configuration
The following example demonstrates the basic configuration of the MultiSelect HtmlHelper. To get a
reference to an existing Telerik UI MultiSelect instance, use the jQuery.data()configuration
option. Once a reference is established, use the MultiSelect APIto control its behavior.
@(Html.Kendo().MultiSelect()
.Name("multiselect")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Placeholder("Select product...")
.ItemTemplate("<span class=\"product-id-id\">#= ProductID #</span> #= ProductName
#")
.Value(new[] { 2, 7 })
.Height(520)
.TagMode(MultiSelectTagMode.Single)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Products_Read", "Home");
})
.ServerFiltering(true);
})
.Events(events => events
.Change("onChange")
.Select("onSelect")
.Deselect("onDeselect")
.Open("onOpen")
.Close("onClose")
.DataBound("onDataBound")
.Filtering("onFiltering")
)
)
<script type="text/javascript">
$(function () {
// The Name() of the MultiSelect is used to get its client-side instance.
var multiselect = $("#multiselect").data("kendoMultiSelect");
});
</script>
640
Telerik UI for ASP.NET Core
Templates
Accessibility
Events
You can subscribe to all MultiSelect events. For a complete example on basic MultiSelect events,
refer to the demo on using the events of the MultiSelect.
@(Html.Kendo().MultiSelect()
.Name("multiselect")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("multiselect_select")
.Change("multiselect_change")
)
)
<script>
function multiselect_select() {
// Handle the select event.
}
function multiselect_change() {
// Handle the change event.
}
</script>
@(Html.Kendo().MultiSelect()
.Name("multiselect")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select(@<text>
function() {
// Handle the select event inline.
}
</text>)
.Change(@<text>
function() {
// Handle the change event inline.
}
</text>)
)
)
See Also
641
Telerik UI for ASP.NET Core
642
Telerik UI for ASP.NET Core
Data Binding
The MultiSelect provides a set of options for binding it to data.
Ajax binding
Server binding
Custom data binding
Model binding
Local binding
Remote binding
See Also
Server-Side API
643
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Telerik UI MultiSelect for Ajax binding to the Northwind Products table which
uses Linq to SQL.
The ToDataSourceResult() extension method modifies the structure of the result and the widget
is not able to bind to it. In this case, return a simple array of data.
public IActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products, JsonRequestBehavior.AllowGet);
}
@(Html.Kendo().MultiSelect()
.Name("productMultiSelect") // The name of the MultiSelect is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the DropDownList as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the DropDownList as a value.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "Home"); // Set the Action and Controller
names.
})
.ServerFiltering(true); // If true, the DataSource will not filter the
data on the client.
})
)
644
Telerik UI for ASP.NET Core
See Also
Server-Side API
645
Telerik UI for ASP.NET Core
Server Binding
You can configure the Telerik UI MultiSelect for server binding to the Northwind Products table
which uses Linq to SQL.
1. Create a new action method and pass the Products table as the model.
public IActionResult Index()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return View(northwind.Products);
}
@model IEnumerable<MvcApplication1.Models.Product>
@(Html.Kendo().MultiSelect()
.Name("productDropDownList") // The name of the MultiSelect is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the MultiSelect as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the MultiSelect as a value.
.BindTo(Model) // Pass the list of Products to the MultiSelect.
)
See Also
Server Filtering by the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Client Filtering by the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Server-Side API
646
Telerik UI for ASP.NET Core
public IActionResult Index()
{
return View();
}
2. Create a new action method and pass the Products table as JSON result.
public JsonResult GetProducts([DataSourceRequest] DataSourceRequest request)
{
NorthwindDataContext northwind = new NorthwindDataContext();
return Json(northwind.Products.ToDataSourceResult(request));
}
@(Html.Kendo().MultiSelect()
.Name("productDropDownList") // The name of the MultiSelect is mandatory. It
specifies the "id" attribute of the widget.
.DataTextField("ProductName") // Specify which property of the Product to be
used by the MultiSelect as a text.
.DataValueField("ProductID") // Specify which property of the Product to be
used by the MultiSelect as a value.
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.Type("aspnetmvc-ajax") // Set this type if you want to use
DataSourceRequest and ToDataSourceResult instances.
.Transport(transport =>
{
transport.Read("GetProducts", "Home");
})
.Schema(schema =>
{
schema.Data("Data") // Define the
[data](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configur
ation-schema.data) option.
.Total("Total"); // Define the
[total](http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configu
ration-schema.total) option.
});
})
)
647
Telerik UI for ASP.NET Core
See Also
Server-Side API
648
Telerik UI for ASP.NET Core
Model Binding
You can implement model binding in the MultiSelect with both local dataand remote data.
Local Data
Local data is the data that is available on the client when the MultiSelect is initialized.
public IActionResult Index()
{
return View(new ProductViewModel
{
Orders = GetOrders(),
SelectedOrders = new int[] { 1, 3 }
});
}
private static List<Order> GetOrders()
{
var orders = Enumerable.Range(0, 2000).Select(i => new Order
{
OrderID = i,
OrderName = "OrderName" + i
});
return orders.ToList();
}
2. Add the MultiSelect to the view and bind it to a property of the view model.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiSelectFor(m => m.SelectedOrders)
.DataValueField("OrderID")
.DataTextField("OrderName")
.BindTo(Model.Orders)
)
Remote Data
You can configure the MultiSelect to get its data from a remote source by making an AJAX request.
649
Telerik UI for ASP.NET Core
int[] { 1, 3 } }); }
public JsonResult GetOrdersAjax()
{
var orders = Enumerable.Range(0, 2000).Select(i => new Order
{
OrderID = i,
OrderName = "OrderName" + i
});
return Json(orders.ToList(), JsonRequestBehavior.AllowGet);
}
2. Add the MultiSelect to the view and configure its DataSource to use remote data.
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiSelectFor(m => m.SelectedOrders)
.Filter("contains")
.DataValueField("OrderID")
.DataTextField("OrderName")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetOrdersAjax", "Home");
})
.ServerFiltering(false);
})
)
See Also
Server-Side API
650
Telerik UI for ASP.NET Core
Templates
The MultiSelect provides full control over the way items, tags, or a pop-up header is rendered
through the Kendo UI for jQuery templates.
Basic Usage
The following example demonstrates how to customize the MultiSelect by referencing a script tag by
its id.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.ItemTemplateId("itemTemplate") //Reference to the template
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
The following example demonstrates how to customize the MultiSelect by declaring an inline string.
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.ItemTemplate("<span><h3>#: data.ContactName #</h3><p>#: data.CompanyName
#</p></span>")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
Item Template
The item template manages the way the list items of a MultiSelect are rendered.
651
Telerik UI for ASP.NET Core
The following example demonstrates how to define an item template and how to evaluate it against
the dataItem.
<!-- Template -->
<script id="itemTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#, CustomerID: #:data.CustomerID#
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.ItemTemplateId("itemTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
Tag Template
The tag template manages the way the tag of a MultiSelect is rendered.
<!-- Template -->
<script id="tagTemplate" type="text/x-kendo-template">
ContactName: #:data.ContactName#
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.TagTemplateId("tagTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
Header Template
The header template manages the way the pop-up header of a MultiSelect is rendered.
652
Telerik UI for ASP.NET Core
<!-- Template -->
<script id="headerTemplate" type="text/x-kendo-template">
<strong>Header</strong>
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.HeaderTemplateId("headerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
Footer Template
The footer template manages the way the pop-up footer of a MultiSelect is rendered. The footer is
re-rendered on every change of the DataSource. The context of the template is the widget itself.
<!-- Template -->
<script id="footerTemplate" type="text/x-kendo-template">
Total <strong>#: instance.dataSource.total() #</strong> items found
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.FooterTemplateId("footerTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
No-Data Templates
The MultiSelect displays noDataTemplate in the popup when the data source is empty.
<!-- Template -->
653
Telerik UI for ASP.NET Core
<script id="noDataTemplate" type="text/x-kendo-template">
<strong>No Data!</strong>
</script>
<!-- MultiSelect initialization -->
@(Html.Kendo().MultiSelect()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.NoDataTemplateId("noDataTemplate") // Reference to the template.
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Customers_Read", "MultiSelect");
});
})
)
See Also
Customizing Templates in the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Server-Side API
654
Telerik UI for ASP.NET Core
Virtualization
Virtualization is useful for displaying large data sets.
The UI virtualization technique uses a fixed amount of list items in the popup list of the widget
regardless of the dataset size. When the list is scrolled, the widget reuses the existing items to
display the relevant data instead of creating new ones.
If the AutoBind option of the MultiSelect is set to false, the widget will be able to display
pre-selected items only after it is focused.
public IActionResult Index()
{
return View(new ProductViewModel
{
SelectedOrders = new int[] { 1, 3 }
});
}
[HttpPost]
public IActionResult OrdersVirtualization_Read([DataSourceRequest]
DataSourceRequest request)
{
return Json(GetOrders().ToDataSourceResult(request));
}
public IActionResult Orders_ValueMapper(int[] values)
{
var indices = new List<int>();
if (values != null && values.Any())
{
var index = 0;
foreach (var order in GetOrders())
{
if (values.Contains(order.OrderID))
{
indices.Add(index);
}
index += 1;
}
}
return Json(indices);
}
private static List<Order> GetOrders()
{
var orders = Enumerable.Range(0, 2000).Select(i => new Order
{
OrderID = i,
655
Telerik UI for ASP.NET Core
OrderName = "OrderName" + i
});
return orders.ToList();
}
@model MvcApplication1.Models.ProductViewModel
@(Html.Kendo().MultiSelectFor(m => m.SelectedOrders)
.Filter("contains")
.DataValueField("OrderID")
.DataTextField("OrderName")
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("OrdersVirtualization_Read", "Home");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
.Virtual(v => v.ItemHeight(26).ValueMapper("valueMapper"))
)
<script>
function valueMapper(options) {
$.ajax({
url: "@Url.Action("Orders_ValueMapper", "Home")",
data: convertValues(options.value),
success: function (data) {
options.success(data);
}
});
}
function convertValues(value) {
var data = {};
value = $.isArray(value) ? value : [value];
for (var idx = 0; idx < value.length; idx++) {
data["values[" + idx + "]"] = value[idx];
}
return data;
}
</script>
656
Telerik UI for ASP.NET Core
See Also
Virtualization by the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Server-Side API
657
Telerik UI for ASP.NET Core
Grouping
The MultiSelect allows you to bind it to a grouped data source.
To group the data, define a group datasource expression which uses a custom DataSource
configuration, and specify the field by which the MultiSelect will be grouped.
The data source sorts the grouped data either in ascending or descending order. To persist a
specific group order, use the server grouping feature of Kendo UI for jQuery. To define the
serverGrouping option, use the ServerGrouping method of the DataSource.
The following example demonstrates how to group the data in the MultiSelect by country.
@(Html.Kendo().MultiSelect()
.Name("customers")
.Placeholder("Select customers...")
.DataSource(source => source
.Custom()
.Group(g => g.Add("Country", typeof(string)))
.Transport(transport => transport
.Read(read =>
{
read.Action("Customers_Read", "MultiSelect")
.Data("onAdditionalData");
}))
.ServerFiltering(true))
.DataTextField("ContactName")
.DataValueField("CustomerID")
)
<script>
function onAdditionalData() {
return {
text: $("#customers").val()
};
}
</script>
See Also
Grouping by the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Server-Side API
658
Telerik UI for ASP.NET Core
MultiSelect Accessibility
The MultiSelect is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in UI for ASP.NET Core.
The MultiSelect provides the following building blocks which, depending on its current state and
options, use different aria properties on their nested elements:
Search Input
If the placeholder option is set and in order for screen readers to announce the placeholder text,
you have to manually toggle the WAI-ARIA label attribute on the input element.
The MultiSelect implements the following WAI-ARIA roles, states, and properties for its search input:
659
Telerik UI for ASP.NET Core
Tag List
In order for the screen readers to announce the selected options after deleting an item from the tag
list:
The MultiSelect implements the following WAI-ARIA roles, states, and properties for its tag list:
660
Telerik UI for ASP.NET Core
Items Popup
The MultiSelect implements the following WAI-ARIA roles, states, and properties for its items popup:
Section 508
The MultiSelect is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The MultiSelect supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the MultiSelect HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the MultiSelect HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
661
Telerik UI for ASP.NET Core
Keyboard Navigation
The MultiSelect also follows the WAI-ARIA best practicesfor implementing the keyboard navigationfor
its component role and is tested against the popular screen readers.
The keyboard navigation of the MultiSelect is always available. For a complete example, refer to the
demo on keyboard navigation of the MultiSelect.
See Also
Keyboard Navigation by the MultiSelect (Demo)
Accessibility in the MultiSelect HtmlHelper for ASP.NET Core
662
Telerik UI for ASP.NET Core
The NumericTextBox allows the user to select numeric values through direct input or using spinner
buttons.
@(Html.Kendo().NumericTextBox()
.Name("numerictextbox") // The name of the NumericTextBox is mandatory. It
specifies the "id" attribute of the widget.
)
Events
You can subscribe to all NumericTextBox events. For a complete example on basic NumericTextBox
events, refer to the demo on using the events of the NumericTextBox.
@(Html.Kendo().NumericTextBox()
.Name("numerictextbox")
.Events(e => e
.Change("numerictextbox_change")
.Spin("numerictextbox_spin")
)
)
<script>
function numerictextbox_spin() {
// Handle the spin event.
}
function numerictextbox_change() {
// Handle the change event.
}
663
Telerik UI for ASP.NET Core
</script>
@(Html.Kendo().NumericTextBox()
.Name("numerictextbox") // The name of the NumericTextBox is mandatory. It
specifies the "id" attribute of the helper.
)
<script>
var numericTextBox = $('#numerictextbox').data('kendoNumericTextBox'); //
numericTextBox is a reference to the instance of the helper.
</script>
See Also
Basic Usage by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Using the API of the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Known Limitations of the NumericTextBox HtmlHelper for ASP.NET Core
Server-Side API
664
Telerik UI for ASP.NET Core
Formats
The NumericTextBox accepts only numeric entries and its specific format defines the conversion
data type—for example, currency or percentage.
@(Html.Kendo().NumericTextBox()
.Name("currency")
.Format("c")
)
@(Html.Kendo().NumericTextBox()
.Name("percentage")
.Format("p0")
)
See Also
Using the API of the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
665
Telerik UI for ASP.NET Core
Input Restrictions
The NumericTextBox enables you to control the precision of the entered numberand also restrict its
value to a specific range.
Numbers
The NumericTextBox controls the precision of the entered number by using the value of the
Decimalsoption which limits the length of the input number to the Decimals length.
By default, the helper does not restrict the length of the typed value. To enforce a specific fraction
length during editing, set the RestrictDecimalsoption to true.
The helper controls the precision of the entered number by using the half-up rounding technique. To
disable this functionality, use the Roundconfiguration option. Once you turn off the rounding, the
value is truncated up to the desired precision length without rounding it.
Value Ranges
You can restrict the value of the NumericTextBox to a specific range by using either of the following
approaches:
Restrict the input value between a specific Minand Maxrange. The typed value gets modified
to fit the range on blur.
Use a custom Kendo UI Validator rule to restrict the input value. The invalid value remains
unchanged and the user is notified for the incorrect input by an error message. For more
information, refer to the article on the custom validation rules.
See Also
Using the API of the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
666
Telerik UI for ASP.NET Core
Known Limitations
The NumericTextBox comes with a couple of limitations that affect its behavior.
This limitation comes from JavaScript and cannot be worked around in a feasible way. You are
recommended to use an <input> element with server validation because some server languages
can parse long numbers.
On the other hand, if the user enters a number with a greater precision than is currently configured
through the decimals property, the widget value will be rounded. For more details and examples,
refer to the API documentation on Decimals.
Input Type
The NumericTextBox uses <input type="text" /> elements. If initialized from an <input
type="number" /> element, the widget switches the input type to text. This behavior enables the
support for the comma (,) as a decimal separator in some non-en-US cultures. Currently, browsers
ignore the culture of the client and the values that contain a comma as a decimal separator.
The side effect of using a text input type is that it prevents the numeric keyboard from appearing
on mobile devices with context-specific software keyboards.
Use a plain numeric input for mobile devices and add a k-textboxCSS class to apply Telerik
UI styling.
Change the input type back to number after the NumericTextBox initializes. This is possible
only for cultures that use a dot (.) as a decimal separator.
/* Helper configuration. */
@(Html.Kendo().NumericTextBox()
.Name("numerictextbox")
)
/* Set the input type to "number". */
<script>
$("#numerictextbox").attr("type", "number");
</script>
/* Alternatively, if the helper object is already available, use the following
setting. */
667
Telerik UI for ASP.NET Core
<script>
var numericTextBoxObject = $("#numerictextbox").data("kendoNumericTextBox");
numericTextBoxObject.element.attr("type", "number");
</script>
See Also
Using the API of the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
668
Telerik UI for ASP.NET Core
NumericTextBox Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
To determine the number precision and other culture-specific properties, the NumericTextBox uses
the kendo.culture.current culture.
Localization of messages
Right-to-left support
See Also
Globalization Support by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
RTL Support by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
669
Telerik UI for ASP.NET Core
Localization
The NumericTextBox provides options for localizing its user interface by utilizing the available
configuration options.
You can change the messages that are displayed in the NumericTextBox by including an additional
messages script file in the document. For example, including the following script to the page will
translate all messages to Bulgarian.
<script
src="http://kendo.cdn.telerik.com/<version>/js/messages/kendo.messages.bg-BG.min.js"><
/script>
See Also
Globalization Support by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
670
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the NumericTextBox.
See Also
RTL Support by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Server-Side API
671
Telerik UI for ASP.NET Core
NumericTextBox Accessibility
The NumericTextBox is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG
2.1, and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers.
Section 508
The NumericTextBox is compliant with the Section 508 requirements.
WCAG 2.1
The NumericTextBox supports the standards for providing accessible web content which are set by
the Web Content Accessibility Guidelines 2.1.
@Html.Label("numeric", "Value")
@Html.Kendo().NumericTextBox().Name("numeric")
<script>
var roles = {
numerictextbox: "kendoNumericTextBox",
combobox: "kendoComboBox",
multiselect: "kendoMultiSelect"
}
function getWidget(element) {
var role = element.data("role");
role = roles[role];
if (role) {
return element.data(role);
}
}
$("label").click(function() {
672
Telerik UI for ASP.NET Core
var label = $(this),
id = label.attr("for"),
widget;
if (id) {
widget = getWidget($("#" + id));
if (widget) {
widget.focus();
}
}
});
</script>
See Also
Keyboard Navigation by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
673
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the NumericTextBox is always available.
For a complete example, refer to the demo on keyboard navigation of the NumericTextBox.
For more information on rendering a numeric software keyboard, refer to the article on known
limitations.
See Also
Keyboard Navigation by the NumericTextBox HtmlHelper for ASP.NET Core (Demo)
Accessibility in the NumericTextBox HtmlHelper for ASP.NET Core
674
Telerik UI for ASP.NET Core
The Rating allows to intuitively rate by selecting number of items stars from a predefined maximum
number of items.
@(Html.Kendo().Rating()
.Name("rating")
)
Basic Configuration
The following example demonstrates the basic configuration for the Rating HtmlHelper.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
)
<script>
$(function() {
// The Name() of the Rating is used to get its client-side instance.
var rating = $("#rating").data("kendoRating");
});
</script>
See Also
675
Telerik UI for ASP.NET Core
676
Telerik UI for ASP.NET Core
Selection
The Rating allows you to control the selection of its items.
continuous—Allows the selection of all items from the start to the end.
single—Allows the selection of a single item.
Continuous Selection
The continuous selection is the default selection mode of the Rating. If not configured, the Rating
will automatically set the Selectionproperty to "continuous".
@(Html.Kendo().Rating()
.Name("rating")
.Selection("continuous")
)
Single Selection
To configure the single selection mode, set the Selectionproperty to "single".
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.Selection("single")
)
See Also
Selection by the Rating HtmlHelper for ASP.NET Core (Demo)
Server-Side API
677
Telerik UI for ASP.NET Core
Precision
The Rating allows you to control the precision with which an item is selected.
Item Precision
The item mode is the default precision mode of the Rating. If not configured, the widget will
automatically set the Precisionproperty to "item" which enables only whole stars to be selected
by click or keyboard interaction.
@(Html.Kendo().Rating()
.Name("rating")
.Precision("item")
)
Half Precision
To configure he half precision mode of the Rating, set the Precisionoption to "half" which allows
you to set decimal values. The passed value is rounded during the rendering phase to display a full
or half item based on the following value specifics:
@(Html.Kendo().Rating()
.Name("rating1")
.Min(1)
.Max(6)
.Value(3.2)
.Precision("half")
)
<br>
@(Html.Kendo().Rating()
.Name("rating2")
.Min(1)
.Max(6)
.Value(3.5)
.Precision("half")
)
<br>
@(Html.Kendo().Rating()
.Name("rating3")
.Min(1)
.Max(6)
.Value(3.7)
678
Telerik UI for ASP.NET Core
.Precision("half")
)
See Also
Precision by the Rating HtmlHelper for ASP.NET Core (Demo)
Server-Side API
679
Telerik UI for ASP.NET Core
Label
By default, the Rating displays a label that shows the current value out of the max value in the format
3 / 5.
If the Rating does not have a selected value, the label will not be displayed initially and will be
toggled after an item is selected.
Getting Started
The following example demonstrates how to use the default label.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
)
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.Label(l => l.TemplateId("rating-label-template"))
)
<script id="rating-label-template" type="text/x-kendo-template">
<span>
#: value # out of #: maxValue #
</span>
</script>
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
680
Telerik UI for ASP.NET Core
.Label(false)
)
See Also
Server-Side API
681
Telerik UI for ASP.NET Core
Tooltip
Each Rating item displays a tooltip that is enabled by default and contains text that is equal to the
value of the item.
Getting Started
The following example demonstrates how to use the default tooltip of the Rating.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
)
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.Tooltip(false)
)
See Also
Server-Side API
682
Telerik UI for ASP.NET Core
Templates
By default, each Rating item is rendered with a star icon from the Kendo Web Font Icons.
To modify the default icon, use the ItemTemplate, SelectedTemplate, and HoveredTemplate
properties.
Item Template
The item template specifies the template which is used for rendering the items of the Rating. If the
SelectedTemplate is not specified, the helper will use the default start icon for selected items.
Therefore, it is recommended that you specify the SelectedTemplate when the ItemTemplate
option is used.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.ItemTemplate("<i class='k-icon k-i-heart-outline'></i>")
.SelectedTemplate("<i class='k-icon k-i-heart'></i>")
)
Selected Template
The selected template specifies the template for rendering the selected state of the items. If the
ItemTemplate is not specified, the helper will use the default start icon for displaying the normal
state of the items. Therefore, it is recommended that you specify the ItemTemplate when the
SelectedTemplate option is used.
When the Rating is in half precision mode, use the same template for both the SelectedTemplate
and HoveredTemplate options.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.ItemTemplate("<i class='k-icon k-i-heart-outline'></i>")
.SelectedTemplate("<i class='k-icon k-i-heart'></i>")
)
Hovered Template
The hovered template specifies the template which is used for rendering the hovered state of the
items. If the ItemTemplate is not specified, the helper will use the default start icon for displaying
683
Telerik UI for ASP.NET Core
When the Rating is in half precision mode, use the same template for both the SelectedTemplate
and HoveredTemplate options.
@(Html.Kendo().Rating()
.Name("rating")
.Min(1)
.Max(6)
.Value(3)
.HoveredTemplate("<i class='k-icon k-i-heart'></i>")
)
See Also
Server-Side API
684
Telerik UI for ASP.NET Core
Rating Accessibility
The Rating is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Rating is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Rating supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Rating HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Rating HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
685
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Rating is always available.
For a complete example, refer to the demo on keyboard navigation of the Rating.
See Also
Keyboard Navigation in the Rating HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Rating HtmlHelper for ASP.NET Core
686
Telerik UI for ASP.NET Core
The Slider provides a rich input for selecting numeric values. The Slider can either present one
handle and two opposing buttons for selecting a single numeric value, or two handlers for defining a
range of numeric values. Unlike the HTML5 range input, the Slider enables the consistent experience
across browsers and delivers rich API calls and event models.
@(Html.Kendo().Slider()
.Name("slider") // The name of the Slider is mandatory. It specifies the "id"
attribute of the widget.
.Min(0) // Set min value of the Slider.
.Max(100) // Set min value of the Slider.
.Value(20) // Set the value of the Slider.
)
@(Html.Kendo().RangeSlider()
.Name("rangeslider")
.Min(0)
.Max(10)
.SmallStep(1)
.LargeStep(10))
Events
You can subscribe to all Slider events. For a complete example on basic Slider events, refer to the
demo on using the events of the Slider.
@(Html.Kendo().Slider()
.Name("slider")
.Events(e => e
.Change("change")
.Slide("slide")
)
)
<script>
function change(e) {
// Handle the change event.
687
Telerik UI for ASP.NET Core
}
function slide(e) {
// Handle the slide event.
}
</script>
@(Html.Kendo().Slider()
.Name("slider")
.Events(e => e
.Change(@<text>
function(e) {
// Handle the change event inline.
}
</text>)
.Slide(@<text>
function(e) {
// Handle the slide event inline.
}
</text>)
)
)
// Place the following after your Telerik UI Slider for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the Slider is used to get its client-side instance.
var slider = $("#slider").data("kendoSlider");
});
</script>
See Also
Basic Usage by the Slider HtmlHelper for ASP.NET Core (Demo)
Using the API of the Slider HtmlHelper for ASP.NET Core (Demo)
Server-Side API
688
Telerik UI for ASP.NET Core
The Switch displays two exclusive choices. With the new Switch variables introduced in the Kendo UI
for jQuery R1 2019 release, the default styling of the Switch component for each of the Sass-based
Kendo UI for jQuery themescan be modified to match the desired custom layout. For more
information and examples, refer to the article on implementing a custom layout for the Switch.
@(Html.Kendo().Switch()
.Name("switch") // The name of the Switch is mandatory. It specifies the "id"
attribute of the widget.
.Checked(true)
)
Events
You can subscribe to all Switch events. For a complete example on basic Slider events, refer to the
demo on using the events of the Slider.
@(Html.Kendo().Switch()
.Name("switch")
.Events(e => e
.Change("change")
)
)
<script>
function change(e) {
//Handle the change event.
}
</script>
689
Telerik UI for ASP.NET Core
@(Html.Kendo().Switch()
.Name("switch")
.Events(e => e
.Change(@<text>
function(e) {
//Handle the change event inline.
}
</text>)
)
)
// Place the following after your Telerik UI Switch for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The Name() of the Switch is used to get its client-side instance.
var switch = $("#switch").data("kendoSwitch");
});
</script>
See Also
Basic Usage by the Switch HtmlHelper for ASP.NET Core (Demo)
Using the API of the Switch HtmlHelper for ASP.NET Core (Demo)
Server-Side API
690
Telerik UI for ASP.NET Core
Switch Accessibility
The Switch is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Switch is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Switch supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Switch HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Switch HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
691
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Switch is always available.
For a complete example, refer to the demo on keyboard navigation of the Switch.
See Also
Keyboard Navigation in the Switch HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Switch HtmlHelper for ASP.NET Core
692
Telerik UI for ASP.NET Core
The TimePicker enables users to select time values from a predefined list or enter new ones.
@(Html.Kendo().TimePicker()
.Name("timepicker") // The name of the TimePicker is mandatory. It specifies
the "id" attribute of the widget.
.Value(DateTime.Now) // Set the value of the TimePicker.
)
Events
You can subscribe to all TimePicker events. For a complete example on basic TimePicker events,
refer to the demo on using the events of the TimePicker.
@(Html.Kendo().TimePicker()
.Name("timepicker")
.Events(e => e
.Open("timepicker_open")
.Close("timepicker_close")
.Change("timepicker_change")
)
)
<script>
function timepicker_open(e) {
693
Telerik UI for ASP.NET Core
// Handle the open event.
}
function timepicker_close(e) {
// Handle the close event.
}
function timepicker_change(e) {
// Handle the change event.
}
</script>
@(Html.Kendo().TimePicker()
.Name("timepicker")
.Events(e => e
.Open(@<text>
function(e) {
// Handle the open event inline.
}
</text>)
.Change(@<text>
function(e) {
// Handle the change event inline.
}
</text>)
)
)
// Place the following after the TimePicker for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the TimePicker is used to get its client-side instance.
var timepicker = $("#timepicker").data("kendoTimePicker");
});
</script>
See Also
Basic Usage by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Using the API of the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
694
Telerik UI for ASP.NET Core
Selected Times
The TimePicker allows you to render a pre-selected time and also define the minimum and
maximum time it displays.
For a complete example on how to select ranges using TimePicker, refer to the demo on range
selection.
The following example demonstrates how to render a TimePicker with an initially selected time and
defined min and max times. The TimePicker sets the value only if the entered time is within the
defined range and is valid.
@(Html.Kendo().TimePicker()
.Name("timepicker")
.Value("8:00 AM")
.Min("8:00 AM")
.Max("5:00 PM")
)
See Also
Selecting Time Ranges with the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
695
Telerik UI for ASP.NET Core
Validation
The TimePicker is designed to keep its input value unchanged even when the typed time is invalid.
The TimePicker allows you to use different formats for time parsing. For more information,
refer to the ParseFormatsoption.
The TimePicker does not automatically update the typed text when the typed text is invalid.
Such changes in the input value may lead to unexpected behavior.
To validate the input value of the TimePicker on the client, use a client-validation framework such as
the Kendo UI Validator for jQuery. In this way, you can provide an error message to end users which
prompts them to do the right actions for them to resolve the issue. For more details, refer to the
demo on custom validation.
See Also
Server-Side API
696
Telerik UI for ASP.NET Core
Formats
The TimePicker allows you to define its time formatting.
@(Html.Kendo().TimePicker()
.Name("TimePicker")
.Value(DateTime.Now)
.Format("{0:hh:mm:ss tt}")
)
The following example demonstrates how to define the interval (in minutes) between the values in
the drop-down list with the time slots.
@(Html.Kendo().TimePicker()
.Name("TimePicker")
.Value(DateTime.Now)
.Interval(15)
)
See Also
Basic Usage by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Using the API of the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
697
Telerik UI for ASP.NET Core
TimePicker Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
Localization of messages
Right-to-left support
See Also
Globalization Support by the TimePicker HtmlHelper for ASP.NET Core (Demo)
RTL Support by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
698
Telerik UI for ASP.NET Core
Localization
The TimePicker provides options for localizing its user interface by utilizing its Cultureproperty.
To enable the desired culture, add a reference to the script file before the TimePicker is initialized
and include the desired culture in the settings of the helper.
<script
src="https://kendo.cdn.telerik.com/2019.2.619/js/cultures/kendo.culture.de-DE.min.js">
</script>
@(Html.Kendo().TimePicker()
.Name("TimePicker")
.Culture("de-DE")
)
See Also
Globalization Support by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
699
Telerik UI for ASP.NET Core
Right-to-Left Support
Right-to-left (RTL) support reflects the ability of a widget to render its content in a right-to-left
direction for right-to-left languages, such as Arabic, Hebrew, Chinese, or Japanese.
For more information, refer to the demo on RTL support by the TimePicker.
See Also
RTL Support by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Server-Side API
700
Telerik UI for ASP.NET Core
TimePicker Accessibility
The TimePicker is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The TimePicker is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The TimePicker supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
701
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the TimePicker is always available.
For a complete example, refer to the demo on keyboard navigation of the TimePicker.
See Also
Keyboard Navigation by the TimePicker HtmlHelper for ASP.NET Core (Demo)
Accessibility in the TimePicker HtmlHelper for ASP.NET Core
702
Telerik UI for ASP.NET Core
The Upload uses progressive enhancement to deliver the best possible uploading experience to
users, without requiring extra developer effort.
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveAsync", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
)
public IHostingEnvironment HostingEnvironment { get; set; }
public UploadController(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
public async Task<ActionResult> SaveAsync(IEnumerable<IFormFile> files)
{
// The Name of the Upload component is "files".
if (files != null)
{
foreach (var file in files)
{
var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// Some browsers send file names with full path.
// The sample is interested only in the file name.
var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
fileName);
// The files are not actually saved in this demo.
using (var fileStream = new FileStream(physicalPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
703
Telerik UI for ASP.NET Core
// Return an empty string to signify success.
return Content("");
}
public ActionResult Remove(string[] fileNames)
{
// The parameter of the Remove action must be called "fileNames".
if (fileNames != null)
{
foreach (var fullName in fileNames)
{
var fileName = Path.GetFileName(fullName);
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
fileName);
// TODO: Verify user permissions.
if (System.IO.File.Exists(physicalPath))
{
// The files are not actually removed in this demo.
// System. IO.File.Delete(physicalPath);
}
}
}
// Return an empty string to signify success.
return Content("");
}
Basic Configuration
The following example demonstrates the basic configuration of the Upload HtmlHelper and how to
get the Upload widget instance.
An Upload widget configured in such way offers support for multiple file selection, asynchronous
removal of uploaded files, progress tracking, in-progress cancellation of upload, file drag-and-drop.
Progress tracking, file drag-and-drop, and in-progress cancellation of upload are automatically
enabled if supported by the browser.
The Upload works in <input type="file" /> elements, so it is only able to upload files selected
by the user, which exist in the file system. For uploading files generated with JavaScript on the fly,
use another approach, e.g. an Ajax request.
@(Html.Kendo().Upload()
.Name("files")
.Multiple(true)
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
.ChunkSize(1100)
)
)
<script type="text/javascript">
$(function() {
704
Telerik UI for ASP.NET Core
// The Name() of the Upload is used to get its client-side instance.
var files = $("#files").data("kendoUpload");
});
</script>
Events
The following example demonstrates Upload HTML helper exposes several events, which could be
handled on the client-side. For a complete example on basic Upload events, refer to the demo on
using the events of the Upload.
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
.Events(events => events
.Cancel("onCancel")
.Complete("onComplete")
.Error("onError")
.Progress("onProgress")
.Remove("onRemove")
.Select("onSelect")
.Success("onSuccess")
.Upload("onUpload")
)
)
<script type="text/javascript">
function onSelect(e) {
console.log("Select :: " + getFileInfo(e));
}
function onUpload(e) {
console.log("Upload :: " + getFileInfo(e));
}
function onSuccess(e) {
console.log("Success (" + e.operation + ") :: " + getFileInfo(e));
}
function onError(e) {
console.log("Error (" + e.operation + ") :: " + getFileInfo(e));
705
Telerik UI for ASP.NET Core
}
function onComplete(e) {
console.log("Complete");
}
function onCancel(e) {
console.log("Cancel :: " + getFileInfo(e));
}
function onRemove(e) {
console.log("Remove :: " + getFileInfo(e));
}
function onProgress(e) {
console.log("Upload progress :: " + e.percentComplete + "% :: " +
getFileInfo(e));
}
function getFileInfo(e) {
return $.map(e.files, function(file) {
var info = file.name;
// File size is not available in all browsers.
if (file.size > 0) {
info += " (" + Math.ceil(file.size / 1024) + " KB)";
}
return info;
}).join(", ");
}
</script>
See Also
Basic Usage by the Upload HtmlHelper for ASP.NET Core (Demo)
Using the API of the Upload HtmlHelper for ASP.NET Core (Demo)
Server-Side API
706
Telerik UI for ASP.NET Core
Modes of Operation
The Upload provides the synchronousand asynchronousmodes of operation.
Synchronous Mode
An Upload in the synchronous mode behaves like a regular file input—the selected files are uploaded
upon form submission and users can select a set of files. When the Upload is in its synchronous
mode, the browser does not have to support multiple file selection.
<form method="post" action='@Url.Action("Submit")'>
<div class="demo-section k-content">
@(Html.Kendo().Upload()
.Name("files")
.HtmlAttributes(new { aria_label = "files" })
)
<p style="padding-top: 1em; text-align: right">
<button type="submit" class="k-button k-primary">Submit</button>
</p>
</div>
</form>
public IHostingEnvironment HostingEnvironment { get; set; }
public UploadController(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
public ActionResult Submit(IEnumerable<IFormFile> files)
{
// The Name of the Upload component is "files".
if (files != null)
{
foreach (var file in files)
{
var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// Some browsers send file names with full path.
// The demo is interested only in the file name.
var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
fileName);
// The files are not actually saved in this demo.
using (var fileStream = new FileStream(physicalPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return View("Result");
}
707
Telerik UI for ASP.NET Core
Asynchronous Mode
An Upload in the asynchronous mode requires dedicated server handlers to store and remove
uploaded files. Files are upload immediately or, optionally, after the confirmation from the user. The
upload request is executed out-of-band without interrupting the page flow. The asynchronous mode
is implemented through the HTML5 File API.
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveAsync", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
)
public IHostingEnvironment HostingEnvironment { get; set; }
public UploadController(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
public async Task<ActionResult> SaveAsync(IEnumerable<IFormFile> files)
{
// The Name of the Upload component is "files".
if (files != null)
{
foreach (var file in files)
{
var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
fileName);
// The files are not actually saved in this demo.
using (var fileStream = new FileStream(physicalPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
// Return an empty string to signify success.
return Content("");
}
public ActionResult Remove(string[] fileNames)
{
// The parameter of the Remove action must be called "fileNames".
if (fileNames != null)
{
foreach (var fullName in fileNames)
{
var fileName = Path.GetFileName(fullName);
708
Telerik UI for ASP.NET Core
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
fileName);
// TODO: Verify user permissions.
if (System.IO.File.Exists(physicalPath))
{
// The files are not actually removed in this demo.
// System.IO.File.Delete(physicalPath);
}
}
}
// Return an empty string to signify success.
return Content("");
}
Handlers
The save handler has to accept POST requests. The requests will contain one or more files with the
same name as the input—for example, "files[]" in the previous Controller example. The
handler is expected to return any of the following responses:
The remove handler has to accept POST requests. The requests will contain one or more text fields
with the "fileNames[]" name. The handler is expected to return any of the following responses:
The uploaded files must be handled both in the save handler and in the form submit action, as in
synchronous mode.
See Also
Asynchronous Mode of Operation by the Upload HtmlHelper for ASP.NET Core (Demo)
Server-Side API
709
Telerik UI for ASP.NET Core
Chunk Upload
The chunk upload of files enables the user to send large files which are uploaded asynchronously
with multiple requests to the server.
It also supports the pausing and resuming of the file upload during the time the application stays
open in the browser.
The chunk upload functionality is available only in the asynchronous modeof the Upload.
Basic Usage
To enable the chunk upload:
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
.ChunkSize(1100)
)
)
2. Implement the server-side logic (that is, the ChunkSave action is assigned) which processes
the file chunks and merges them into file:
public class ChunkMetaData
{
public string UploadUid { get; set; }
public string FileName { get; set; }
public string RelativePath { get; set; }
public string ContentType { get; set; }
public long ChunkIndex { get; set; }
public long TotalChunks { get; set; }
public long TotalFileSize { get; set; }
}
public class FileResult
{
// Because the chunks are sent in a specific order,
// the server is expected to send back a response
// with the meta data of the chunk that is uploaded.
public bool uploaded { get; set; }
public string fileUid { get; set; }
}
public void AppendToFile(string fullPath, IFormFile content)
710
Telerik UI for ASP.NET Core
{
try
{
using (FileStream stream = new FileStream(fullPath, FileMode.Append,
FileAccess.Write, FileShare.ReadWrite))
{
content.CopyTo(stream);
}
}
catch (IOException ex)
{
throw ex;
}
}
public ActionResult ChunkSave(IEnumerable<IFormFile> files, string metaData)
{
if (metaData == null)
{
return Save(files);
}
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(metaData));
JsonSerializer serializer = new JsonSerializer();
ChunkMetaData chunkData;
using (StreamReader streamReader = new StreamReader(ms))
{
chunkData = (ChunkMetaData)serializer.Deserialize(streamReader,
typeof(ChunkMetaData));
}
string path = String.Empty;
// The Name of the Upload component is "files".
if (files != null)
{
foreach (var file in files)
{
path = Path.Combine(HostingEnvironment.WebRootPath, "App_Data",
chunkData.FileName);
// AppendToFile(path, file);
}
}
FileResult fileBlob = new FileResult();
// This response indicates to the Upload
// that it can proceed either
// with the next chunk ("uploaded" = false) or with the next file
("uploaded" = true).
fileBlob.uploaded = chunkData.TotalChunks - 1<= chunkData.ChunkIndex;
fileBlob.fileUid = chunkData.UploadUid;
return Json(fileBlob);
}
public ActionResult Save(IEnumerable<IFormFile> files)
{
// The Name of the Upload component is "files".
if (files != null)
{
foreach (var file in files)
711
Telerik UI for ASP.NET Core
{
var fileContent =
ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// Some browsers send file names with full path.
// The demo is interested only in the file name.
var fileName =
Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(HostingEnvironment.WebRootPath,
"App_Data", fileName);
file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success.
return Content("");
}
As a client-side solution, the Upload does not handle validation. File validation and security
requirements have to be handled on the server by using application logic.
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
.ChunkSize(1100) // Will separate the file into chunks of size 11000 bytes.
.Concurrent(true) // Will upload all files simultaneously.
.AutoRetryAfter(300) // Will attempt a failed chunk upload after 300ms.
.MaxAutoRetries(4) // Will attempt the same failed chunk upload 4 times.
)
)
See Also
Chunk Upload by the Upload HtmlHelper for ASP.NET Core (Demo)
Server-Side API
712
Telerik UI for ASP.NET Core
You can also initialize custom drop zones depending on a particular selector that provides the
upload of a file through the drag-and-drop functionality.
1. Drag a file over the browser window for the drop zone to appear. When you pass the mouse
over the drop zone, it gets highlighted.
2. Release the file over the drop zone to add it to the upload queue.
<div class="dropZoneElement" style="height: 200px; width: 200px; border: 1px solid
red;">
</div>
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
.DropZone(".dropZoneElement")
)
To customize the appearance of the drop zone during the process of dragging and dropping, note
the following:
1. When the user drags the file over the browser window, the custom drop zone element
receives the "k-dropzone-active" class.
2. When the user drags the files over the drop zone itself, the element receives an additional
"k-dropzone-hovered" class and the drop zone is highlighted.
3. Once the file is released over the drop zone, it is added to the upload queue.
713
Telerik UI for ASP.NET Core
The following example demonstrates how to override the default drop zone—when the Upload itself
is used as a drop zone—by applying CSS rules.
div.k-dropzone {
border: 1px solid #c5c5c5; /* For Default; Different for each theme */
}
div.k-dropzone em {
visibility: visible;
}
The following example demonstrates how to customize the appearance of the drop zone during the
process of dragging and dropping.
div.k-dropzone {
border: 1px solid red;
}
.customDropZone.k-dropzone-active {
border: 1px solid yellow;
}
.customDropZone.k-dropzone-active.k-dropzone-hovered {
border: 1px solid green;
}
See Also
Custom Drop Zones by the Upload HtmlHelper for ASP.NET Core (Demo)
Server-Side API
714
Telerik UI for ASP.NET Core
File Identification
The internal implementation of the Upload widget allows you to identify which is the file object which
is in the process of uploading to the remote endpoint.
Regardless of the mode of operation, the Upload generates a unique identifier ( uid) for each file.
When the Upload is in a synchronous or asynchronous mode with its batch option enabled, the
single uid that is generated stands for the whole batch of files which were selected at the same
time. If the Upload is in an asynchronous mode with its batch option disabled, the Upload generates
a uid for each separate file.
The generated uid is added as a property of the e.files collection to all of the following events:
cancel
error
progress
remove
select
upload
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
)
.Events(events => events
.Select("onSelect")
)
)
<script type="text/javascript">
function onSelect(e) {
console.log("Selected files uids :: [ " + getFileInfo(e) + " ]");
}
function getFileInfo(e) {
return $.map(e.files, function(file) {
var info = file.uid;
return info;
}).join(", ");
}
</script>
See Also
Server-Side API
715
Telerik UI for ASP.NET Core
Metadata
Usually, asynchronous uploading means that you lose the association between the files and the
context they originate from.
For example, in an application, the save handler must associate the uploaded files with a particular
message. The message and the file might be processed on different servers in a load-balancing or
cloud-computing scenario.
Sending Metadata
To send metadata over to the Save() handler:
1. Add an input field for the file description. Its value is going to be sent to the save handler.
@(Html.Kendo().TextBox().Name("fileDescription"))
2. Declare a handler for the upload event and attach a data object to the passed event.
function onUpload(e) {
e.data = {
fileDescription: $("#fileDescription").val()
};
}
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
)
.Events(e => e.Upload("onUpload"))
)
4. Process the file and the associated description. The description, and any other fields of the
e.data object, will be serialized in the POST request.
Receiving Metadata
The save handler can sometimes produce a result that needs to be routed back to the page. The
716
Telerik UI for ASP.NET Core
The same approach of sending and receiving metadata is also applicable for the remove endpoint
handler.
To receive metadata from the save handler:
return Json(new object() { foo = "bar" });
function onSuccess(e) {
alert("Foo: " + e.response.foo);
}
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
)
.Events(e => e.Success("onSuccess"))
)
See Also
Server-Side API
717
Telerik UI for ASP.NET Core
File Validation
The Upload supports file validation—selected files can be validated against their extensions and
size.
Types of Validation
The Upload supports three types of validation:
File extension
Maximum file size
Minimum file size
The following example demonstrates a sample configuration for all the three types of validation.
@(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("ChunkSave", "Upload")
.Remove("Remove", "Upload")
)
.Validation(validation => validation
.AllowedExtensions(new string[] { ".gif", ".jpg", ".png" })
.MaxFileSize(31457280)
.MinFileSize(30720)
)
)
File Extension
The AllowedExtensions(), which accepts an array of strings listing all file extensions that are
allowed. If the user tries to select a file with an extension that is not included in the array, the
validation will fail.
718
Telerik UI for ASP.NET Core
Browser Limitations
Internet Explorer versions prior to version 10 provide no information on the file size. As a result, the
Upload validation for the MinFileSize() and MaxFileSize() options will not work as expected.
See Also
File Validation by the Upload HtmlHelper for ASP.NET Core (Demo)
Server-Side API
719
Telerik UI for ASP.NET Core
Troubleshooting
This page provides solutions for common problems you may encounter while working with the
Telerik UI Upload HtmlHelper.
Because the File Browser dialogs of the Telerik UI Editor for ASP.NET Core rely on the Upload
control, the issue might occur when uploading images and other files through them on MAC Safari.
Solution The solution solely depends on a dedicated decision by Apple about whether and when to
fix this browser issue. However, you can work around it by applying the suggestions provided in the
Programmatically enable or disable anonymous authentication in IIS StackOverflow thread. This means
to build a separate web service for file upload with an authentication setting, such as Anonymous for
Safari scenarios, and the main application authentication setting, such as Windows Authentication.
See Also
Basic Usage by the Upload HtmlHelper for ASP.NET Core (Demo)
Using the API of the Upload HtmlHelper for ASP.NET Core (Demo)
UploadBuilder Server-Side API
Upload Server-Side API
720
Telerik UI for ASP.NET Core
Upload Accessibility
The Upload is accessible by screen readers and provides WAI-ARIA, Section 508 and WCAG 2.1
support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Upload is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Upload supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Accessibility in Telerik UI for ASP.NET Core
721
Telerik UI for ASP.NET Core
public ActionResult Index()
{
return View();
}
@(Html.Kendo().ArcGauge()
.Name("arcGauge") // The name of the AcrGauge is mandatory. It specifies the
"id" attribute of the widget.
.Value(65)
.Scale(x => x.Min(0).Max(100))
.CenterTemplate("#:value#%")
)
// Place the following after your Telerik UI ArcGauge for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the ArcGauge is used to get its client-side instance.
var gauge = $("#arcGauge").data("kendoArcGauge");
});
</script>
See Also
722
Telerik UI for ASP.NET Core
723
Telerik UI for ASP.NET Core
@(Html.Kendo().LinearGauge()
.Name("linearGauge") // The name of the LinearGauge is mandatory. It specifies
the "id" attribute of the widget.
.Scale(scale => scale
.Min(0) // Set the min value of the LinearGauge.
.Max(200) // Set the min value of the LinearGauge.
)
.Pointer(pointer => pointer
.Value(10) // Set the value of the LinearGauge.
)
)
// Place the following after the LinearGauge for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the LinearGauge is used to get its client-side instance.
var gauge = $("#linearGauge").data("kendoLinearGauge");
});
</script>
See Also
Basic Usage of the LinearGauge HtmlHelper for ASP.NET Core (Demo)
Server-Side API
724
Telerik UI for ASP.NET Core
@(Html.Kendo().RadialGauge()
.Name("radialGauge") // The name of the RadialGauge is mandatory. It specifies
the "id" attribute of the widget.
.Scale(scale => scale
.Min(0) // Set the min value of the RadialGauge.
.Max(200) // Set the min value of the RadialGauge.
)
.Pointer(pointer => pointer
.Value(10) // Set the value of the RadialGauge.
)
)
// Place the following after the RadialGauge for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the RadialGauge is used to get its client-side instance.
var gauge = $("#radialGauge").data("kendoRadialGauge");
});
</script>
See Also
Basic Usage of the RadialGauge HtmlHelper for ASP.NET Core (Demo)
Server-Side API
725
Telerik UI for ASP.NET Core
The ProgressBar delivers rich functionality for displaying and tracking the progress of a task. It
supports multiple types, horizontal and vertical orientation, reversed direction, minimum and
maximum values, and animation duration.
@(Html.Kendo().ProgressBar()
.Name("progressbar")
.Type(ProgressBarType.Percent)
.Animation(a => a.Duration(600))
)
<script type="text-javascript">
$(document).ready(function () {
$("#progressbar").data("kendoProgressBar").value(50);
});
</script>
Basic Configuration
The following example demonstrates the basic configuration of the ProgressBar HtmlHelper.
@(Html.Kendo().ProgressBar()
.Name("progressBar")
.Type(ProgressBarType.Chunk)
.ChunkCount(4)
.Min(0)
.Max(4)
.Value(2)
.ShowStatus(true)
.Orientation(ProgressBarOrientation.Vertical)
.Events(e =>
{
e.Change("onChange");
e.Complete("onComplete");
})
.Animation(а =>
{
а.Duration(500);
})
)
726
Telerik UI for ASP.NET Core
Events
You can subscribe to all ProgressBar events. For a complete example on basic ProgressBar events,
refer to the demo on using the events of the ProgressBar.
@(Html.Kendo().ProgressBar()
.Name("progressBar")
.Events(e => {
e.Change("onChange");
e.Complete("onComplete");
})
)
<script>
function onChange(e) {
// Handle the change event.
}
function onComplete(e) {
// Handle the complete event.
}
</script>
@(Html.Kendo().ProgressBar()
.Name("progressBar")
.Events(e => e.Change(@<text>
function() {
// Handle the change event.
}
</text>)
)
)
@(Html.Kendo().ProgressBar()
.Name("progressBar")
)
<script type="text/javascript">
727
Telerik UI for ASP.NET Core
$(function () {
// The Name() of the ProgressBar is used to get its client-side instance.
var progressbar = $("#progressbar").data("kendoProgressBar");
console.log(progressbar);
});
</script>
See Also
Basic Usage of the ProgressBar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
728
Telerik UI for ASP.NET Core
The following example demonstrates a basic declaration of a Sortable widget using the Sortable
HtmlHelper. The widget is initialized for the sortable-basic element making its list items sortable.
<ul id="sortable-basic">
<li class="sortable">Papercut <span>3:04</span></li>
<li class="sortable">One Step Closer <span>2:35</span></li>
<li class="sortable">With You <span>3:23</span></li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable-basic") // The for option of the Sortable is mandatory.
// It is a jQuery selector which specifies
// the already existing element for which the Sortable will be initialized.
.HintHandler("hint") // The JavaScript function which
// constructs the hint element of the Sortable.
.PlaceholderHandler("placeholder") // The JavaScript function which
// constructs the placeholder element of the Sortable.
)
<script>
// Define the hint handler.
function hint(element) {
return element.clone().addClass("hint");
}
// Define the placeholder handler.
function placeholder(element) {
return element.clone().addClass("placeholder").text("drop here");
}
</script>
729
Telerik UI for ASP.NET Core
Events
You can subscribe to all Sortable events. For a complete example on basic Sortable events, refer to
the demo on using the events of the Sortable.
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Events(events => events
.Start("onStart")
.Change("onChange")
)
)
<script>
function onStart(e) {
var id = e.sender.element.attr("id");
kendoConsole.log(id + " start: " + e.item.text());
}
function onChange(e) {
var id = e.sender.element.attr("id"),
text = e.item.text(),
newIndex = e.newIndex,
oldIndex = e.oldIndex;
kendoConsole.log(id + " change: " + text + " newIndex: " + newIndex + "
oldIndex: " + oldIndex + " action: " + e.action);
}
</script>
<ul id="sortable">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Events(events => events
.Start(@<text>
function() {
// Handle the show event inline.
}
</text>)
.Change(@<text>
730
Telerik UI for ASP.NET Core
function() {
// Handle the show event inline.
}
</text>)
)
)
// Place the following after your Telerik UI Sortable for ASP.NET Core declaration.
<script>
$(function() {
// The For() of the Sortable is used to get its client-side instance.
var sortable = $("#container").data("kendoSortable");
});
</script>
See Also
Basic Usage of the Sortable HtmlHelper for ASP.NET Core (Demo)
Server-Side API
731
Telerik UI for ASP.NET Core
Hint
By default, the Sortable renders a hint.
To disable that behavior, set the hint to an empty function by using jQuery.noop.
@(Html.Kendo().Sortable()
.For("#sortable")
.HintHandler("noHint")
)
<script>
var noHint = $.noop;
</script>
See Also
Server-Side API
732
Telerik UI for ASP.NET Core
Items
The Sortable provides options for controlling the behavior of its items.
Disabling Items
To make items non-sortable, disable them by providing a selector that matches these items. As a
result, the user will not be able to drag the disabled non-sortable items, or to change their position.
However, they will still be valid sort targets.
@(Html.Kendo().Sortable()
.For("#sortable-basic")
.Disable(".disable")
)
Filtering Items
To prevent items both from being dragged and being sort targets, specify a filter.
@(Html.Kendo().Sortable()
.For("#sortable-basic")
.Filter(".sortable")
)
If the axis is set to "x" or "y", the Sortable will start operating in an axis movement mode and will
use only the x or y coordinate of the mouse cursor to determine the position of the placeholder. The
axis mode is useful when dragging is restricted in a container.
@(Html.Kendo().Sortable()
.For("#sortable-listA")
.ConnectWith("#sortable-listB")
.PlaceholderHandler("placeholder")
)
@(Html.Kendo().Sortable()
.For("#sortable-listB")
733
Telerik UI for ASP.NET Core
.ConnectWith("#sortable-listB")
.PlaceholderHandler("placeholder")
)
<script>
function placeholder(element) {
return $("<li class='list-item' id='placeholder'>Drop Here!</li>");
}
</script>
See Also
Disabling and Filtering Items in the Sortable HtmlHelper for ASP.NET Core (Demo)
Dragging Items within Containers by the Sortable HtmlHelper for ASP.NET Core (Demo)
Dragging Items between Lists in the Sortable HtmlHelper for ASP.NET Core (Demo)
Server-Side API
734
Telerik UI for ASP.NET Core
Cursor
The cursor configuration option determines the type of cursor that will be displayed while the user
is dragging a sortable item.
Avoid using a custom cursor in Internet Explorer. Due to the browser specifics in custom icon
rendering, using a custom cursor may lead to performance issues.
The following example demonstrates how to change the cursor type to "move".
<ul id="sortable">
<li>ItemA1</li>
<li>ItemA2</li>
<li>ItemA3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Cursor("move")
)
The cursor option changes the style of the cursor only for the time the item is dragged. To change
the cursor type on hover, use CSS.
<ul id="sortable">
<li>ItemA1</li>
<li>ItemA2</li>
<li>ItemA3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Cursor("url('https://demos.telerik.com/kendo-ui//content/web/sortable/grabbing.cur'),
default")
)
<style>
#sortable li {
cursor:
url('https://demos.telerik.com/kendo-ui//content/web/sortable/grabbing.cur'), default;
}
</style>
See Also
Basic Usage of the Sortable HtmlHelper for ASP.NET Core (Demo)
Server-Side API
735
Telerik UI for ASP.NET Core
Placeholder
You can change the default placeholder of the Sortable by setting the placeholder configuration
option.
The following example demonstrates how to build the placeholder from the dragged element.
<ul id="sortable">
<li>ItemA1</li>
<li>ItemA2</li>
<li>ItemA3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.PlaceholderHandler("placeholderCustom")
)
<script>
function placeholderCustom(element) {
return element.clone().css({
"opacity": 0.3,
"border": "1px dashed #000000"
});
}
</script>
<ul id="sortable">
<li>ItemA1</li>
<li>ItemA2</li>
<li>ItemA3</li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Placeholder("<li>Drop Here!</li>")
)
See Also
Basic Usage of the Sortable HtmlHelper for ASP.NET Core (Demo)
Server-Side API
736
Telerik UI for ASP.NET Core
Grid Integration
You can use the Telerik UI Sortable HtmlHelper for ASP.NET Coreto reorder the items in a Grid by
dragging and dropping.
Prerequisites
Overview of the Telerik UI Sortable HtmlHelper for ASP.NET Core
Overview of the Telerik UI Grid HtmlHelper for ASP.NET Core
DataSource client-side API
The following example demonstrates how to style the hint element so that the reordering takes
place immediately.
@(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName).Title("Product Name");
columns.Bound(p => p.UnitPrice).Title("Unit Price").Width(130);
columns.Bound(p => p.UnitsInStock).Title("Units In Stock").Width(130);
columns.Bound(p => p.Discontinued).Width(130);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(16)
.ServerOperation(false)
)
)
@(Html.Kendo().Sortable()
.For("#Grid")
737
Telerik UI for ASP.NET Core
.Filter("table > tbody > tr")
.Cursor("move")
.HintHandler("noHint")
.PlaceholderHandler("placeholder")
.ContainerSelector("#Grid tbody")
.Events(events => events.Change("onChange"))
)
<script>
var noHint = $.noop;
function placeholder(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
}
function onChange(e) {
var grid = $("#Grid").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 {
cursor: move;
}
</style>
If the Grid is configured to display details, use a selector that matches only the master Grid rows, for
example, filter: ">tbody >tr.k-master-row". In this way, the detail rows will not be
draggable.
For more information on the Sortable events, refer to the JavaScript API article on Sortable eventsand
the demo on integrating the Sortable and the Grid.
The editing functionality of the Telerik UI Grid for ASP.NET Core is rendered through its inline, popup,
and batchedit modes. The inline and popup modes are more common and easier to implement than
the batch edit mode.
738
Telerik UI for ASP.NET Core
.filter(">tbody >tr:not(.k-grid-edit-row)")
If you use the batch (incell) edit mode, the code from the previous example that is applied to the
inline and popup edit modes will not work. To work around this issue, use custom editorsand
configure them to update when the input event fires—by default, the framework listens for the
change event. To implement the solution, add the data-value-update="input" attribute to the
editor inputs. The downside of this approach is that the input event does not work for earlier
Internet Explorer versions.
The data-value-update approach works with regular inputs. However, you must manually
configure the Telerik UI HtmlHelpers for ASP.NET Core as they do not support the
data-value-update attribute.
The following example demonstrates how to shift the position of the items in the DataSource.
// The change event handler of the Sortable.
function onChange(e) {
var grid = e.sender.element.data("kendoGrid"),
oldIndex = e.oldIndex , // The old position.
newIndex = e.newIndex , // The new position.
view = grid.dataSource.view(),
dataItem = grid.dataSource.getByUid(e.item.data("uid")); // Retrieve the moved
dataItem.
dataItem.Order = newIndex; // Update the order.
dataItem.dirty = true;
// Shift the order of the records.
if (oldIndex < newIndex) {
for (var i = oldIndex + 1; i <= newIndex; i++) {
view[i].Order--;
view[i].dirty = true;
}
} else {
for (var i = oldIndex - 1; i >= newIndex; i--) {
view[i].Order++;
view[i].dirty = true;
}
}
739
Telerik UI for ASP.NET Core
grid.dataSource.sync(); // Submit the changes through the update transport and
refresh the Grid.
}
The following example demonstrates how to send the newIndex and oldIndex to the server.
// The change event handler of the Sortable.
function onChange(e) {
var grid = e.sender.element.data("kendoGrid"),
oldIndex = e.oldIndex , // The old position.
newIndex = e.newIndex , // The new position.
dataItem = grid.dataSource.getByUid(e.item.data("uid")); // Retrieve the moved
dataItem.
$.ajax({
url: "yourUrl",
dataType: "json",
data: { // Send the data and update the order of the items on the server.
oldIndex: oldIndex,
newIndex: newIndex,
dataItem: dataItem
},
success: function (response) {
grid.dataSource.read(); //refresh the Grid
}
});
}
Known Limitations
The Sortable does not work as expected with a Grid that has its paging or virtual scrolling
enabled.
The Sortable operates with the existing DOM. It is not aware of the Grid or of its DataSource.
If paging or virtual scrolling are enabled, the Grid will render only the elements which belong
to the current page. As a result, the sorting will be limited to the current page only.
The Sortable uses the index of the DOM elements. When the Grid displays grouped data, the
index of the DOM element does not match the index of the corresponding data item in the
DataSource. This makes updating the order in the DataSource impossible.
The Sortable does not work with a Grid that has locked (frozen) columns.
See Also
Server-side API
740
Telerik UI for ASP.NET Core
ListView Integration
You can use the Telerik UI Sortable HtmlHelper for ASP.NET Coreto reorder the items in a ListView by
dragging and dropping.
Prerequisites
Overview of the Telerik UI Sortable HtmlHelper for ASP.NET Core
Overview of the Telerik UI ListView HtmlHelper for ASP.NET Core
To reorder the data items of the ListView, use the approach for reordering the Grid data items. For
more information on the Sortable events, refer to the Sortable server-side API.
See Also
Reordering of Grid and DataSource Data Items
Server-side API
741
Telerik UI for ASP.NET Core
TabStrip Integration
You can use the Telerik UI Sortable HtmlHelper for ASP.NET Coreto reorder the items in the tabs of a
TabStrip.
Prerequisites
Overview of the Telerik UI Sortable HtmlHelper for ASP.NET Core
Overview of the Telerik UI TabStrip HtmlHelper for ASP.NET Core
@(Html.Kendo().Sortable()
.For("#tabstrip")
.Filter("li.k-item")
.ContainerSelector("ul.k-tabstrip-items")
.HintHandler("hintHandler")
.Events(ev=>ev.Start("onStart").Change("onChange"))
)
<script>
function hintHandler(element) {
return $("<div id='hint' class='k-widget k-header k-tabstrip'><ul
class='k-tabstrip-items k-reset'><li class='k-item k-state-active k-tab-on-top'>" +
element.html() + "</li></ul></div>");
}
function onStart(e) {
$("#tabstrip").data("kendoTabStrip").activateTab(e.item);
}
function onChange(e) {
var tabstrip = $("#tabstrip").data("kendoTabStrip"),
reference = tabstrip.tabGroup.children().eq(e.newIndex);
if(e.oldIndex < e.newIndex) {
tabstrip.insertAfter(e.item, reference);
} else {
tabstrip.insertBefore(e.item, reference);
}
}
</script>
742
Telerik UI for ASP.NET Core
To avoid visual glitches, activate the current tab at the start event handler of the Sortable.
function onStart(e) {
$("#tabstrip").data("kendoTabStrip").activateTab(e.item);
}
function onChange(e) {
var tabstrip = $("#tabstrip").data("kendoTabStrip"),
reference = tabstrip.tabGroup.children().eq(e.newIndex);
if(e.oldIndex < e.newIndex) {
tabstrip.insertAfter(e.item, reference);
} else {
tabstrip.insertBefore(e.item, reference);
}
}
See Also
Server-side API
743
Telerik UI for ASP.NET Core
Common Scenarios
This article provides common scenarios you might encounter when working with the Telerik UI
Sortable HtmlHelper for ASP.NET Core.
The following example demonstrates how to persist the order of the current items in local storage.
<div id="sortable"></div>
<button id="reset">Reset</button>
<script id="tmp" type="text/x-kendo-template">
<div class="sortable">Item #:data#</div>
</script>
<script>
var initialData = [1, 2, 3, 4, 5, 6, 7], //initial items order (used if there is
no saved data
localStorageSupport = (('localStorage' in window && window['localStorage'] !==
null)),
data,
html;
if (localStorageSupport) {
// Retrieve local storage data if such is available. Otherwise, use the default
order.
data = JSON.parse(localStorage.getItem("sortableData")) || initialData;
} else {
alert("your browser does not support local storage");
data = initialData;
}
html = kendo.render(kendo.template($("#tmp").html()), data); // Render the HTML
with the data.
$("#sortable").html(html); //append the HTML to the Sortable container
function onChange(e) {
var item = data.splice(e.oldIndex, 1)[0]; // Remove the item that has changed
its order.
data.splice(e.newIndex, 0, item); // Add the item back using the newIndex.
localStorage.setItem("sortableData", kendo.stringify(data)); // Set the updated
data in the local storage.
744
Telerik UI for ASP.NET Core
}
$("#reset").click(function () {
localStorage.clear(); // Clear the local storage.
alert("Local storage is cleared. Please reload the page!");
});
</script>
@(Html.Kendo().Sortable()
.For("#sortable")
.Filter(".sortable")
.Events(ev => ev.Change("onChange"))
)
<style>
#sortable {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
width: 300px;
}
.sortable {
padding: 10px 0;
margin: 1px 0;
width: 358px;
text-align: center;
color: #ffffff;
background-color: #51A0ED;
}
</style>
<ul id="sortable">
<li>ItemA1 <input type="text" /></li>
<li>ItemA2 <input type="text" /></li>
<li>ItemA3 <input type="text" /></li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable")
.Ignore("input")
)
745
Telerik UI for ASP.NET Core
<ul id="sortable-basic">
<li class="sortable"><input type="radio" name="foo" />Papercut
<span>3:04</span></li>
<li class="sortable"><input type="radio" name="foo" />One Step Closer
<span>2:35</span></li>
<li class="sortable"><input type="radio" name="foo" />With You
<span>3:23</span></li>
<li class="sortable"><input type="radio" name="foo" />Points of Authority
<span>3:20</span></li>
<li class="sortable"><input type="radio" name="foo" />Crawling
<span>3:29</span></li>
</ul>
@(Html.Kendo().Sortable()
.For("#sortable-basic")
.HintHandler("hintCustom")
.PlaceholderHandler("placeholderCustom")
)
<script>
function hintCustom(element) {
var hint = element.clone().addClass("hint");
// Alternatively, remove the input from the hint.
hint.find("input").attr("name", "");
return hint;
}
function placeholderCustom(element) {
return element.clone().addClass("placeholder").text("drop here");
}
</script>
See Also
Basic Usage of the Sortable HtmlHelper for ASP.NET Core (Demo)
Server-Side API
746
Telerik UI for ASP.NET Core
Badge Overview
The Badge is an absolutely positioned element that is used to decorate avatars, navigation menus,
or other components in the application when the visual notification is needed.
It also provides customizing its content through templates, setting different types and layouts.
<a class="k-button">
@(Html.Kendo().Badge()
.Name("badge")
.Value("42")
.Appearance("rectangle"))
</a>
Basic Configuration
The badge also provides the choice to be inline or overlay and set its type. To make the badge
overlay add the k-badge-overlay class to the parent parent element.
<a class="k-button k-badge-overlay">
@(Html.Kendo().Badge()
.Name("badge")
.Value("42")
.Type("warning")
.Appearance("rectangle"))
</a>
Using templates
With the badge you can customize the content using templates.
<a class="k-button k-badge-overlay">
@(Html.Kendo().Badge()
.Name("badge")
.Value("42")
.Template("#= +value > 10 ? '9+' : value #")
.Appearance("rectangle"))
</a>
747
Telerik UI for ASP.NET Core
<a class="k-button k-badge-overlay">
@(Html.Kendo().Badge()
.Name("badge")
.Value("42")
.Template("#= +value > 10 ? '9+' : value #")
.Appearance("rectangle"))
</a>
<script>
var badge = $('#badge').data('kendoBadge');
</script>
See Also
Basic Usage of the Badge HtmlHelper for ASP.NET Core (Demo)
Server-Side API
748
Telerik UI for ASP.NET Core
The Dialog is a modal popup that brings information to the user. It also provides actions through its
action buttons to prompt the user for input or to ask for a decision. The component can also contain
more complex UI elements that require the focus of the user. The Dialog is a subset of the Kendo UI
for jQuery Windowwhere the most prominent difference is the added functionality for actions and
predefined dialogs.
The following example demonstrates how to define the Dialog by using the Dialog HtmlHelper.
@(Html.Kendo().Dialog()
.Name("dialog") // The name of the Dialog is mandatory. It specifies the "id"
attribute of the widget.
.Title("Software Update")// Set the title of the Dialog.
.Content("Do you agree terms and conditions?") // Define the content of the
Dialog.
.Visible(false) // The widget will be initialized as invisible.
)
Basic Configuration
The Dialog provides default configuration options that can be set during initialization such as its
height and width, custom action buttons, title and Close buttons, animation effects and duration, and
so on.
@(Html.Kendo().Dialog()
.Name("dialog")
.Title("Software Update")
.Content("Do you agree terms and conditions?")
.Width(400) // Set the width of the Dialog.
.Modal(false) // Disable the modality of the Dialog.
.ButtonLayout("stretched") // Set a "stretched" layout for the action buttons.
.Actions(actions =>
{
actions.Add().Text("NO"); // Set text of the first button.
actions.Add().Text("YES").Primary(true); // Set text of the second button and
define it as primary.
749
Telerik UI for ASP.NET Core
})
)
<script type="text/javascript">
$(function() {
// The Name() of the Dialog is used to get its client-side instance.
var dialog = $("#dialog").data("kendoDialog");
});
</script>
Events
You can subscribe to all Dialog events. For a complete example on basic Dialog events, refer to the
demo on using the events of the Dialog.
@(Html.Kendo().Dialog()
.Name("dialog")
.Events(e => e
.InitOpen("onInitOpen")
.Open("dialog_open")
.Close("dialog_close")
.Show("onShow")
.Hide("onHide")
)
)
<script>
function onInitOpen(e) {
// Handle the InitOpen event.
}
function onOpen(e) {
// Handle the open event.
}
function onClose(e) {
// Handle the close event.
}
function onShow(e) {
// Handle the show event.
}
function onHide(e) {
// Handle the hide event.
}
</script>
750
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Dialog HtmlHelper for ASP.NET Core (Demo)
Using the API of the Dialog HtmlHelper for ASP.NET Core (Demo)
Server-Side API
751
Telerik UI for ASP.NET Core
The following example demonstrates the possible markup and a possible placement of the Dialog
HTML helper.
<body>
<div id="container1">
@(Html.Kendo().Dialog()
.Name("dialog")
.Content("Content of the Dialog")
)
...
</div>
<div id="container2">
...
</div>
</body>
The following example demonstrates how the markup of the page from the previous example
changes after the initialization of the Dialog when the widget is moved to become a child of the
<body> and its additional markup (the wrapper and the title bar) is generated.
<body>
<div id="container1">
...
</div>
<div id="container2">
...
</div>
<div class="k-widget k-dialog k-window">
<div class="k-window-titlebar">...</div>
<div id="dialog" class="k-content">
Content of the Dialog
</div>
</div>
</body>
See Also
Server-Side API
752
Telerik UI for ASP.NET Core
Action Buttons
The Dialog action buttons allow you to provide specific interaction to users.
Each button has a text and an action handler attached to it. Generally, each button closes the Dialog
as its last action but you can cancel this from the custom action handler. The order of the values in
the Actions() configuration method determines the order in which the action buttons are rendered
in the Dialog. You can also define a button as Primary(true).
The following example demonstrates how to set three action buttons in a Dialog with a stretched
layout. The last button has an Action() event handler attached and is set as Primary(true).
@(Html.Kendo().Dialog()
.Name("dialog")
.Title("Software Update")
.Content("<p>A new version of <strong>Kendo UI</strong> is available. Would you
like to download and install it now?<p>")
.Width(400)
.Modal(false)
.ButtonLayout("stretched")
.Actions(actions =>
{
actions.Add().Text("Skip this version");
actions.Add().Text("Remind me later");
actions.Add().Text("Install update").Primary(true).Action("onInstall");
})
)
<script type="text/javascript">
function onInstall(e) {
alert("Install update action was clicked");
// Returning false will prevent the closing of the dialog.
return true;
}
</script>
See Also
Server-Side API
753
Telerik UI for ASP.NET Core
Dimensions
By default, the Dialog does not have any preset height and width and its size depends on its content.
If the Dialog contains horizontally expandable block-level elements—including Kendo UI for jQuery
widgets such as the Grid, Editor, and others—the widget can expand horizontally to the point of
touching the right edge of the browser viewport. In such cases, the widget sticks to the right
viewport edge and cannot be separated from it. This issue occurs because the Dialog is absolutely
positioned with CSS. To avoid such behavior, set an appropriate width to the widget, or a
(max-)width to its content.
The lack of restrictions over the dimensions for vertical expanding of the Dialog and its content
might result in undesired behavior—for example, the rendition of a popup which is higher than the
browser viewport.
See Also
Server-Side API
754
Telerik UI for ASP.NET Core
Dialog Accessibility
The Dialog is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Dialog is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The Dialog supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Dialog HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Dialog HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
755
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Dialog is always available.
For a complete example, refer to the demo on keyboard navigation of the Dialog.
See Also
Keyboard Navigation in the Dialog HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Dialog HtmlHelper for ASP.NET Core
756
Telerik UI for ASP.NET Core
The Notification provides a styled UI widget with arbitrary content which can provide information to
the user on various occasions.
@(Html.Kendo().Notification()
.Name("notification")
)
<script type="text/javascript">
$(document).ready(function () {
var popupNotification = $("#notification").data("kendoNotification");
popupNotification.show("Test popup message", "info");
});
</script>
Basic Configuration
The following example demonstrates the basic configuration of the Notification HtmlHelper.
@(Html.Kendo().Notification()
.Name("notification")
.Stacking(NotificationStackingSettings.Down)
.Width("12em")
.Height(200)
.HideOnClick(false)
.Events(ev => ev.Show("onShow").Hide("onHide"))
.Templates(t =>
{
t.Add().Type("time").ClientTemplate("<div style='padding: .6em 1em'>Time is: #:
time #</div>");
})
.Button(true)
)
<script type="text/javascript">
$(function () {
// The Name() of the Notification is used to get its client-side instance.
var notification = $("#notification").data("kendoNotification");
console.log(notification);
});
757
Telerik UI for ASP.NET Core
</script>
Events
For a complete example on basic Notification events, refer to the demo on using the events of the
Notification.
See Also
Basic Usage of the Notification HtmlHelper for ASP.NET Core (Demo)
Using the API of the Notification HtmlHelper for ASP.NET Core (Demo)
Server-Side API
758
Telerik UI for ASP.NET Core
Types
The Notification provides the built-in "info", "success", "warning", and "error" Notification
types.
You can use different templates and looks for each type. The built-in Notification types provide
ready-to-use shorthand methods for display as well as built-in templates and styling. The names of
the shorthand methods match the listed Notification types.
If no type is specified when a Notification is displayed, the "info" type is displayed. You can define
an unlimited amount of custom notification types and corresponding templates.
The following example demonstrates the built-in Notification types.
@(Html.Kendo().Notification()
.Name("notification")
)
<script>
$(function(){
var notificationWidget = $("#notification").data("kendoNotification");
// Display a "foo" warning message.
notificationWidget.show("foo", "warning");
// The above line is equivalent to the following:
notificationWidget.warning("foo");
// Display a "bar" info message.
notificationWidget.show("bar", "info");
// The above line is equivalent to the following:
notificationWidget.show("bar");
// and also to the following:
notificationWidget.info("bar");
});
</script>
See Also
NotificationBuilder Server-Side API
Notification Server-Side API
759
Telerik UI for ASP.NET Core
Hiding
By default, the Notification remains visible for five seconds and then disappears.
A 0 (zero) value disables the automatic hiding of the Notification. The delay of the Notification hiding
can be configured in milliseconds.
Clicking anywhere on the Notification immediately hides it. If this behavior is not intuitive enough for
the user, you can implement a visible Close button.
You can also disable the automatic hiding of the Notification that is triggered by the user clicking
anywhere on it. In this case, the Notification can be dismissed only with a button for closing or hiding
(if implemented).
In addition, you can postpone the manual hiding of the Notification which prevents the accidental
hiding of notifications which have just appeared. By default, the manual delay of the Notification is
disabled.
The following example demonstrates how to manage the hiding of the Notification.
@(Html.Kendo().Notification()
.Name("notification")
// Hide automatically after seven seconds.
.AutoHideAfter(7000)
// Prevent accidental hiding for one second.
.AllowHideAfter(1000)
// Show a Hide button.
.Button(true)
// Prevent hiding by clicking on the Notification content.
.HideOnClick(false)
)
See Also
NotificationBuilder Server-Side API
Notification Server-Side API
760
Telerik UI for ASP.NET Core
If no position settings are defined, the first popup will be displayed near the bottom-right corner of
the browser viewport and subsequent popups will stack upwards.
You can independently control the positioning and stacking of the Notifications. If you do not define
any stacking setting, the popups stack upwards or downwards depending on the positioning
settings. For example, popups which display at the top of the viewport stack downwards and vice
versa. Explicitly defining stacking is mostly needed when you need a more specific stacking
direction, for example, leftwards or rightwards.
By default, popups are pinned, that is, when the page is scrolled, popups do not move. This behavior
is achieved by applying a position:fixed style to the popups. When the popups are not pinned,
they use position:absolute.
If the popup content varies and stacking is likely to occur, explicitly define dimensions so that the
popups are aligned and look better when stacked next to one another.
The following example demonstrates how to manage the position, stacking, and size of the
Notification.
@(Html.Kendo().Notification()
.Name("notification")
.Position(p =>
{
// The Notification popup will scroll together with the other content.
p.Pinned(false);
// The first Notification popup will appear 30px from the top and right edge of
the viewport.
p.Top(30);
p.Right(30);
})
// New notifications will appear under old ones.
.Stacking(NotificationStackingSettings.Down)
// Set the appropriate size.
.Width(300)
.Height(50)
)
You may need the popup notifications to appear too quickly or to implement so many Notifications
on the screen that the available space gets very little. In such cases, the subsequent popups appear
outside the visible viewport area and are inaccessible if they are pinned. In such cases, consider
using a shorter hiding delay or implementing static notifications for better usability.
Notifications can also display static messages which do not overlay other elements but take part in
the normal flow of the page content instead. In this case, the positioning settings are ignored.
Stacking can be downwards (by default) or upwards. Static notifications are displayed if you specify
a target container. A single Notification instance can display either popup or static notifications but
761
Telerik UI for ASP.NET Core
@(Html.Kendo().Notification()
.Name("notification")
// Insert all notifications to the originating element of the Notification.
.AppendTo("#notification")
// New notifications will appear over old ones.
.Stacking(NotificationStackingSettings.Up)
)
See Also
Positioning and Stacking by the Notification HtmlHelper for ASP.NET Core (Demo)
NotificationBuilder Server-Side API
Notification Server-Side API
762
Telerik UI for ASP.NET Core
Templates
Notifications enable you to configure multiple templates.
Each template is used together with its corresponding built-in or custom notification type. If you
define a custom template for a built-in notification type, you will not be able to use the corresponding
built-in template but you can still use the shorthand show methods.
<script id="myAlertTemplate" type="text/x-kendo-template">
<div class="myAlert">System alert generated at #= time # : #= myMessage #</div>
</script>
@(Html.Kendo().Notification()
.Name("notification")
.Templates(t =>
{
// Define a custom template for the built-in "warning" Notification type.
t.Add().Type("warning").ClientTemplate("<div class='myWarning'>Warning: #=
myMessage #</div>");
// Define a template for the custom "timeAlert" Notification type.
t.Add().Type("timeAlert").ClientTemplate("<div class='myAlert'>System alert
generated at #= time # : #= myMessage #</div>");
// The template content can also be defined separately. The above line can be
replaced with the following:
t.Add().Type("timeAlert").ClientTemplateID("myAlertTemplate");
})
)
<script>
$(function(){
var n = $("#notification").data("kendoNotification");
// Show a warning message by using the built-in shorthand method.
n.warning({
myMessage: "some warning message here"
});
// Show a "timeAlert" message by using the default show() method.
n.show({
time: new Date().toLocaleTimeString(),
myMessage: "Server will be restarted."
}, "timeAlert");
});
</script>
See Also
Using Templates in the Notification HtmlHelper for ASP.NET Core (Demo)
NotificationBuilder Server-Side API
Notification Server-Side API
763
Telerik UI for ASP.NET Core
The Splitter provides a dynamic layout of resizable and collapsible panes. It converts the children of
an HTML element into an interactive layout by adding resize and collapse handles depending on its
configuration. The vertical and horizontal orientation of the Splitter can be combined to build
complex layouts.
@(Html.Kendo().Splitter()
.Name("splitter")
.Orientation(SplitterOrientation.Vertical)
.Panes(verticalPanes =>
{
verticalPanes.Add()
.Content(
Html.Kendo().Splitter()
.Name("horizontal")
.Panes(horizontalPanes =>
{
horizontalPanes.Add()
.HtmlAttributes(new { id = "left-pane" })
.Size("220px")
.Content(@<div class="pane-content">
<h3>Inner splitter / left pane</h3>
</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "center-pane" })
.Content(@<div class="pane-content">
<h3>Inner splitter / center pane</h3>
</div>);
horizontalPanes.Add()
.HtmlAttributes(new { id = "right-pane" })
.Collapsible(true)
.Size("220px")
.Content(@<div class="pane-content">
<h3>Inner splitter / right pane</h3>
</div>);
}).ToHtmlString()
);
verticalPanes.Add()
.Size("100px")
.Collapsible(false)
.Content(@<div class="pane-content">
<h3>Outer splitter / middle pane</h3>
764
Telerik UI for ASP.NET Core
</div>);
verticalPanes.Add()
.Size("100px")
.Content(@<div class="pane-content">
<h3>Outer splitter / bottom pane</h3>
</div>);
})
)
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration of the Splitter HtmlHelper.
@(Html.Kendo().Splitter()
.Name("splitter")
.HtmlAttributes(new { style = "height: 400px;" })
.Orientation(SplitterOrientation.Vertical)
.Events(events => events
.Collapse("collapse")
.Resize("resize")
.Expand("expand")
.ContentLoad("contentLoad")
)
.Panes(panes =>
{
panes.Add()
.HtmlAttributes(new { id = "top_pane" })
.Size("100px")
.Collapsible(true)
.Scrollable(false)
.Content(@<p>
Top pane
</p>);
panes.Add()
.HtmlAttributes(new { id = "middle_pane" })
.Content(@<div class="pane-content">
<h3>Middle pane</h3>
</div>);
panes.Add()
.HtmlAttributes(new { id = "bottom_pane" })
.Collapsible(true)
.Scrollable(true)
.Size("20%")
.Content(@<p>
Bottom pane
</p>);
})
765
Telerik UI for ASP.NET Core
)
<script type="text/javascript">
$(function () {
// The Name() of the Splitter is used to get its client-side instance.
var splitter = $("#splitter").data("kendoSplitter");
console.log(splitter);
});
</script>
Events
For a complete example on basic Splitter events, refer to the demo on using the events of the Splitter.
See Also
Basic Usage of the Splitter HtmlHelper for ASP.NET Core (Demo)
Using the API of the Splitter HtmlHelper for ASP.NET Core (Demo)
Server-Side API
766
Telerik UI for ASP.NET Core
Auto-Resizing to Window
You can add a Splitter that resizes automatically along with the Kendo UI for jQuery Window widget.
@(Html.Kendo().Window()
.Name("win")
.Title("Kendo UI Window")
.Modal(true)
.Width(400)
.Height(250)
.Draggable(true)
)
<script id="template" type="text/x-kendo-template">
@(Html.Kendo().Splitter()
.Name("vertical")
.Orientation(SplitterOrientation.Horizontal)
.Panes(verticalPane =>
{
verticalPane.Add().Collapsible(true).Content("left pane <br /><br /> Please
resize the Window and watch the Splitter resize automatically.");
verticalPane.Add().Collapsible(true).Content("right pane");
})
.ToClientTemplate()
)
</script>
<script>
$(function () {
var template = kendo.template($("#template").html());
$("#win").append(template({}));
$("#win").data("kendoWindow").center();
})
</script>
<style>
html {
font: 12px sans-serif;
}
#splitter {
border-width: 0;
height: 100%;
}
#win {
padding: 0;
overflow: hidden;
}
</style>
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
767
Telerik UI for ASP.NET Core
}
}
See Also
Server-Side API
768
Telerik UI for ASP.NET Core
Auto-Resizing to Content
You can expand the height of the Splitter based on the content inside a pane.
1. Set up the Splitter to expand to the height of its parent according to the article on how to
expand to 100% height and auto-resize.
2. Make sure that the parent content is resized when the content of the pane is rendered.
3. Call the resize method to finalize the process.
@(Html.Kendo().Splitter()
.Name("vertical")
.Orientation(SplitterOrientation.Horizontal)
.Panes(verticalPane =>
{
verticalPane.Add().Collapsible(true).Content("<div id='grid'></div>");
verticalPane.Add().Collapsible(true);
})
)
@(Html.Kendo().Grid<CoreDocumentationSplitter.Models.Products>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.ProductName);
})
.DataSource(dataSource => dataSource
.Custom()
.Batch(true)
.Schema(schema => schema.Model(m => m.Id(p => p.ProductID)))
.Transport(transport =>
{
transport.Read(read =>
read.Url("https://demos.telerik.com/kendo-ui/service/products")
.DataType("jsonp")
);
})
)
.Events(e => { e.DataBound("onDataBound"); })
)
<script>
function onDataBound(e) {
var gridHeight = e.sender.wrapper.outerHeight() +
e.sender.wrapper.outerHeight() - e.sender.wrapper.height();
$(document).find("body").height(gridHeight);
var splitter = $("#vertical").data("kendoSplitter");
splitter.resize(true);
}
</script>
<style>
html,
body,
main,
#vertical,
.container
{
769
Telerik UI for ASP.NET Core
height: 100%;
margin: 0;
padding: 0;
}
</style>
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
}
}
public class Products
{
public string ProductID { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
}
See Also
Server-Side API
770
Telerik UI for ASP.NET Core
Web standards require that elements with percentage height have a parent element with an explicit
height. The rule applies recursively until an element with a pixel height is reached, or until the
<html> element is reached. If the requirement is not met, the computed height of the Splitter falls
back to auto and the widget collapses, depending on its content.
You also have to remove the border of the Splitter. Elements that are 100% high cannot have
borders, margins, paddings, and sibling elements. In a nested-Splitter scenario, if each Splitter is a
direct child of a parent pane, the inner Splitters remove their borders automatically.
@(Html.Kendo().Splitter()
.Name("splitter")
.Orientation(SplitterOrientation.Vertical)
.Panes(verticalPane => {
verticalPane.Add().Collapsible(true).Size("60px").Content("Outer splitter : top
pane (resizable and collapsible)");
verticalPane.Add().Collapsible(false)
.Content(Html.Kendo().Splitter()
.Name("horizontal")
.Orientation(SplitterOrientation.Horizontal)
.Panes(horizontalPanes => {
horizontalPanes.Add().Collapsible(true).Size("100px").Content("Inner splitter
:: left pane");
horizontalPanes.Add().Collapsible(false).Content("Inner splitter :: center
pane"); ;
horizontalPanes.Add().Collapsible(false).Resizable(true).Size("15%").Content("Inner
splitter :: right pane");
}).ToHtmlString()
);
verticalPane.Add().Collapsible(false).Resizable(false).Size("15%").Content("Outer
splitter : bottom pane (non-resizable, non-collapsible)");
})
)
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
771
Telerik UI for ASP.NET Core
#vertical,
#horizontal {
height: 100%;
}
#vertical {
border-width: 0;
}
</style>
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
}
}
<div id="header">Page header</div>
@(Html.Kendo().Splitter()
.Name("vertical")
.Orientation(SplitterOrientation.Vertical)
.Panes(verticalPane =>
{
verticalPane.Add().Collapsible(true).Size("60px").Content("Outer splitter : top
pane (resizable and collapsible)");
verticalPane.Add().Collapsible(false)
.Content(Html.Kendo().Splitter()
.Name("horizontal")
.Orientation(SplitterOrientation.Horizontal)
.Panes(horizontalPanes =>
{
horizontalPanes.Add().Collapsible(true).Size("100px").Content("Inner splitter
:: left pane");
horizontalPanes.Add().Collapsible(false).Content("Inner splitter :: center
pane"); ;
horizontalPanes.Add().Collapsible(false).Resizable(true).Size("15%").Content("Inner
splitter :: right pane");
}).ToHtmlString()
);
verticalPane.Add().Collapsible(false).Resizable(false).Size("15%").Content("Outer
splitter : bottom pane (non-resizable, non-collapsible)");
})
)
<div id="footer">Page footer</div>
<script>
$(document).ready(function () {
772
Telerik UI for ASP.NET Core
var outerSplitter = $("#vertical").data("kendoSplitter");
var browserWindow = $(window);
var headerFooterHeight = $("#header").height() + $("#footer").height();
function resizeSplitter() {
outerSplitter.wrapper.height(browserWindow.height() - headerFooterHeight);
outerSplitter.resize();
}
resizeSplitter();
browserWindow.resize(resizeSplitter);
})
</script>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#horizontal {
height: 100%;
}
#vertical {
border-width: 0;
}
#header,
#footer {
height: 50px;
background: #fed;
}
</style>
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
}
}
See Also
Server-Side API
773
Telerik UI for ASP.NET Core
@(Html.Kendo().Splitter()
.Name("splitter")
.Panes(panes=> {
panes.Add().Collapsible(true).Size("20%");
panes.Add().Collapsible(false);
})
.Events(e => { e.Resize("onResize"); })
)
<script>
function onResize(e) {
console.log(e.sender.options.panes);
// Prevent endless recursion from resizes.
if (!this.appliesSizes) {
this.appliesSizes = true;
// Calculate the pane width.
var element = this.element;
var pane = element.find(".k-pane:first");
var ratio = Math.ceil(pane.width() * 100 / element.width());
// set pane width in percentages
this.size(pane, ratio + "%");
this.appliesSizes = false;
}
}
</script>
public class SplitterController : Controller
{
public IActionResult Index()
{
return View();
}
}
See Also
Server-Side API
774
Telerik UI for ASP.NET Core
The Tooltip displays a popup hint for a specific HTML element. Its content can be defined either as
static text or loaded dynamically with AJAX.
<span id="tooltip" class="k-button wider">Hover me!</span>
@(Html.Kendo().Tooltip()
.For("#tooltip")
.Position(TooltipPosition.Top)
.Content("Hello!")
)
Basic Configuration
The following example demonstrates the basic configuration of the Tooltip HtmlHelper.
<span id="tooltip" class="k-button wider">
<а href="#">Hover me</a>
</span>
@(Html.Kendo().Tooltip()
.For("#tooltip")
.Position(TooltipPosition.Top)
.Content("Hello!")
.Width(120)
.AutoHide(false)
.Filter("a")
.Events(events => events.Hide("onHide").Show("onShow"))
)
Events
775
Telerik UI for ASP.NET Core
For a complete example on basic Tooltip events, refer to the demo on using the events of the Tooltip.
// Place the following after your Telerik UI Tooltip for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The For() configuration option of the Tooltip is used to get its client-side
instance.
var tooltip = $("#tooltip").data("kendoTooltip");
});
</script>
See Also
Basic Usage of the Tooltip HtmlHelper for ASP.NET Core (Demo)
Using the API of the Tooltip HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
776
Telerik UI for ASP.NET Core
Content
The Tooltip provides options for loading and configuring its content.
<span id="tooltip" class="k-button wider">Hover me!</span>
@(Html.Kendo().Tooltip()
.For("#tooltip")
.Position(TooltipPosition.Top)
.Content("Hello!")
)
For more information on the capabilities and syntax of the templates, refer to the Kendo UI Templates
Overview documentation article. For a runnable example, refer to the Templates demo.
The following example demonstrates how to customize the Tooltip by referencing a script tag by its
id.
<ul id="products">
<li>
<a href="#" data-id="11" title="A cheese made in the artisan tradition by rural
dairy farmers in the north of Spain">
Queso de Cabrales
</a>
</li>
<li>
<a href="#" data-id="12" title="A cheese made in the La Mancha region of Spain
from the milk of sheep of the Manchega breed">
Queso<br />Manchego
</a>
</li>
</ul>
@(Html.Kendo().Tooltip()
.For("#products")
.Filter("a")
.ContentTemplateId("template")
.Position(TooltipPosition.Top)
)
<script id="template" type="text/x-kendo-template">
<div class="template-wrapper">
777
Telerik UI for ASP.NET Core
<p>#=target.data('id')#</p>
<p>#=target.data('title')#</p>
</div>
</script>
The following example demonstrates how to load the content asynchronously with AJAX by using
the LoadContentFrom configuration method.
@(Html.Kendo().Tooltip()
.For("#products")
.Filter("a")
.LoadContentFrom("Details", "Tooltip")
.Position(TooltipPosition.Top)
.Width(220)
.Height(280)
.Events(events => events.RequestStart("requestStart"))
)
<script type="text/javascript">
function requestStart(e) {
e.options.data = {
id: e.target.data("id")
}
}
</script>
For a complete example, refer to the Loading Content with AJAX Demo.
See Also
Content Template in the Tooltip HtmlHelper for ASP.NET Core (Demo)
Loading Content with AJAX in the Tooltip HtmlHelper for ASP.NET Core (Demo)
778
Telerik UI for ASP.NET Core
The Window displays content in a modal or non-modal HTML window. By default, the user can move,
resize, and close a Window. Its content can also be defined either as static HTML or dynamically
loaded with AJAX.
@(Html.Kendo().Window()
.Name("window")
.Title("Window title")
.Content(@<text>
Static content of the Window.
</text>)
)
public class WindowController : Controller
{
public IActionResult Index()
{
return View();
}
}
Basic Configuration
The Window provides default configuration options that can be set during initialization such as
height and width, user actions, draggable behavior, initial position, and so on.
The following example demonstrates the basic configuration of the Window HtmlHelper.
@(Html.Kendo().Window()
.Name("window")
.Width(500)
.Height(300)
.Title("Window title")
.Visible(true)
.Actions(actions => actions.Refresh().Minimize().Maximize().Close())
.LoadContentFrom("AjaxContent", "Window")
.Draggable(false)
.Resizable(false)
)
779
Telerik UI for ASP.NET Core
<script type="text/javascript">
$(function() {
// The Name() of the Window is used to get its client-side instance.
var dialog = $("#window").data("kendoWindow");
});
</script>
Events
You can subscribe to all Window events. For a complete example on basic Window events, refer to
the demo on using the events of the Window.
@(Html.Kendo().Window()
.Name("window")
.Events(e => e
.Open("window_open")
.Close("window_close")
)
)
<script>
function window_open() {
// Handle the open event.
}
function window_close() {
// Handle the close event.
}
</script>
@(Html.Kendo().Window()
.Name("window")
.Events(e => e
.Open(@<text>
780
Telerik UI for ASP.NET Core
function() {
// Handle the open event inline.
}
</text>)
.Close(@<text>
function() {
// Handle the close event inline.
}
</text>)
)
)
See Also
Basic Usage of the Window HtmlHelper for ASP.NET Core (Demo)
Using the API of the Window HtmlHelper for ASP.NET Core (Demo)
Server-Side API
781
Telerik UI for ASP.NET Core
Dimensions
By default, the Window HtmlHelper does not have any pre-set dimensions and its size depends on its
content.
@(Html.Kendo().Window()
.Name("window")
.Title("Alvar Aalto")
.Width(300)
.Height(250)
.Content(@<text>
<p>
Alvar Aalto is one of the greatest names in modern architecture and design.
Glassblowers at the iittala factory still meticulously handcraft the legendary
vases
that are variations on one theme, fluid organic shapes that let the end user
decide the use.
</p>
</text>)
)
The Window HTML helper also allows configuration for its min and max dimensions (height and
width).
@(Html.Kendo().Window()
.Name("window")
.Title("Alvar Aalto")
.MinWidth(150)
.MaxWidth(450)
.MinHeight(200)
.MaxHeight(300)
.Content(@<text>
<p>
Alvar Aalto is one of the greatest names in modern architecture and design.
Glassblowers at the iittala factory still meticulously handcraft the legendary
vases
that are variations on one theme, fluid organic shapes that let the end user
decide the use.
</p>
</text>)
)
782
Telerik UI for ASP.NET Core
right edge of the browser viewport. In such cases, the widget sticks to the right viewport edge and
cannot be separated from it. This issue occurs because the Window is absolutely positioned with
CSS. To avoid such behavior, set an appropriate width to the widget, or a (max-)width to its content.
The lack of restrictions over the dimensions for vertical expanding of the Window and its content
might result in undesired behavior—for example, the rendition of a popup which is higher than the
browser viewport.
If the Window uses an iframe element, it does not resize automatically according to the iframe
content, because there is no relationship between the content and size of the iframe. However, iOS
devices do not support iframe scrolling and expand iframes according to their content, which might
increase the Window height too much. That is why it is not recommended to use the Window in an
iframe mode on Apple touch devices.
See Also
Server-Side API
783
Telerik UI for ASP.NET Core
Positioning
You can dynamically adjust the position of the Window by using its API.
Usually, it is preferable to center the Window rather than open it near the HTML element which is
used to define its content. Often, the Window is opened as a result of a user action rather than of the
load event of the page. Basically, the widget can be initialized as non-visible and can be opened
when needed.
The following example demonstrates how to center and open a Kendo UI for jQuery Window on a
button click. If the content is loaded through Ajax, centering occurs after the request is complete.
@(Html.Kendo().Window()
.Name("window")
.Title("Centered Window")
.Visible(false)
.Width(200)
.Height(200)
.Content(@<text>
Window content here.
</text>)
)
@(Html.Kendo().Button()
.Name("button")
.Content("Open Window")
.Events(e => e.Click("onClick"))
)
The following example demonstrates how to center and open the Window upon button click.
function onClick(e) {
var win = $("#window").data("kendoWindow");
win.center().open();
}
See Also
Server-Side API
784
Telerik UI for ASP.NET Core
The Containment() option overrides the appendTo setting and attaches the Window to the
specified DOM element. You have to correctly position the containment element by using the
relative, absolute, or fixed CSS rules.
The following example demonstrates how to create a modal Window and constrain its movement
inside a DOM element.
<style>
#container {
position: relative;
width: 500px;
height: 500px;
border: 1px solid grey;
}
</style>
<div id="container">
@(Html.Kendo().Window()
.Name("window")
.Title("Alvar Aalto")
.Width(300)
.Height(250)
.Draggable(d => d.Containment("#container"))
.Content(@<text>
<p>
Alvar Aalto is one of the greatest names in modern architecture and design.
Glassblowers at the iittala factory still meticulously handcraft the legendary
vases
that are variations on one theme, fluid organic shapes that let the end user
decide the use.
</p>
</text>)
)
<div id="window">
</div>
</div>
See Also
Constraining the Movement of the Window HtmlHelper for ASP.NET Core (Demo)
Server-Side API
785
Telerik UI for ASP.NET Core
Loading Content
You can hardcode or dynamically load the content of the Window HtmlHelper at a later stage.
Static Content
The Window exposes a Content() configuration method which allows you to load predefined
HTML content.
@(Html.Kendo().Window()
.Name("window")
.Title("Static content")
.Content(@<text>
<strong>Static content</strong> of the Window.
</text>)
)
Load-on-Demand Content
To configure the Window with load-on-demand content:
public IActionResult Index()
{
return View();
}
public IActionResult AjaxContent()
{
return View();
}
3. Add a Window.
@(Html.Kendo().Window()
.Name("window") // The name of the Window is mandatory. It specifies the
"id" attribute of the widget.
.Title("About Alvar Aalto") // Set the title of the Window.
.LoadContentFrom("AjaxContent", "Window") //Define the Action and Controller
names.
)
786
Telerik UI for ASP.NET Core
See Also
Server-Side API
787
Telerik UI for ASP.NET Core
Using iframe
You can force the Window to display its content in an <iframe> element by using the
Iframe(true) configuration method.
Loading HTML fragments (partial content) inside an iframe is not correct. iframe pages
have to include a DOCTYPE, html, head, and body tags, just like a standard web page does.
Avoid using iframes on iOS devices because they are not scrollable and always expand to
match the content.
The following example demonstrates how to access the window and document objects inside the
iframe. To achieve this, the nested page has to belong to the same domain as the main page. The
iframe is accessed through the element of the Window.
@(Html.Kendo().Window()
.Name("window")
.Title("Iframe Window")
.Iframe(true)
.LoadContentFrom("Content", "Home")
)
<script>
$(function() {
var windowElement = $("#window");
var iframeDomElement = windowElement.children("iframe")[0];
var iframeWindowObject = iframeDomElement.contentWindow;
var iframeDocumentObject = iframeDomElement.contentDocument;
// which is equivalent to
// var iframeDocumentObject = iframeWindowObject.document;
var iframejQuery = iframeWindowObject.$; // if jQuery is registered inside the
iframe page, of course
});
</script>
See Also
Server-Side API
788
Telerik UI for ASP.NET Core
Forms Integration
The Window HtmlHelper provides various approaches to load a <form> element as its content.
The following example demonstrates how to insert a complete form inside the Window.
@{Html.Kendo().Window()
.Name("window")
.Content(@<text>
@using (Html.BeginForm("FormSubmit", "Home"))
{
//...
}
</text>)
.Render();
}
Though the Window allows the creation of popup forms, you need to consider the conceptual
differences during their implementation. Typically, if you load a view into a Kendo UI for jQuery
Window, it does not act as a separate browser window. This means that any returned data from the
form submit action loads into the main page and eventually might lead to unexpected results.
@(Html.Kendo().Window()
.Name("PopupForm")
.Title("My Form")
.LoadContentFrom("GetForm","Home")
.Iframe(true)
.Resizable()
.Draggable()
)
<script>
// Implement a script that will close the popup when model is valid.
function closeFormPopup() {
$("#PopupForm").data("kendoWindow").close();
}
</script>
789
Telerik UI for ASP.NET Core
public IActionResult GetForm()
{
// Return the view with the form.
return View("Form");
}
@* As this is loaded in an iframe, the view will have a layout to load an entire HTML
page. *@
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@model TelerikMvcApp.Models.MyModel
@using (Html.BeginForm("MyModel_Create", "MyModel", FormMethod.Post))
{
@Html.ValidationSummary()
@Html.EditorForModel(Model);
@(Html.Kendo().Button()
.Name("SubmitBtn")
.HtmlAttributes(new { type = "submit" })
.Content("Submit")
)
}
public class MyModel
{
[Required]
[Url(ErrorMessage = "Please enter a valid url")]
public string Url { get; set; }
[Required]
[StringLength(10)]
public string Description { get; set; }
}
[HttpPost]
public IActionResult MyModel_Create(MyModel model)
{
if (!ModelState.IsValid)
{
/* If the model is invalid, as expected, return the same
view and send the invalid model to update validation. */
return View("Form", model);
}
// Return a script that runs the close method of the parent window.
return Content("<script>window.parent.closeFormPopup()</script>");
}
See Also
Constraining the Movement of the Window HtmlHelper for ASP.NET Core (Demo)
790
Telerik UI for ASP.NET Core
Server-Side API
791
Telerik UI for ASP.NET Core
Window Accessibility
The Window is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Window is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The Window supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Window HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Window HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
792
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Window is always available.
For a complete example, refer to the demo on keyboard navigation of the Window.
See Also
Keyboard Navigation in the Window HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Window HtmlHelper for ASP.NET Core
793
Telerik UI for ASP.NET Core
The MediaPlayer plays video files from static sources or streams online YouTube videos and
enriches your website with dynamic content in a user-friendly interface. It provides a styled video UI
functionality by using the HTML5 <video> element and brings powerful media capabilities to your
applications without the necessity of installing additional plug-ins.
To respond to cutting-end design practices and trends, the MediaPlayer component provides a
responsive layout. This means that its size adapts depending on the capabilities of the client (end
user) device and browser. The component automatically resizes its area to display the video in the
most suitable possible way within the provided dimensions. The responsive web design of the
MediaPlayer is shipped out-of-the-box and intends to save you time and efforts when developing
your responsive applications.
Because of the mobile considerations, browsers on iOS do not automatically play embedded
media. This limitation prevents unsolicited downloads over cellular networks at the expense
of the user. The user always has to initiate a playback. For more information, refer to the
article on audio and video HTML.
Other functionalities may also be limited due to iOS restrictions. For more information, refer
to this articleand to other available resources on the Web.
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer")
.AutoPlay(true)
.Navigatable(true)
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
Basic Configuration
The following example demonstrates the basic configuration of the MediaPlayer HtmlHelper.
794
Telerik UI for ASP.NET Core
@(Html.Kendo().MediaPlayer()
.AutoPlay(true) // Start playing the video as soon as it loads.
.Navigatable(true) // Enable the keyboard navigation.
.AutoRepeat(true) // Loop the video.
.ForwardSeek(false) // Disable forward seeking to ensure viewers will watch the
entire video.
.FullScreen(false) // When set to true, the player will automatically enter the
full-screen mode.
.Mute(true) // Start without sound.
.Volume(20) // Preset the volume level (0 - 100).
.Media(m => m // Define the media file - a YouTube video in this case.
.Title("Getting Started with Telerik UI for ASP.NET Core on Windows")
.Source("https://www.youtube.com/watch?v=AIFNeWrZCdM")
)
.Name("mediaPlayer") // The name of the widget that is used for the ID and for
referencing it at runtime.
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
Events
You can subscribe to all MediaPlayer events. For a complete example on basic MediaPlayer events,
refer to the demo on using the events of the MediaPlayer.
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer")
.AutoPlay(true)
.Events(e =>
{
e.Pause("playerPause");
e.VolumeChange("playerVolumeChange");
})
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
<script>
function playerPause(e) {
// Handle the pause event.
}
function playerVolumeChange(e) {
// Handle the volumeChange event.
}
795
Telerik UI for ASP.NET Core
</script>
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer")
.AutoPlay(true)
.Events(e =>
e.Pause(@<text>
function(e) {
// Handle the pause event inline.
}
</text>)
.VolumeChange(@<text>
function(e) {
// Handle the volumeChange event inline.
}
</text>)
)
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer")
.AutoPlay(true)
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
<button onclick="buttonClick();">Pause Video</button>
<script>
function buttonClick() {
var player = $("#mediaplayer1").data("kendoMediaPlayer");
player.pause();
}
</script>
See Also
Basic Usage of the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
Using the API of the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
796
Telerik UI for ASP.NET Core
Server-Side API
797
Telerik UI for ASP.NET Core
Multiple Sources
To add multiple sources for the same video, you have to configure the quality-dependent client-side
HD feature.
When you add multiple sources for the video, an HD button is automatically displayed in the bottom
right corner next to the FullScreen button. This behavior enables you to select your preferred quality.
@(Html.Kendo().MediaPlayer()
.AutoPlay(true)
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source(new[] { // define the media files for different quality options
new { quality = "480p", url = "Video/videoLQ.mp4" },
new { quality = "720p", url = "Video/videoHD.mp4" },
new { quality = "1080p", url = "Video/videoFHD.mp4" },
})
)
.Name("mediaPlayer")
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
See Also
Basic Usage of the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
Using the API of the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
798
Telerik UI for ASP.NET Core
MediaPlayer Globalization
The globalization process combines the translation of component messages (localization) with
adapting them to specific cultures (internationalization and right-to-left support).
The globalization functionality of the MediaPlayer is enabled through the localization of messages.
For more information on using localization and right-to-left languages with Telerik UI for ASP.NET
Core helpers, refer to the article on globalization support by Telerik UI for ASP.NET Core.
See Also
Globalization in Telerik UI for ASP.NET Core
Server-Side API
799
Telerik UI for ASP.NET Core
Localization
You can localize the tooltip texts from the MediaPlayer interface through the Messages
configuration options.
For a complete list of localizable messages, refer to the MediaPlayer server-side API.
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer1")
.Messages(messages =>
{
messages.Play("Wiedergabe");
messages.Pause("Pausieren");
})
.Media(m => m
.Title("Mein Video")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
See Also
Globalization in Telerik UI for ASP.NET Core
Server-Side API
800
Telerik UI for ASP.NET Core
MediaPlayer Accessibility
The MediaPlayer is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The MediaPlayer follows the WAI-ARIA Authoring Practices for implementing the keyboard
navigation for its component role and is tested against the popular screen readers. For more
information, refer to the article on WAI-ARIA support in UI for ASP.NET Core.
Section 508
The MediaPlayer is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for jQuery.
WCAG 2.1
The MediaPlayer supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1.
See Also
Keyboard Navigation by the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the MediaPlayer HtmlHelper for ASP.NET Core
Accessibility Compliance in Telerik UI for ASP.NET Core
801
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the MediaPlayer is always available.
To enable it, use the Navigatable(true) configuration. For a complete example, refer to the demo
on using the keyboard navigation of the MediaPlayer .
Shortcut Description
Enter Opens the video in the full-screen mode.
Esc Exits the full-screen mode.
Space Toggles the play and pause state.
M Toggles the mute and unmute state.
@(Html.Kendo().MediaPlayer()
.Name("mediaplayer")
.Navigatable(true)
.Media(m => m
.Title("Our Company Culture - Lesson 1")
.Source("Video/video1.mp4")
)
.HtmlAttributes(new { style = "height:360px; width:640px" })
)
See Also
Keyboard Navigation by the MediaPlayer HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
802
Telerik UI for ASP.NET Core
The ScrollView displays a horizontal collection of content or image views with built-in navigation
between them. It can be scrolled through dragging, gestures, arrow click or page click or tap. Among
the key features of the ScrollView are data-source binding, customizable template, built-in pager,
adjustable bounce effects and scroll velocity.
From HTML
1. Use its Items() method.
2. Add HTML elements for each page as part of the content of the ScrollView items.
<style>
h1 {
margin-top: 30%;
text-align:center;
}
</style>
@(Html.Kendo().ScrollView()
.Name("scrollView")
.ContentHeight("100%")
.Items(x =>
{
x.Add().Content("<h1>One</h1>");
x.Add().Content("<h1>Two</h1>");
x.Add().Content("<h1>Three</h1>");
})
.HtmlAttributes(new { style = "height:748px; width:1022px; max-width: 100%;" })
)
Make sure that the template provides the pageSize of the data source. If serverPaging is enabled,
the ScrollView will request the data in advance so it becomes available before it is required, thus
improving user experience. The ScrollView uses virtualization when it is bound to a data source and
it only has three pages at all times—the current, the previous, and the next.
803
Telerik UI for ASP.NET Core
@(Html.Kendo().ScrollView()
.Name("scrollView")
.ContentHeight("100%")
.TemplateId("employee-template")
.DataSource(d =>
d.Custom()
.Type("odata")
.Transport(t => t.Read(r =>
r.Url("https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees")))
.ServerPaging(true)
.PageSize(1))
.HtmlAttributes(new { style = "height:600px; width:890px; max-width: 100%;" })
)
<script id="employee-template" type="text/x-kendo-template">
<div class="template">
<h1>
<span>#:TitleOfCourtesy# #: FirstName# #: LastName# </span>
</h1>
<h3>Title: #: Title #</h3>
<div class="notes"><em>#:Notes#</em></div>
<div class="country">
#: Country #
</div>
</div>
</script>
The following example demonstrates how to fetch data from a Controller action.
@(Html.Kendo().ScrollView()
.Name("scrollView")
.EnablePager(false)
.ContentHeight("100%")
.TemplateId("scrollview-template")
.DataSource(dataSource => dataSource
.Custom()
.Type("aspnetmvc-ajax")
.Transport(transport => transport
.Read(read => read.Action("GetScrollViewData", "Home"))
)
.Schema(s => s.Data("Data").Total("Total"))
.ServerPaging(true)
.PageSize(1))
.HtmlAttributes(new { style = "height:200px; width:300px" })
)
<script id="scrollview-template" type="text/x-kendo-template">
<p style="border: 2px solid blue; color: red;">#= data.SomeField #</p>
</script>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetScrollViewData([DataSourceRequest]DataSourceRequest
request)
804
Telerik UI for ASP.NET Core
{
IEnumerable<MyModel> data = Enumerable.Range(1, 5).Select(x => new MyModel {
SomeField = "item " + x + " from page " + request.Page });
return Json(data.ToDataSourceResult(request));
}
}
public class MyModel
{
public string SomeField { get; set; }
}
If you set the PageSize option to a larger value, you will need to use a loop in the template.
<script id="scrollview-template" type="text/x-kendo-template">
# for (var i = 0; i < data.length; i++) { #
<p style="border: 2px solid blue; color: red;">#= data[i].SomeField #</p>
# } #
</script>
Events
For a complete example on basic ScrollView events, refer to the demo on using the events of the
ScrollView.
// Place the following after your Telerik UI ScrollView for ASP.NET Core declaration.
<script>
$(function() {
// The For() of the ScrollView is used to get its client-side instance.
var scrollview = $("#scrollview").data("kendoScrollView");
});
</script>
See Also
Basic Usage of the ScrollView HtmlHelper for ASP.NET Core (Demo)
Using the API of the ScrollView HtmlHelper for ASP.NET Core (Demo)
805
Telerik UI for ASP.NET Core
806
Telerik UI for ASP.NET Core
Templates
You can configure the items of the ScrollView by using plain HTML and CSS, by setting a dynamic
template, or by using a no-item template.
HTML Template
The following example demonstrates how to use HTML templates to set the ScrollView items.
@(Html.Kendo().ScrollView()
.Name("scrollView")
.ContentHeight("100%")
.Items(x =>
{
x.Add().Content("<div class='photo photo1'></div>");
x.Add().Content("<div class='photo photo2'></div>");
x.Add().Content("<div class='photo photo3'></div>");
x.Add().Content("<div class='photo photo4'></div>");
x.Add().Content("<div class='photo photo5'></div>");
x.Add().Content("<div class='photo photo6'></div>");
x.Add().Content("<div class='photo photo7'></div>");
x.Add().Content("<div class='photo photo8'></div>");
x.Add().Content("<div class='photo photo9'></div>");
x.Add().Content("<div class='photo photo10'></div>");
})
.HtmlAttributes(new { style = "height:748px; width:1022px; max-width: 100%;" })
)
<style>
.photo {
display: inline-block;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
width:inherit;
height:inherit;
}
.photo1 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo2 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo3 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo4 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
807
Telerik UI for ASP.NET Core
.photo5 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo6 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo7 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo8 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo9 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
.photo10 {
background-image: url("../shared/images/photos/@(random.Next(1,30)).jpg");
}
</style>
Dynamic Template
The ScrollView allows for configuring a dynamic template which loops through all of its data items.
@(Html.Kendo().ScrollView()
.Name("scrollView")
.EnablePager(false)
.ContentHeight("100%")
.TemplateId("scrollview-template")
.DataSource(d =>
d.Custom()
.Type("odata")
.Transport(t => t.Read(r =>
r.Url("https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products")))
.ServerPaging(true)
.PageSize(3))
.HtmlAttributes(new { style = "height:600px; width:890px; max-width: 100%;" })
)
<script id="scrollview-template" type="text/x-kendo-template">
<div class="img-wrapper">
# for (var i = 0; i < data.length; i++) { #
<div>
<div style="width: 140px; height: 140px; background-image:
#=setBackground(data[i].ProductID)#; background-repeat:no-repeat; background-size:
cover;"></div>
<p>#= data[i].ProductName #</p>
</div>
# } #
</div>
</script>
<script>
function setBackground(id) {
808
Telerik UI for ASP.NET Core
return "url(https://demos.telerik.com/kendo-ui/content/web/foods/" + id +
".jpg)";
}
</script>
No-Item Template
The following example demonstrates how to set a template when no ScrollView items will be
displayed.
@(Html.Kendo().ScrollView()
.Name("scrollview")
.EmptyTemplateId("scrollview-empty")
)
<script id="scrollview-empty" type="text/x-kendo-template">
<div style="width: 100%; height: 100%; background-color: red;">empty</div>
</script>
See Also
Basic Usage of the ScrollView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
809
Telerik UI for ASP.NET Core
Paging
By default, the pager of the Telerik UI ScrollView for ASP.NET Core is enabled.
If the pager is set to false, the ScrollView will not display a pager.
@(Html.Kendo().ScrollView()
.Name("scrollView")
.EnablePager(false) // The ScrollView will not display a pager.
.ContentHeight("100%")
.TemplateId("scrollview-template")
.DataSource(d =>
d.Custom()
.Type("odata")
.Transport(t => t.Read(r =>
r.Url("https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products")))
.ServerPaging(true)
.PageSize(3))
.HtmlAttributes(new { style = "height:600px; width:890px; max-width: 100%;" })
)
<script id="scrollview-template" type="text/x-kendo-template">
<div class="img-wrapper">
# for (var i = 0; i < data.length; i++) { #
<div>
<div style="width: 140px; height: 140px; background-image:
#=setBackground(data[i].ProductID)#; background-repeat:no-repeat; background-size:
cover;"></div>
<p>#= data[i].ProductName #</p>
</div>
# } #
</div>
</script>
<script>
function setBackground(id) {
return "url(https://demos.telerik.com/kendo-ui/content/web/foods/" + id +
".jpg)";
}
</script>
See Also
Basic Usage of the ScrollView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
810
Telerik UI for ASP.NET Core
The Breadcrumb is an intuitive UI component that allows navigation within a folder structure or web
page. It provides an easy way to navigate backwards by one or multiple steps.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
)
Basic Configuration
The following example demonstrates the basic configuration for the Breadcrumb HtmlHelper.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
.Items(items =>
{
items.Add()
.Type(BreadcrumbItemType.RootItem)
.Href("https://demos.telerik.com/kendo-ui/")
.Text("All Components")
.Icon("home")
.ShowIcon(true);
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/breadcrumb")
.Text("Breadcrumb")
.ShowText(true);
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/index")
.Text("Basic Usage")
.ShowText(true);
})
)
<script>
$(function() {
// The Name() of the Breadcrumb is used to get its client-side instance.
var breadcrumb = $("#breadcrumb").data("kendoBreadcrumb");
});
</script>
811
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
Using the API of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
812
Telerik UI for ASP.NET Core
Items
The items configuration allows you to set specific attributes to the Breadcrumb items. You can set
the text and the icon of an element and determine whether they would be visible or not. The
configuration also allows you to add classes for the different elements which are rendered when
initializing the widget.
The following example demonstrates how the attributes of the Breadcrumb items can be set through
the items configuration.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
.Items(items =>
{
items.Add()
.Type(BreadcrumbItemType.RootItem)
.Href("https://demos.telerik.com/kendo-ui/")
.Text("All Components")
.ShowText(true)
.Icon("home")
.ShowIcon(true)
.ItemClass("root")
.IconClass("root")
.LinkClass("root");
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/breadcrumb")
.Text("Breadcrumb")
.ShowText(true)
.ItemClass("item")
.IconClass("item")
.LinkClass("item");
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/index")
.Text("Basic Usage")
.ShowText(true)
.ItemClass("item")
.IconClass("item")
.LinkClass("item");
})
)
See Also
Basic Usage of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
813
Telerik UI for ASP.NET Core
Icons
The Breadcrumb allows to configure the icons of the items and the delimiters.
Root Icon
The root icon is the first icon and is rendered as a home icon. It can be changed through the
items.icon configuration. It is also clickable and it will reset the value of the component.
Item Icon
The icons rendered for each element after the root icon. It is also clickable and can be configured
through the items.icon.
Delimiter Icon
The icons that separate the items of the Breadcrumb.
Example
The following example demonstrates how to configure different icons.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
.Items(items =>
{
items.Add()
.Type(BreadcrumbItemType.RootItem)
.Href("https://demos.telerik.com/kendo-ui/")
.Text("All Components")
.ShowText(true)
.Icon("globe");
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/breadcrumb")
.Text("Breadcrumb")
.ShowText(true)
.Icon("gear")
.ShowIcon(true);
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/icons")
.Text("Icons")
.ShowText(true)
.ItemClass("item")
.IconClass("item")
.LinkClass("item");
})
.DelimiterIcon("line")
)
814
Telerik UI for ASP.NET Core
See Also
Icons of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
815
Telerik UI for ASP.NET Core
Editing
The path set through the Breadcrumb widget can be edited if the Editable configuration is enabled.
When clicking in an empty area of the component or on the current page, the Breadcrumb will enter
into editing mode. That will also happen when enter is pressed if the Breadcrumb is focused.
Editing mode shows an input field containing the current value of the widget. Users are allowed to
type a new path.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
.Items(items =>
{
items.Add()
.Type(BreadcrumbItemType.RootItem)
.Href("https://demos.telerik.com/kendo-ui/")
.Text("All Components")
.ShowText(true)
.Icon("home");
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/breadcrumb")
.Text("Breadcrumb");
items.Add()
.Type(BreadcrumbItemType.Item)
.Href("/editing")
.Text("Editing");
})
.Editable(true)
)
See Also
Editing of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
816
Telerik UI for ASP.NET Core
Navigation
The Navigationalconfiguration determines whether automatic navigation will be enabled. The
default value is false. When set to true, the url will be added to the href attribute of the Breadcrumb
items.
@(Html.Kendo().Breadcrumb()
.Name("breadcrumb")
.BindToLocation(true)
.Navigational(true)
)
The BindToLocation configuration sets the value ot the widget to the current url (the location
object). In addition, that url will be added to the href attribute of the Breadcrumb items through the
Navigational configuration.
When the configuration is disabled, you need to implement the navigation programmatically.
See Also
Navigation of the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
817
Telerik UI for ASP.NET Core
Breadcrumb Accessibility
The Breadcrumb is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Breadcrumb is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Breadcrumb supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Breadcrumb HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
818
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Breadcrumb is always available.
For a complete example, refer to the demo on keyboard navigation of the Breadcrumb.
See Also
Keyboard Navigation in the Breadcrumb HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Breadcrumb HtmlHelper for ASP.NET Core
819
Telerik UI for ASP.NET Core
The Button provides a styled clickable UI functionality with arbitrary content. Apart from consistent
Kendo UI for jQuery styling, the Button provides keyboard operability for elements, which natively do
not have it—for example, span.
@(Html.Kendo().Button()
.Name("textButton")
.HtmlAttributes( new {type = "button"} )
.Content("Text Button")
)
Basic Configuration
The Name() configuration method is mandatory as its value will be used for the id and the
name attributes of the Button element. Moreover, the id is used in order to properly initialize
the Button widget. The id attribute value is also used to retrieve its client-side instance.
The Content() configuration specifies the text that would be rendered in the button. This
option does not accept HTML, but only string values.
The Enable() option determines whether the widget will be initially enabled (by default) of
disabled.
The Tag() method allows the developer to determine whether the widget will be initialized
from a <button> element (by default), or from an <a> element.
The following example demonstrates the available configuration options for the Button HtmlHelper.
@(Html.Kendo().Button()
.Name("textButton")
.Content("Sample Button")
.Enable(false)
.Tag("a")
)
<script type="text/javascript">
$(function() {
// The Name() of the Button is used to get its client-side instance.
var button = $("#textButton").data("kendoButton");
});
</script>
820
Telerik UI for ASP.NET Core
Events
The Button HTML helper exposes only a Click() event that can be handled. For a complete
example on basic Button events, refer to the demo on using the events of the Button.
@(Html.Kendo().Button()
.Name("button")
.Content("Sample Button")
.Events(e => e.Click("onClick"))
)
<script>
function onClick() {
alert('Button clicked!')
}
</script>
See Also
Basic Usage of the Button HtmlHelper for ASP.NET Core (Demo)
Using the API of the Button HtmlHelper for ASP.NET Core (Demo)
Server-Side API
821
Telerik UI for ASP.NET Core
Disabled Button
The business logic of an application often requires a certain button to be temporarily disabled or
enabled.
You can initially configure the Button as disabled either through its .Enable() setting. The Button
can also be disabled or enabled at any time with JavaScript by using its enable() methodwith a
Boolean argument.
The following example demonstrates how to enable and disable the Button.
@(Html.Kendo().Button()
.Name("disabledButton")
.Enable(false)
.Content("Disabled button"))
See Also
Basic Usage of the Button HtmlHelper for ASP.NET Core (Demo)
Using the API of the Button HtmlHelper for ASP.NET Core (Demo)
ButtonBuilder Server-Side API
Button Server-Side API
822
Telerik UI for ASP.NET Core
Icon Button
The Button can accommodate an icon which enhances the meaning of the text content.
The Button HtmlHelper provides the following methods for configuring icons:
Icon()
SpriteCssClass()
ImageUrl()
Use only one of them with a particular Button instance. If you define multiple properties, only one of
them will be obeyed according to the order stated above.
The Icon() method displays the appropriate Kendo UI for jQuery font iconas a content of a <spn>
:before pseudo element. The Button enables you to completely omit any text to be specified for its
contents.
@(Html.Kendo().Button()
.Name("textButton")
.Icon("delete")
)
The SpriteCssClass() method displays the icon as a background of a span element instead.
@(Html.Kendo().Button()
.Name("textButton")
.Content("Sample Button")
.SpriteCssClass("myDeleteIcon")
)
Image icons are applied by using the ImageUrl() method and are displayed as an img element.
@(Html.Kendo().Button()
.Name("textButton")
.Content("Sample Button")
.ImageUrl("url/to/myDeleteIcon.png")
)
See Also
Adding Images to the Button HtmlHelper for ASP.NET Core (Demo)
Server-Side API
823
Telerik UI for ASP.NET Core
Button Accessibility
The Button is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Button is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The Button supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Button HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Button HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
824
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Button is always available.
For a complete example, refer to the demo on keyboard navigation of the Button.
See Also
Keyboard Navigation in the Button HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Button HtmlHelper for ASP.NET Core
825
Telerik UI for ASP.NET Core
@(Html.Kendo().ButtonGroup()
.Name("select-period")
.Items(t =>
{
t.Add().Text("Month");
t.Add().Text("Quarter");
t.Add().Text("Year");
}))
Events
For a complete example on basic ButtonGroup events, refer to the demo on using the events of the
ButtonGroup.
See Also
Basic Usage of the ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Using the API of the ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Server-Side API
826
Telerik UI for ASP.NET Core
Disabled ButtonGroup
The ButtonGroup provides options for setting its enabled and disabled state.
To configure the ButtonGroup as initially disabled, use its .Enable() setting. The ButtonGroup can
also be disabled or enabled with JavaScript by using its .Enable() method with a Boolean
argument.
The following example demonstrates how to enable and disable the ButtonGroup over the
.Enable() configuration.
@(Html.Kendo().ButtonGroup()
.Name("select-period")
.Enable(false)
.Items(t =>
{
t.Add().Text("Month");
t.Add().Text("Quarter");
t.Add().Text("Year");
}))
See Also
Server-Side API
827
Telerik UI for ASP.NET Core
Icon ButtonGroup
The ButtonGroup can accommodate an icon and in this way to enhance the meaning of the text
content.
You can configure the icons by using the .Icon() method of the ButtonGroup.
@(Html.Kendo().ButtonGroup()
.Name("player")
.Items(t =>
{
t.Add().Icon("play");
t.Add().Icon("pause");
t.Add().Icon("stop");
}))
<div class="k-button-group k-widget" data-role="buttongroup" id="player" role="group"
tabindex="0">
<span data-icon="play" aria-pressed="false" role="button" class="k-button
k-button-icon">
<span class="k-icon k-i-play"></span>
</span>
<span data-icon="pause" aria-pressed="false" role="button" class="k-button
k-button-icon">
<span class="k-icon k-i-pause"></span>
</span>
<span data-icon="stop" aria-pressed="false" role="button" class="k-button
k-button-icon">
<span class="k-icon k-i-stop"></span>
</span>
</div>
See Also
Adding Images to the ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Server-Side API
828
Telerik UI for ASP.NET Core
Index
You can configure the initially selected index of the Telerik UI ButtonGroup by using its index
property.
You can also select an index through the select() method with a Integer argument.
@(Html.Kendo().ButtonGroup()
.Name("select-period")
.Index(1)
.Items(t =>
{
t.Add().Text("Month");
t.Add().Text("Quarter");
t.Add().Text("Year");
}))
See Also
Server-Side API
829
Telerik UI for ASP.NET Core
Selection
You can restrict the number of Buttons that can be selected by using the .Selection() property of
each Button within the ButtonGroup.
@(Html.Kendo().ButtonGroup()
.Name("select-period")
.Selection("multiple")
.Items(t =>
{
t.Add().Text("Month");
t.Add().Text("Quarter");
t.Add().Text("Year");
}))
See Also
Selection by the Telerik UI ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Server-Side API
830
Telerik UI for ASP.NET Core
ButtonGroup Accessibility
The ButtonGroup is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1,
and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The ButtonGroup is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The ButtonGroup supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the ButtonGroup HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
831
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the ButtonGroup is always available.
For a complete example, refer to the demo on keyboard navigation of the ButtonGroup.
See Also
Keyboard Navigation in the ButtonGroup HtmlHelper for ASP.NET Core (Demo)
Accessibility in the ButtonGroup HtmlHelper for ASP.NET Core
832
Telerik UI for ASP.NET Core
The Drawer is a dismissible panel used for navigation in responsive web applications or for changing
a content of a section in the page.
@(Html.Kendo().Drawer()
.Name("drawer")
.Template(@"<ul>
<li data-role='drawer-item'>First Item</li>
<li data-role='drawer-separator'></li>
<li data-role='drawer-item'>Second Item</li>
<li data-role='drawer-item' class='k-state-selected'>Third Item</li>
</ul>")
.Mode("push")
.Position("left")
.SwipeToOpen(true)
.Content(@"<div style='height: 200px;'>Lorem ipsum dolor sit amet consectetur
adipisicing elit. Error accusantium odit, optio nulla maiores quo neque fugit debitis
dignissimos incidunt maxime?</div>")
)
@(Html.Kendo().Drawer()
.Name("drawer")
.Template(@"<ul>
<li data-role='drawer-item'>First Item</li>
<li data-role='drawer-separator'></li>
<li data-role='drawer-item'>Second Item</li>
</ul>")
.Content(@"<div style='height: 200px;'>Lorem ipsum dolor sit amet consectetur
adipisicing elit. Error accusantium odit, optio nulla maiores quo neque fugit debitis
833
Telerik UI for ASP.NET Core
dignissimos incidunt maxime?</div>")
)
<script type="text/javascript">
$(function () {
// The Name() of the Drawer is used to get its client-side instance.
var drawer = $("#drawer").data("kendoDrawer");
console.log(drawer);
});
</script>
See Also
Basic Usage of the Drawer HtmlHelper for ASP.NET Core (Demo)
Using the API of the Drawer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
834
Telerik UI for ASP.NET Core
Display Modes
The Drawer provides a set of modes for handling the way it is displayed.
Overlay Mode
The overlay mode is not associated with any content. The Drawer appears on top of the page
contents from the side which is configured in the Position()method. To show the Drawer, either
swipe or drag with mouse or call the client-side show()method of the Drawer. The Drawer closes on
click or tap of any of the options or on the overlay.
Push Mode
The push mode is associated with specific page content and the element from which the widget is
initialized has to wrap that content. When the drawer opens it will push that content to the side. It is
designed for wider screens (desktop or tablet). To show the Drawer, either swipe or drag with
mouse, or call the client-side show()method of the Drawer. The Drawer closes on click or tap of any
of the options or on the associated content.
The height of the Drawer is determined by the higher content of the template of the widget or of the
wrapped content with which it is associated. You can use the MinHeight()method to prevent the
content from changing its height as the user toggles the drawer options.
Mini Mode
You can use the Mini() option both with the overlay and push modes by adding a the Mini()
method. If set to true, a portion of the Drawer that is always visible occupies the default width of
50px and the main template. If the Mini() configurator is used, the Width() and
Template()/TemplateId() can also be changed.
.Mini(m=>m.Width(500).TemplateId("mini-template"))
See Also
Mini Mode by the Drawer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
835
Telerik UI for ASP.NET Core
Interaction Modes
The Drawer provides a set of modes and with which the user can interact and positions in which it
can be rendered.
(Default) overlay
push
The Drawer supports the following positions which determine the side on which the it will be
rendered:
(Default) left
right
The Drawer provides gesture support. It also features the mini mode which makes the it always
partly visible and allows the user to reveal its full content either with a gesture or by calling the
show() method of the Drawer.
See Also
Position by the Drawer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
836
Telerik UI for ASP.NET Core
Templates
To distinguish the items within the template when the user interacts with the Drawer, add the
data-role="drawer-item" attribute to each item HTML template.
To add a separator between the Drawer items, use the data-role="drawer-separator" attribute.
You can add icons with a span with the k-icon class combined with the desired Kendo UI for jQuery
web font iconclass. To ensure that the icons and text have a sufficient padding, wrap the item
template text in a span with class k-item-text.
@"<ul>
<li data-role='drawer-item'>
<span class='k-icon k-i-eye'></span>
<span class='k-item-text'>See More</span>
</li>
</ul>"
See Also
Server-Side API
837
Telerik UI for ASP.NET Core
The Menu displays hierarchical data as a multi-level menu. It provides rich styling for unordered lists
of items, and can be used for both navigation and execution of JavaScript commands.
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
{
items.Add()
.Text("Products")
.Items(children =>
{
children.Add().Text("Furniture")
.Items(innerChildren =>
{
innerChildren.Add().Text("Tables & Chairs");
innerChildren.Add().Text("Sofas");
innerChildren.Add().Text("Occasional Furniture");
innerChildren.Add().Text("Childerns Furniture");
innerChildren.Add().Text("Beds");
});
children.Add().Text("Decor")
.Items(innerChildren =>
{
innerChildren.Add().Text("Bed Linen");
innerChildren.Add().Text("Throws");
innerChildren.Add().Text("Curtains & Blinds");
innerChildren.Add().Text("Rugs");
innerChildren.Add().Text("Carpets");
});
});
items.Add()
.Text("Stores")
.Items(children =>
{
children.Add().Text("Around the Globe")
.Items(innerChildren =>
{
innerChildren.Add().Text("United States");
innerChildren.Add().Text("Canada");
innerChildren.Add().Text("Europe");
innerChildren.Add().Text("Australia");
});
838
Telerik UI for ASP.NET Core
children.Add().Text("Decor")
.Items(innerChildren =>
{
innerChildren.Add().Text("Bed Linen");
innerChildren.Add().Text("Throws");
innerChildren.Add().Text("Curtains & Blinds");
innerChildren.Add().Text("Rugs");
innerChildren.Add().Text("Carpets");
});
});
})
)
public class MenuController : Controller
{
public IActionResult Index()
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration of the Menu HtmlHelper.
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
{
items.Add().Text("Item 1")
.ImageUrl(Url.Content("~/Content/shared/icons/sports/baseball.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
children.Add().Separator(true);
children.Add().Text("Videos Records");
children.Add().Text("Radio Records");
});
items.Add().Text("Item 2")
.ImageUrl(Url.Content("~/Content/shared/icons/sports/golf.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
children.Add().Separator(true);
children.Add().Text("Videos Records");
children.Add().Text("Radio Records");
});
items.Add().Text("Item 3")
.ImageUrl(Url.Content("~/Content/shared/icons/sports/swimming.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
});
})
839
Telerik UI for ASP.NET Core
.Animation(animation =>
{
animation.Open(open =>
{
open.Expand(ExpandDirection.Vertical);
});
})
.HoverDelay(500)
.Direction(MenuDirection.Left)
.Orientation(MenuOrientation.Horizontal)
.Events(events => events
.Open("onOpen")
.Close("onClose")
.Select("onSelect")
.Activate("onActivate")
.Deactivate("onDeactivate")
)
)
<script type="text/javascript">
$(function () {
// The Name() of the Menu is used to get its client-side instance.
var menu = $("#menu").data("kendoMenu");
console.log(menu);
});
</script>
Events
You can subscribe to all Menu events. For a complete example on basic Menu events, refer to the
demo on using the events of the Menu.
@(Html.Kendo().Menu()
.Name("menu")
.Events(e => e
.Open("menu_open")
.Close("menu_close")
)
)
<script>
function menu_close() {
// Handle the close event.
}
function menu_open() {
840
Telerik UI for ASP.NET Core
// Handle the open event.
}
</script>
@(Html.Kendo().Menu()
.Name("menu")
.Events(e => e
.Open(@<text>
function() {
// Handle the open event inline.
}
</text>)
.Close(@<text>
function() {
// Handle the close event inline.
}
</text>)
)
)
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
{
items.Add().Text("First Item");
items.Add().Text("Second Item").HtmlAttributes(new { @onclick =
"alert('select');" });
})
)
See Also
Basic Usage of the Menu HtmlHelper for ASP.NET Core (Demo)
Using the API of the Menu HtmlHelper for ASP.NET Core (Demo)
Server-Side API
841
Telerik UI for ASP.NET Core
Data Binding
The Menu provides a set of options for binding it to data.
Items binding
Model Binding
Binding to Remote Data
See Also
Server-Side API
842
Telerik UI for ASP.NET Core
Items Binding
The Menu enables you to manually define the properties of each item.
1. Make sure you followed all the steps from the introductory article on Telerik UI for ASP.NET
Core.
2. Create a new action method which renders the view.
public ActionResult Index()
{
return View();
}
@(Html.Kendo().Menu()
.Name("menu") // The name of the Menu is mandatory. It specifies the "id"
attribute of the Menu.
.Items(items =>
{
items.Add().Text("Item 1"); // Add an item with the text "Item1".
items.Add().Text("Item 2"); // Add an item with the text "Item2".
}
)
See Also
Basic Usage of the Menu HtmlHelper for ASP.NET Core (Demo)
MenuItemBuilder Server-Side API
MenuBuilder Server-Side API
Menu Server-Side API
843
Telerik UI for ASP.NET Core
Model Binding
The Telerik UI Menu enables you to bind it to a hierarchical model.
1. Create a new action method and pass the Categories table as the model. The Categories
has to be associated to the Products table.
public ActionResult Index()
{
NorthwindDataContext northwind = new NorthwindDataContext();
return View(northwind.Categories);
}
@model IEnumerable<MvcApplication1.Models.Category>
3. Add a Menu.
@(Html.Kendo().Menu()
.Name("menu") // The name of the Menu is mandatory. It specifies the "id"
attribute of the widget.
.BindTo(Model, mappings =>
{
mappings.For<category>(binding => binding // Define the first level of
the Menu.
.ItemDataBound((item, category) => // Define the mapping between the Menu
item properties and the model properties.
{
item.Text = category.CategoryName;
})
.Children(category => category.Products)); // Define which property of
the model contains the children.
mappings.For<product>(binding => binding
.ItemDataBound((item, product) =>
{
item.Text = product.ProductName;
}));
})
)
See Also
Model Binding by the Menu HtmlHelper for ASP.NET Core (Demo)
Binding to Custom Attributes by the Menu HtmlHelper for ASP.NET Core (Demo)
Server-Side API
844
Telerik UI for ASP.NET Core
1. Implement an action method in your controller that returns the collection for the Menu.
public JsonResult GetCategories()
{
SampleEntities northwind = new SampleEntities();
var result = northwind.Categories.Select((category) =>
new
{
Name = category.CategoryName,
Products = northwind.Products
.Where((product) => product.CategoryID == category.CategoryID)
.Select((product)=> new { Name = product.ProductName })
}
);
return Json(result, JsonRequestBehavior.AllowGet);
}
2. Use the DataSource to configure the action URL to the end-point. Set up the DataTextField
to define the field which will be bound to the text of the items. If the children items are not in
an items field, configure the Model with the corresponding field that holds the children
collection.
@(Html.Kendo().Menu()
.Name("menu")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Model(model => model.Children("Products"))
.Read(read => read
.Action("GetCategories", "Menu")
)
)
)
See Also
Remote Data Binding by the Menu HtmlHelper for ASP.NET Core (Demo)
Server-Side API
845
Telerik UI for ASP.NET Core
The ContextMenu displays hierarchical data as a multi-level menu in a popup. It provides rich styling
for unordered lists of items, and can be used for both navigation and execution of JavaScript
commands.
Basic Usage
The following example demonstrates how to define the ContextMenu by using the ContextMenu
HtmlHelper.
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.Items(items =>
{
items.Add()
.Text("Furniture") //Add an item with the text "Item1".)
.Items(children =>{
children.Add().Text("Sofas");
children.Add().Text("Chairs");
children.Add()
.Text("Tables")
.Items(i =>{
i.Add().Text("Dinning Tables");
i.Add().Text("Coffee Tables");
})
children.Add().Text("Accessories");
});
items.Add()
.Text("Electronics"); //Add an item with the text "Item2".)
.Items(children =>{
children.Add().Text("TVs");
children.Add().Text("Laptops");
});
})
)
Configuration
The following example demonstrates the basic configuration of the ContextMenu HtmlHelper and
how to get the ContextMenu instance.
846
Telerik UI for ASP.NET Core
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.Items(items =>
{
items.Add().Text("Item 1")
.ImageUrl(Url.Content("http://demos.telerik.com/kendo-ui/content/shared/icons/sports/b
aseball.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
children.Add().Separator(true);
children.Add().Text("Videos Records");
children.Add().Text("Radio Records");
});
items.Add().Text("Item 2")
.ImageUrl(Url.Content("http://demos.telerik.com/kendo-ui/content/shared/icons/sports/g
olf.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
children.Add().Separator(true);
children.Add().Text("Videos Records");
children.Add().Text("Radio Records");
});
items.Add().Text("Item 3")
.ImageUrl(Url.Content("http://demos.telerik.com/kendo-ui/content/shared/icons/sports/s
wimming.png"))
.Items(children =>
{
children.Add().Text("Top News");
children.Add().Text("Photo Galleries");
});
})
.Animation(animation =>
{
animation.Open(fade => fade.Fade(FadeDirection.In));
animation.Open(open => open.Expand(ExpandDirection.Vertical));
})
.HoverDelay(500)
.Direction("left")
.Orientation(ContextMenuOrientation.Horizontal)
.Events(events => events
.Open("onOpen")
)
)
<script type="text/javascript">
function onOpen() {
// The Name() of the ContextMenu is used to get its instance.
var menu = $("#contextmenu").data("kendoContextMenu");
console.log(menu);
}
</script>
847
Telerik UI for ASP.NET Core
Events
You can subscribe to all ContextMenu events.
By Handler Names
The following example demonstrates how to subscribe to events by a handler name.
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.Events(events => events
.Open("openMenu")
.Close("closeMenu")
.Select("onSelect")
)
)
<script>
function openMenu(){
// Handle the open event.
}
function closeMenu(){
// Handle the close event.
}
function onSelect(){
// Handle the select event.
}
</script>
By Template Delegates
The following example demonstrates how to subscribe to events by a template delegate.
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.Events(events => events
.Open(@<text>
function(){
// Handle the open event inline.
}
</text>)
.Close(@<text>
function(){
// Handle the close event inline.
}
</text>)
)
848
Telerik UI for ASP.NET Core
)
By HTML Attributes
The following example demonstrates how to subscribe to the select event of a single ContextMenu
item.
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.Items(items =>
{
items.Add().Text("First Item");
items.Add().Text("Second Item").HtmlAttributes(new { @onclick =
"alert('select');" });
})
)
See Also
Server-Side API
849
Telerik UI for ASP.NET Core
Data Binding
The ContextMenu provides Model Binding for binding it to data:
Model Binding
The Telerik UI ContextMenu enables you to bind it to a hierarchical model.
@model IEnumerable<ModelBindingDemo.Models.Category>
@model IEnumerable<ModelBindingDemo.Models.Category>
<div id="target">Click to open</div>
@(Html.Kendo().ContextMenu()
.Name("contextmenu")
.Target("#target")
.ShowOn("click")
.BindTo(Model, mappings =>
{
mappings.For<ModelBindingDemo.Models.Category>(binding => binding
.ItemDataBound((item, category) =>
{
item.Text = category.CategoryName;
})
.Children(category => category.Products));
mappings.For<ModelBindingDemo.Models.Product>(binding => binding
.ItemDataBound((item, product) =>
{
item.Text = product.ProductName;
}));
})
)
public class ContextMenuController : BaseController
{
public ActionResult ModelBinding()
{
var model = new List<Category>()
{
new Category
{
CategoryID = 1,
CategoryName = "Item 1",
Products = new List<Product>
850
Telerik UI for ASP.NET Core
{
new Product { ProductID = "1" , ProductName = "SubItem 1" },
new Product { ProductID = "2" , ProductName = "SubItem 2" },
new Product { ProductID = "3" , ProductName = "SubItem 3" }
}
},
new Category
{
CategoryID = 2,
CategoryName = "Item 2",
Products = new List<Product>
{
new Product { ProductID = "1" , ProductName = "SubItem 1" },
new Product { ProductID = "2" , ProductName = "SubItem 2" },
new Product { ProductID = "3" , ProductName = "SubItem 3" }
}
}
};
return View(model);
}
}
See Also
Server-Side API
851
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the ContextMenu is always available.
SHORTCUT DESCRIPTION
Home Focuses the first item.
End Focuses the last item.
Left Arrow Moves the active item on the root level
of a horizontal ContextMenu to the left.
Closes an item group.
See Also
852
Telerik UI for ASP.NET Core
Server-Side API
853
Telerik UI for ASP.NET Core
Menu Accessibility
The Menu is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in UI for ASP.NET Core.
Section 508
The Grid is compliant with the Section 508 requirements. For more information, refer to the article on
Section 508 support in Kendo UI for jQuery.
WCAG 2.1
The Grid supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1.
For more information, refer to the article on WCAG 2.1 compliance in UI for ASP.NET Core .
See Also
Keyboard Navigation by the Menu HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the menu HtmlHelper for ASP.NET Core
Accessibility Compliance in Telerik UI for ASP.NET Core
854
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Menu is always available.
SHORTCUT DESCRIPTION
Home Focuses the first item.
End Focuses the last item.
Left Arrow Moves the active item on the root level
of a horizontal Menu to the left.
Closes an item group.
See Also
Keyboard Navigation by the Menu HtmlHelper for ASP.NET Core (Demo)
855
Telerik UI for ASP.NET Core
Server-Side API
856
Telerik UI for ASP.NET Core
Basic Configuration
The following example demonstrates the basic configuration of the PanelBar HtmlHelper.
@(Html.Kendo().PanelBar()
.Name("panelbar")
.ExpandMode(PanelBarExpandMode.Single)
.Items(items =>
{
items.Add().Text("Root1")
.Items(subitems =>
{
subitems.Add().Text("Level2 1");
subitems.Add().Text("Level2 2");
});
items.Add().Text("Root2")
.Items(subitems =>
{
subitems.Add().Text("Level2 1");
subitems.Add().Text("Level2 2");
});
})
)
Events
You can subscribe to all PanelBar events. For a complete example on basic PanelBar events, refer to
the demo on using the events of the PanelBar.
857
Telerik UI for ASP.NET Core
@(Html.Kendo().PanelBar()
.Name("panelbar")
.Events(e => e
.Expand("panelbar_expand")
.Collapse("panelbar_collapse")
)
)
<script>
function panelbar_collapse() {
// Handle the collapse event.
}
function panelbar_expand() {
// Handle the expand event.
}
</script>
@(Html.Kendo().PanelBar()
.Name("panelbar")
.Events(e => e
.Expand(@<text>
function() {
// Handle the expand event inline.
}
</text>)
.Collapse(@<text>
function() {
// Handle the collapse event inline.
}
</text>)
)
)
// Place this after the PanelBar for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The Name() of the panelbar is used to get its client-side instance.
var panelbar = $("#panelbar").data("kendoPanelBar");
});
</script>
See Also
Basic Usage of the PanelBar HtmlHelper for ASP.NET Core (Demo)
Using the API of the PanelBar HtmlHelper for ASP.NET Core (Demo)
858
Telerik UI for ASP.NET Core
859
Telerik UI for ASP.NET Core
Data Binding
The PanelBar HTML helper provides support for declaratively defining its items and for local (on the
server) and remote (using a DataSource configuration object) binding.
The following example demonstrates how to configure a PanelBar with three levels of hierarchy.
@(Html.Kendo().PanelBar()
.Name("panelbar")
.Items(panelbar =>
{
panelbar.Add().Text("My Web Site")
.Items(root =>
{
root.Add().Text("images")
.Items(images =>
{
images.Add().Text("logo.png");
images.Add().Text("body-back.png");
});
root.Add().Text("about.html");
root.Add().Text("contacts.html");
});
})
)
PanelBar Binding
The PanelBar supports the following data-binding approaches:
Items binding
Server binding
Ajax binding
See Also
Local Data Binding by the PanelBar HtmlHelper for ASP.NET Core (Demo)
Ajax Data Binding by the PanelBar HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
860
Telerik UI for ASP.NET Core
Items Binding
The PanelBar enables you to manually define the properties of each item.
1. Make sure you followed all the steps from the introductory article on Telerik UI for ASP.NET
Core.
2. Create a new action method which renders the view.
public ActionResult Index()
{
return View();
}
3. Add a PanelBar.
@(Html.Kendo().PanelBar()
.Name("panelbar") // The name of the panelbar is mandatory. It specifies
the "id" attribute of the PanelBar.
.Items(items =>
{
items.Add().Text("Item 1"); // Add item with text "Item1".
items.Add().Text("Item 2"); // Add item with text "Item2".
})
)
See Also
Basic Usage of the PanelBar HtmlHelper for ASP.NET Core (Demo)
PanelBarBuilder Server-Side API
PanelBar Server-Side API
861
Telerik UI for ASP.NET Core
Server Binding
Local data is the data that is available on the client when the PanelBar is initialized.
You can bind the PanelBar locally on the server by passing the appropriate collection to the HTML
helper BindTo() method.
public ActionResult Index()
{
ViewBag.panelbarData = GetData();
return View();
}
private IEnumerable<PanelBarItemModel> GetData()
{
List<PanelBarItemModel> data = new List<PanelBarItemModel>
{
new PanelBarItemModel
{
Text = "Furniture",
Items = new List<PanelBarItemModel>
{
new PanelBarItemModel()
{
Text = "Tables & Chairs"
},
new PanelBarItemModel
{
Text = "Sofas"
},
new PanelBarItemModel
{
Text = "Occasional Furniture"
}
}
},
new PanelBarItemModel
{
Text = "Decor",
Items = new List<PanelBarItemModel>
{
new PanelBarItemModel()
{
Text = "Bed Linen"
},
new PanelBarItemModel
{
Text = "Curtains & Blinds"
},
new PanelBarItemModel
{
Text = "Carpets"
}
}
}
};
862
Telerik UI for ASP.NET Core
return data;
}
2. Add the PanelBar to the view and bind it to the data that is saved in the ViewData.
@using Kendo.Mvc.UI.Fluent
@(Html.Kendo().PanelBar()
.Name("panelbar")
.BindTo((IEnumerable<PanelBarItemModel>)ViewBag.panelbarData)
)
See Also
Ajax Data Binding by the PanelBar HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
863
Telerik UI for ASP.NET Core
@(Html.Kendo().PanelBar()
.Name("panelbar")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_PanelBarData", "Home")
)
)
)
public static IList<HierarchicalViewModel> GetHierarchicalData()
{
var result = new List<HierarchicalViewModel>()
{
new HierarchicalViewModel() { ID = 1, ParentID = null, HasChildren = true, Name
= "Parent item" },
new HierarchicalViewModel() { ID = 2, ParentID = 1, HasChildren = true, Name =
"Parent item" },
new HierarchicalViewModel() { ID = 3, ParentID = 1, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 4, ParentID = 2, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 5, ParentID = 2, HasChildren = false, Name =
"Item" }
};
return result;
}
public IActionResult Read_PanelBarData(int? id)
{
var result = GetHierarchicalData()
.Where(x => id.HasValue ? x.ParentID == id : x.ParentID == null)
.Select(item => new {
id = item.ID,
Name = item.Name,
hasChildren = item.HasChildren
});
return Json(result);
}
See Also
Local Data Binding by the PanelBar HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
864
Telerik UI for ASP.NET Core
Expand Modes
The PanelBar supports a single and a multiple expand mode.
If ExpandMode is set to Single, the user can expand only a single root item or a single child
item of a specific parent item. Expanding another root item or another child of the parent of
the currently expanded item will collapse the currently expanded item. This approach is also
the only way to collapse an expanded item in the single expand mode.
If ExpandMode is set to Multiple, the user can expand multiple root items or children of the
same parent item at a time. Expanding an item does not collapse the currently expanded
items. Expanded items can be collapsed by clicking on them.
@(Html.Kendo().PanelBar()
.Name("panelbar")
.ExpandMode(PanelBarExpandMode.Single)
.Items(items =>
{
items.Add().Text("Root1")
.Items(subitems =>
{
subitems.Add().Text("Level2 1");
subitems.Add().Text("Level2 2");
});
items.Add().Text("Root2")
.Items(subitems =>
{
subitems.Add().Text("Level2 1");
subitems.Add().Text("Level2 2");
});
})
)
See Also
Basic Usage of the PanelBar HtmlHelper for ASP.NET Core (Demo)
PanelBar Server-Side API
865
Telerik UI for ASP.NET Core
PanelBar Accessibility
The PanelBar is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The PanelBar is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The PanelBar supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the PanelBar HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the PanelBar HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
866
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the PanelBar is always available.
For a complete example, refer to the demo on keyboard navigation of the PanelBar.
See Also
Keyboard Navigation in the PanelBar HtmlHelper for ASP.NET Core (Demo)
Accessibility in the PanelBar HtmlHelper for ASP.NET Core
867
Telerik UI for ASP.NET Core
@(Html.Kendo().RadioButton()
.Name("MyRadioButton")
.Label("I agree")
.Checked(true))
See Also
RadioButton Server-Side API
RadioButtonBuilder Server-Side API
868
Telerik UI for ASP.NET Core
Disabled RadioButton
The business logic of an application often requires a certain radio button to be temporarily enabled
or disabled.
The RadioButton can be configured to be initially disabled through its .Enable() setting. The
widget can also be enabled or disabled at any time by using jQuery.
The following example demonstrates how to use the .Enable() configuration option.
@(Html.Kendo().RadioButton()
.Name("disabledRadioButton")
.Enable(false)
.Label("Disabled radio button")
.Checked(false))
See Also
RadioButton Server-Side API
RadioButtonBuilder Server-Side API
869
Telerik UI for ASP.NET Core
Checked RadioButton
You can configure the RadioButton to be initially checked through its .Checked() setting.
The widget can also be checked or unchecked at any time by using jQuery.
The following example demonstrates how to use the .Checked() configuration option.
@(Html.Kendo().RadioButton()
.Name("MyRadioButton")
.Label("I agree")
.Checked(true))
See Also
RadioButton Server-Side API
RadioButtonBuilder Server-Side API
870
Telerik UI for ASP.NET Core
Model Binding
You can bind a Telerik UI RadioButton to a model.
1. Create a new action method and pass the instance of the model to the View.
public class RadioButtonModel
{
public bool IAgreeProp { get; set; }
}
public partial class ButtonController : Controller
{
public ActionResult RadioButton()
{
RadioButtonModel myModel = new RadioButtonModel() { IAgreeProp = false };
return View(myModel);
}
}
@model Kendo.Mvc.Examples.Controllers.RadioButtonModel
3. Add two RadioButtons and set the Boolean values for the checked state through the .Value
setting. The matched Boolean value from model will define the initial checked state.
The following example demonstrates how the radio button with the I Disagree label will be
checked because its false value matches the model value.
@(Html.Kendo().RadioButtonFor(m => m.IAgreeProp).Label("I agree").Value(true))
@(Html.Kendo().RadioButtonFor(m => m.IAgreeProp).Label("I
Disagree").Value(false))
See Also
RadioButton Server-Side API
RadioButtonBuilder Server-Side API
871
Telerik UI for ASP.NET Core
The TabStrip displays a collection of tabs with associated content. It is composed of an unordered
list of items which represent tabs, and a collection of div elements, which contain the content for
each tab.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.Selected(true)
.Content(@<text>
<div class="weather">
<p>Rainy weather in Paris.</p>
</div>
</text>);
tabstrip.Add().Text("Sofia")
.Content(@<text>
<div class="weather">
<p>Sunny weather in Sofia.</p>
</div>
</text>);
tabstrip.Add().Text("Moscow")
.Content(@<text>
<div class="weather">
<p>Cloudy weather in Moscow.</p>
</div>
</text>);
tabstrip.Add().Text("Sydney")
.Content(@<text>
<div class="weather">
<p>Rainy weather in Sidney.</p>
</div>
</text>);
})
)
public class TabStripController : Controller
{
public IActionResult Index()
872
Telerik UI for ASP.NET Core
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration of the TabStrip HtmlHelper.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.TabPosition(TabStripTabPosition.Bottom)
.Collapsible(true)
.Navigatable(false)
.Animation(animation =>
{
animation.Open(config =>
{
config.Fade(FadeDirection.In);
});
})
.Items(items =>
{
items.Add().Text("One")
.Content(@<text>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</text>);
items.Add().Text("Two")
.Content(@<text>
<p>Mauris pulvinar molestie accumsan.</p>
</text>);
})
)
<script type="text/javascript">
$(function () {
// The Name() of the TabStrip is used to get its client-side instance.
var tabstrip = $("#tabstrip").data("kendoTabStrip");
console.log(tabstrip);
});
</script>
Events
The following example demonstrates the available TabStrip events and how an event handler could
be implemented for each of them. For a complete example on basic TabStrip events, refer to the
demo on using the events of the TabStrip.
873
Telerik UI for ASP.NET Core
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.LoadContentFrom(Url.Action("Paris", "Home"));
tabstrip.Add().Text("Sofia")
.LoadContentFrom(Url.Action("Sofia", "Home"));
})
.Events(events => events
.Show("onShow")
.Select("onSelect")
.Activate("onActivate")
.ContentLoad("onContentLoad")
.Error("onError")
)
)
<script type="text/javascript">
function onShow(e) {
console.log("Shown: " + $(e.item).find("> .k-link").text());
}
function onSelect(e) {
console.log("Selected: " + $(e.item).find("> .k-link").text());
}
function onActivate(e) {
console.log("Activated: " + $(e.item).find("> .k-link").text());
}
function onContentLoad(e) {
console.log("Content loaded in <b>"+ $(e.item).find("> .k-link").text() +
"</b>");
}
function onError(e) {
console.error("Loading failed with " + e.xhr.statusText + " " + e.xhr.status);
}
</script>
See Also
Basic Usage of the TabStrip HtmlHelper for ASP.NET Core (Demo)
Using the API of the TabStrip HtmlHelper for ASP.NET Core (Demo)
Server-Side API
874
Telerik UI for ASP.NET Core
Tabs
The TabStrip provides advanced options for configuring its tabs.
Dynamic Tabs
The TabStrip API provides methods for dynamically adding or removing TabStrip bars.
The following example demonstrates how to add a new TabStrip tab and position it after the first
existing tab.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.Content(@<text>
<p>Rainy weather in Paris.</p>
</text>);
tabstrip.Add().Text("Sofia")
.Content(@<text>
<p>Sunny weather in Sofia.</p>
</text>);
})
)
<script>
var tabstrip = $("#tabstrip").data("kendoTabStrip");
tabstrip.insertAfter(
{
text: 'Sydney',
content: '<p>Rainy weather in Sidney.</p>'
},
tabstrip.tabGroup.children("li:first")
);
</script>
Scrollable Tabs
The TabStrip supports scrollable top and bottom tabs through TabPosition(). During
initialization, the TabStrip checks if the tabs fit in the available horizontal space and if not, renders
scroll buttons on the sides. By default, the scrollable tabs are enabled. To disable them, use the
Scrollable(false)method of the Kendo UI for jQuery widget.
875
Telerik UI for ASP.NET Core
If the TabStrip has no fixed width and is placed in a fluid layout, it can re-check whether tab scrolling
is necessary or no longer required. To enable this option, execute the resize()method of the Kendo
UI TabStrip for jQuery upon window.resize. The resize method will also render the right scroll
button if the last and selected tab becomes invisible as a result of TabStrip shrinking.
<div style="width: 150px;">
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.Content(@<text>
<p>Rainy weather in Paris.</p>
</text>);
tabstrip.Add().Text("Sofia")
.Content(@<text>
<p>Sunny weather in Sofia.</p>
</text>);
})
)
</div>
The following example demonstrates how to use the Selected() configuration method.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.Content(@<text>
<p>Rainy weather in Paris.</p>
</text>);
tabstrip.Add().Text("Sofia")
.Selected(true)
.Content(@<text>
<p>Sunny weather in Sofia.</p>
</text>);
})
)
See Also
Scrollable Tabs by the TabStrip HtmlHelper for ASP.NET Core (Demo)
876
Telerik UI for ASP.NET Core
877
Telerik UI for ASP.NET Core
Tab Content
The TabStrip provides options for loading and configuring its tab content area.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.Content(@<text>
<p>Rainy weather in Paris.</p>
</text>);
tabstrip.Add().Text("Sofia")
.Content(@<text>
<p>Sunny weather in Sofia.</p>
</text>);
})
)
The following example demonstrates how to load the tab content asynchronously by using AJAX.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.LoadContentFrom(Url.Action("Paris", "Home"));
tabstrip.Add().Text("Sofia")
.LoadContentFrom(Url.Action("Sofia", "Home"));
})
)
Scrollable Content
By default, the containers of the TabStrip content are scrollable which enables a TabStrip with a
fixed height and large content that cannot fit to display scrollbars. You can also disable the scrolling
of the TabStrip content which is useful when the TabStrip hosts a widget (such as a Menu) that
878
Telerik UI for ASP.NET Core
needs to overflow the TabStrip. To disable the scrolling of the TabStrip content, use the
Scrollable(false)method of the Kendo UI for jQuery widget.
Depending on the browser, you can reset the scroll position of the content when the active tab is
changed. To persist the scroll position, use the selectevent of the Kendo UI for jQuery widget to
save the current scroll position and then the activateevent to restore it.
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Scrollable(false)
.Items(tabstrip =>
{
tabstrip.Add().Text("Paris")
.LoadContentFrom(Url.Action("Paris", "Home"));
tabstrip.Add().Text("Sofia")
.LoadContentFrom(Url.Action("Sofia", "Home"));
})
)
See Also
Loading Content with AJAX in the TabStrip HtmlHelper for ASP.NET Core (Demo)
Server-Side API
879
Telerik UI for ASP.NET Core
TabStrip Accessibility
The TabStrip is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The TabStrip is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The TabStrip supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the TabStrip HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the TabStrip HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
880
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the TabStrip is always available.
For a complete example, refer to the demo on keyboard navigation of the TabStrip.
See Also
Keyboard Navigation in the TabStrip HtmlHelper for ASP.NET Core (Demo)
Accessibility in the TabStrip HtmlHelper for ASP.NET Core
881
Telerik UI for ASP.NET Core
Timeline Overview
The Telerik UI Timeline HtmlHelper for ASP.NET Core is a server-side wrapper for the Kendo UI
Timeline widget.
The Timeline widget displays a collection of events and their data in a chronological succession for
each year.
You can scroll through the events and collapse/expand them. The events order can be vertical or
horizontal, and you can customize their templates, as well as respond to events and use API control
the widget behavior. You can also control the format of the rendered date for the event. If you
provide a list of actions, they will be rendered as links after the description and images.
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.DataDateField("EventDate")
882
Telerik UI for ASP.NET Core
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.Orientation("vertical") // defines the layout of the widget
.AlternatingMode() // renders the events on both sides of the axis in vertical
mode
.CollapsibleEvents() // starts all events collapsed in vertical mode
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Barcelona \u0026 Tenerife",
Subtitle = "May 15, 2015",
Description = "First event description.",
EventDate = new System.DateTime(2015, 4, 15),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 1, 27),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
events.Add(new TimelineEventModel()
{
Title = "Malta, a Country of Кnights",
Subtitle = "My second trip this year",
Description = "Third event description.",
EventDate = new System.DateTime(2015, 5, 25),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Malta/Bibliotheca-Natio
nal-Library_Marie-Lan-Nguyen.JPG?width=500&height=500" }
883
Telerik UI for ASP.NET Core
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
return Json(events);
}
}
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; } // this field name must be "src"
}
public class TimelineEventActionModel
{
public string text { get; set; } // this field name must be "text"
public string url { get; set; } // this field name must be "url"
}
Events
For a complete example on the Timeline events, refer to the demo on using the events of the Timeline
in ASP.NET Core.
You can provide an event handler through its JavaScript function name, or by specifying an inline
function in a template.
884
Telerik UI for ASP.NET Core
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.Events(ev =>
{
ev.Change("onChange");
ev.Navigate("onNavigate");
ev.DataBound("onDataBound");
ev.ActionClick("onActionClick");
})
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline")) // see the first example
in this article for a sample data source
)
<script>
function onChange(e) {
console.log("OnChange: " + e.dataItem.Title);
}
function onNavigate(e) {
console.log("OnNavigate: " + e.action);
}
function onActionClick(e) {
console.log("OnActionClick: " + e.element.text());
}
function onDataBound(e) {
console.log("OnDataBound: " + e.sender.dataSource.view().length);
}
</script>
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.Events(e =>
e.Change(@<text>
function(e) {
// Handle the Change event inline.
}
</text>)
.Navigate(@<text>
function(e) {
// Handle the Navigate event inline.
}
</text>)
)
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
885
Telerik UI for ASP.NET Core
.DataActionsField("Actions")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline")) // see the first example
in this article for a sample data source
)
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.Orientation("horizontal")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline")) // see the first example
in this article for a sample data source
)
<button onclick="buttonClick();">Go to next event</button>
<script>
function buttonClick() {
var timeline = $("#Timeline").data("kendoTimeline");
timeline.next();
}
</script>
See Also
Basic Usage of the Timeline (Demo)
Using the Events of the Timeline (Demo)
Applying the Timeline API (Demo)
JavaScript API Reference of the Timeline
886
Telerik UI for ASP.NET Core
Actions
The Timeline can render links (<a> tags) for the items from the Actions collection in its data
source, so the user can navigate to the specific pages.
The href attribute of an action will be set to the value of the src field of the action literal, and the
text will come from the text field.
The example below shows how you can a few actions actions for one event.
@(Html.Kendo().Timeline<Kendo.Mvc.Examples.Models.TimelineEventModel>()
.Name("Timeline")
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataActionsField("Actions")
.Orientation("horizontal")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Summer trip in Europe",
Subtitle = "May 15, 2015",
Description = "Lorem ipsum dolor sit amet",
EventDate = new System.DateTime(2015, 6, 25),
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" },
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 1, 27),
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
return Json(events);
}
}
887
Telerik UI for ASP.NET Core
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventActionModel
{
public string text { get; set; } // this field name must be "text"
public string url { get; set; } // this field name must be "url"
}
See Also
Basic Usage of the Timeline (Demo)
888
Telerik UI for ASP.NET Core
Images
The Timeline can render an <img /> tag for the first item from the Images collection in its data
source. Its src attribute will be set to the value of the src field of the image literal.
The example below shows how you can add an image for the events.
If you want to show more than one image, you need to customize the template of the Timeline.
@(Html.Kendo().Timeline<Kendo.Mvc.Examples.Models.TimelineEventModel>()
.Name("Timeline")
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.Orientation("vertical")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Summer trip in Europe",
Subtitle = "May 15, 2015",
Description = "Lorem ipsum dolor sit amet",
EventDate = new System.DateTime(2015, 5, 25),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 2, 27),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
}
});
return Json(events);
}
}
889
Telerik UI for ASP.NET Core
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; } // this field name must be "src"
}
See Also
Templates in the Timeline
Basic Usage of the Timeline (Demo)
890
Telerik UI for ASP.NET Core
Orientation
The Timeline can render its events in a verticalor horizontallist.
Vertical
By default, the timeline is vertical, with events arranged on one side of the axis.
You can have the events render alternatingly on both sides of the axis by adding its
.AlternatingMode() option.
If you add the .CollapsibleEvents() option, all events will start out collapsed (by default, all
events are expanded). The user can then expand a particular event to see more than its title and
subtitle.
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.Orientation("vertical") // defines the layout of the widget
.AlternatingMode() // renders the events on both sides of the axis in vertical
mode
.CollapsibleEvents() // starts all events collapsed in vertical mode
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Barcelona \u0026 Tenerife",
Subtitle = "May 15, 2015",
Description = "First event description.",
EventDate = new System.DateTime(2015, 4, 15),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" }
}
});
events.Add(new TimelineEventModel()
{
891
Telerik UI for ASP.NET Core
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 1, 27),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
events.Add(new TimelineEventModel()
{
Title = "Malta, a Country of Кnights",
Subtitle = "My second trip this year",
Description = "Third event description.",
EventDate = new System.DateTime(2015, 5, 25),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Malta/Bibliotheca-Natio
nal-Library_Marie-Lan-Nguyen.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
return Json(events);
}
}
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; } // this field name must be "src"
}
public class TimelineEventActionModel
{
public string text { get; set; } // this field name must be "text"
public string url { get; set; } // this field name must be "url"
}
Horizontal
892
Telerik UI for ASP.NET Core
In the horizontal mode, the timeline renders buttons the user can click or tap to navigate between
periods. There is always one rendered event below the time axis, and the user can select another to
reveal its details.
The horizontal mode renders the event details on demand (only when they are selected), and is
responsive (renders as many of the events as there is room on the axis for).
Alternating rendering and collapsing is not available for the events in this mode.
@(Html.Kendo().Timeline<MyApp.Models.TimelineEventModel>()
.Name("Timeline")
.Orientation("horizontal") // defines the layout of the widget
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Barcelona \u0026 Tenerife",
Subtitle = "May 15, 2015",
Description = "First event description.",
EventDate = new System.DateTime(2015, 4, 15),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 1, 27),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
893
Telerik UI for ASP.NET Core
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
events.Add(new TimelineEventModel()
{
Title = "Malta, a Country of Кnights",
Subtitle = "My second trip this year",
Description = "Third event description.",
EventDate = new System.DateTime(2015, 5, 25),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Malta/Bibliotheca-Natio
nal-Library_Marie-Lan-Nguyen.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
return Json(events);
}
}
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; } // this field name must be "src"
}
public class TimelineEventActionModel
{
public string text { get; set; } // this field name must be "text"
public string url { get; set; } // this field name must be "url"
}
See Also
Horizontal Orientation of the Timeline (Demo)
894
Telerik UI for ASP.NET Core
Templates
The Timeline lets you define your own template for rendering the events data, so you can customize
it to your needs instead of using the default card.
You can find a live example in the Templates demo of the Timeline.
The following example shows how you can customize the template of the timeline - to show more
than one image and how you can use custom fields from your model that would not be recognized
by the default template. The classes and HTML structure in this example mimic the default card
template (except the custom field).
@(Html.Kendo().Timeline<Kendo.Mvc.Examples.Models.TimelineEventModel>()
.Name("Timeline")
.EventTemplateId("eventTemplate")
.Orientation("horizontal")
.Dateformat("MMMM yyyy")
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubTitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.DataSource(dt => dt.Read("GetTimelineData", "Timeline"))
)
<script id="eventTemplate" type="text/x-kendo-template">
<div class="k-card-header">
<h5 class="k-card-title">#= data.Title #</h5>
<h6 class="k-card-subtitle"><strong>#= kendo.toString(data.EventDate, "MMM d,
yyyy")#</strong></h6>
</div>
<div class="k-card-body">
<div class="k-card-description">
<p>#= data.Description #</p>
<div class="imageContainer">
# for (var i = 0; i < data.Images.length; i++) { #
<img src="#= data.Images[i].src #" class="k-card-image">
# } #
</div>
</div>
</div>
<p>I was with #=data.Friends#</p>
<div class="k-card-actions">
<a class="k-button k-flat k-primary" href="#= data.Actions[0].url #"
target="_blank">#= data.Actions[0].text #</a>
</div>
</script>
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
895
Telerik UI for ASP.NET Core
events.Add(new TimelineEventModel() {
Title = "Summer trip in Europe",
Subtitle = "May 15, 2015",
Description = "Lorem ipsum dolor sit amet",
EventDate = new System.DateTime(2015, 5, 25),
Friends = "John and Maria",
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" },
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Malta/Bibliotheca-Natio
nal-Library_Marie-Lan-Nguyen.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" },
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 2, 27),
Friends = "Mandy",
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
return Json(events);
}
}
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public string Friends { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; }
896
Telerik UI for ASP.NET Core
}
public class TimelineEventActionModel
{
public string text { get; set; }
public string url { get; set; }
}
See Also
Templates in the Timeline (Demo)
JavaScript API Reference of the Timeline
897
Telerik UI for ASP.NET Core
For a runnable example, refer to the demo on binding to a shared data source.
The following example demonstrates how to bind two Telerik UI for ASP.NET Core widgets to the
same data source. Changes done from one of the widgets is automatically reflected in the data
source and UI of the other widget.
@(Html.Kendo().DataSource<Kendo.Mvc.Examples.Models.TimelineEventModel>()
.Name("sharedDataSource")
.Custom(dataSource => dataSource
.Transport(tr=>tr.Read(read => read.Action("GetEvents", "TimelineEvents")))
)
)
@(Html.Kendo().Timeline<Kendo.Mvc.Examples.Models.TimelineEventModel>()
.Name("Timeline")
.DataDateField("EventDate")
.DataDescriptionField("Description")
.DataSubtitleField("Subtitle")
.DataTitleField("Title")
.DataImagesField("Images")
.DataActionsField("Actions")
.Orientation(TimelineOrientation.Vertical)
.AlternatingMode()
.CollapsibleEvents()
.DataSource("sharedDataSource")
)
@(Html.Kendo().DropDownList()
.Name("titles")
.DataTextField("Title")
.DataValueField("Title")
.DataSource("sharedDataSource")
.OptionLabel("Select an item...")
.Value("Barcelona & Tenerife")
)
See Also
Bindig to a Shared DataSource (Demo)
JavaScript API Reference of the Timeline
898
Telerik UI for ASP.NET Core
The ToolBar is designed to hold different types of controls such as buttons, button groups, toggle
buttons, split buttons, and other customized elements. The ToolBar consists of the ToolBar wrapper,
overflow anchor, and command overflow popup main areas. The wrapper holds all commands that
can be placed within the available container width. The ones that have no space to fit are moved to
the command overflow popup.
@(Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button");
items.Add().Type(CommandType.Button).Text("Toggle Button").Togglable(true);
items.Add().Type(CommandType.SplitButton).Text("Insert").MenuButtons(menuButtons =>
{
menuButtons.Add().Text("Insert above").Icon("insert-up");
menuButtons.Add().Text("Insert between").Icon("insert-middle");
menuButtons.Add().Text("Insert below").Icon("insert-down");
});
})
)
public class ToolBarController : Controller
{
public ActionResult Index()
{
return View();
}
}
Basic Configuration
The following example demonstrates the basic configuration of the ToolBar HtmlHelper.
@(Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button
1").Id("button1").Click("buttonClickHandler");
items.Add().Type(CommandType.Button).Text("Button
899
Telerik UI for ASP.NET Core
2").Id("button2").Click("buttonClickHandler");
items.Add().Type(CommandType.Separator);
items.Add().Type(CommandType.Button).Togglable(true).Text("Toggle
1").Id("toggle1").Toggle("buttonToggleHandler");
items.Add().Type(CommandType.Button).Togglable(true).Text("Toggle
2").Id("toggle2").Toggle("buttonToggleHandler");
items.Add().Type(CommandType.Separator);
items.Add().Template("<input id='dropdown' style='width: 150px;'
/>").Overflow(ShowInOverflowPopup.Never);
items.Add().Type(CommandType.SplitButton).Text("Split
Button").Id("mainButton").Click("splitButtonClickHandler").MenuButtons(menuButtons =>
{
menuButtons.Add().Text("Action 1").Id("action1");
menuButtons.Add().Text("Action 2").Id("action2");
menuButtons.Add().Text("Action 3").Id("action3");
});
items.Add().Type(CommandType.Separator);
items.Add().Type(CommandType.ButtonGroup).Buttons(buttons =>
{
buttons.Add().Text("Radio
1").Id("radio1").Togglable(true).Group("radio").Toggle("buttonToggleHandler");
buttons.Add().Text("Radio
2").Id("radio2").Togglable(true).Group("radio").Toggle("buttonToggleHandler");
buttons.Add().Text("Radio
3").Id("radio3").Togglable(true).Group("radio").Toggle("buttonToggleHandler");
});
items.Add().Type(CommandType.Button).Text("Overflow
button").Id("overflowButton").Overflow(ShowInOverflowPopup.Always);
})
.Events(e =>
e.Click("onClick").Toggle("onToggle").Open("onOpen").Close("onClose").OverflowOpen("on
OverflowOpen").OverflowClose("onOverflowClose"))
)
<script type="text/javascript">
$(function() {
// Initialize a DropDownList in the template of a ToolBar item.
$("#dropdown").kendoDropDownList({
optionLabel: "Paragraph",
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Heading 1", value: 1 },
{ text: "Heading 2", value: 2 },
{ text: "Heading 3", value: 3 },
{ text: "Title", value: 4 },
{ text: "Subtitle", value: 5 },
]
});
// The Name() of the ToolBar is used to get its client-side instance.
var toolbar = $("#ToolBar").data("kendoToolBar");
});
</script>
900
Telerik UI for ASP.NET Core
Events
For a complete example on basic ToolBar events, refer to the demo on using the events of the ToolBar.
See Also
Basic Usage of the ToolBar HtmlHelper for ASP.NET Core (Demo)
Using the API of the ToolBar HtmlHelper for ASP.NET Core (Demo)
ToolBar Server-Side API
ToolBar Client-Side API
901
Telerik UI for ASP.NET Core
Spacer
The Spacer command type moves the tools that are declared after it to the right side of the ToolBar.
@(Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button 1").Id("button1");
items.Add().Type(CommandType.Spacer);
items.Add().Type(CommandType.Button).Text("Button 2").Id("button2");
})
)
You can use multiple spacers to create an equal amount of space between several tools.
@(Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button 1").Id("button1");
items.Add().Type(CommandType.Spacer);
items.Add().Type(CommandType.Button).Text("Button 2").Id("button2");
items.Add().Type(CommandType.Spacer);
items.Add().Type(CommandType.Button).Text("Button 3").Id("button3");
})
)
See Also
Server-Side API
902
Telerik UI for ASP.NET Core
Manual Closing
The ToolBar provides options for closing its popup from a button click event in a template.
@(Html.Kendo().ToolBar()
.Name("toolbar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button");
items.Add().Template("<a class='k-item k-state-default ng-scope' >Test</a>")
.OverflowTemplate("<button onclick='action()' class='btn' >Test</button>")
.Overflow(ShowInOverflowPopup.Always);
}
)
)
<script>
function action() {
$("#toolbar").data("kendoToolBar").popup.close();
}
</script>
public class ToolBarController : Controller
{
public IActionResult Index()
{
return View();
}
}
See Also
Server-Side API
903
Telerik UI for ASP.NET Core
<style>
.fa.k-sprite,
.fa.k-sprite::before {
font-size: 14px;
line-height: 16px;
}
</style>
public class ToolBarController : Controller
{
public IActionResult Index()
{
return View();
}
}
See Also
Server-Side API
904
Telerik UI for ASP.NET Core
@(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_TreeViewData", "TreeView")
)
)
)
public static IList<HierarchicalViewModel> GetHierarchicalData()
{
var result = new List<HierarchicalViewModel>()
{
new HierarchicalViewModel() { ID = 1, ParendID = null, HasChildren = true, Name
= "Parent item" },
new HierarchicalViewModel() { ID = 2, ParendID = 1, HasChildren = true, Name =
"Parent item" },
new HierarchicalViewModel() { ID = 3, ParendID = 1, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 4, ParendID = 2, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 5, ParendID = 2, HasChildren = false, Name =
"Item" }
};
return result;
}
public IActionResult Read_TreeViewData(int? id)
{
var result = GetHierarchicalData()
.Where(x => id.HasValue ? x.ParendID == id : x.ParendID == null)
.Select(item => new {
id = item.ID,
Name = item.Name,
expanded = item.Expanded,
imageUrl = item.ImageUrl,
hasChildren = item.HasChildren
});
905
Telerik UI for ASP.NET Core
return Json(result);
}
Basic Configuration
The following example demonstrates the basic configuration of the TreeView HtmlHelper and how
to get the TreeView instance.
@(Html.Kendo().TreeView()
.Name("treeview")
.Checkboxes(true)
.DragAndDrop(true)
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Employees", "TreeView")
)
)
)
<script type="text/javascript">
$(function () {
// The Name() of the TreeView is used to get its client-side instance.
var treeview = $("#treeview").data("kendoTreeView");
console.log(treeview);
});
</script>
Events
The following example demonstrates the available TreeView events and how an event handler could
be implemented for each of them. For a complete example on basic TreeView events, refer to the
demo on using the events of the TreeView.
@(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.Checkboxes(true)
.DragAndDrop(true)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Employees", "TreeView")
)
)
.Events(events => eventsChange("onChange")
906
Telerik UI for ASP.NET Core
.Select("onSelect")
.Check("onCheck")
.Collapse("onCollapse")
.Expand("onExpand")
.DragStart("onDragStart")
.Drag("onDrag")
.DragEnd("onDragEnd")
.Drop("onDrop")
)
)
<script type="text/javascript">
function onChange(e) {
console.log('Selected node changed to:', e.sender.select());
}
function onSelect(e) {
console.log('Selected node:', e.node);
}
function onCheck(e) {
console.log('Checked node:', e.node);
}
function onCollapse(e) {
console.log('Collapsed node:', e.node);
}
function onExpand(e) {
console.log('Expanded node:', e.node);
}
function onDragStart(e) {
console.log('Started dragging:', e.sourceNode);
}
function onDrag(e) {
console.log("Dragging:", e.sourceNode);
}
function onDragEnd(e) {
console.log("Finished dragging:", e.sourceNode);
}
function onDrop(e) {
console.log("Dropped:", e.sourceNode);
}
</script>
See Also
Basic Usage of the TreeView HtmlHelper for ASP.NET Core (Demo)
Using the API of the TreeView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
907
Telerik UI for ASP.NET Core
TreeView Binding
The TreeView HTML helper provides support for declaratively defining its items and for local (on the
server) and remote (using a DataSource configuration object) binding.
The following example demonstrates how to configure a TreeView with three levels of hierarchy.
@(Html.Kendo().TreeView()
.Name("treeview")
.Items(treeview =>
{
treeview.Add().Text("My Web Site")
.Items(root =>
{
root.Add().Text("images")
.Items(images =>
{
images.Add().Text("logo.png");
images.Add().Text("body-back.png");
});
root.Add().Text("about.html");
root.Add().Text("contacts.html");
});
})
)
@(Html.Kendo().TreeView()
.Name("treeview-left")
.BindTo((IEnumerable<TreeViewItemModel>)ViewBag.treeData)
)
public ActionResult Local_Data_Binding()
{
ViewBag.treeData = GetData();
return View();
}
private IEnumerable<TreeViewItemModel> GetData()
{
List<TreeViewItemModel> inline = new List<TreeViewItemModel>
{
908
Telerik UI for ASP.NET Core
new TreeViewItemModel
{
Text = "Furniture",
Items = new List<TreeViewItemModel>
{
new TreeViewItemModel()
{
Text = "Tables & Chairs"
},
new TreeViewItemModel
{
Text = "Sofas"
},
new TreeViewItemModel
{
Text = "Occasional Furniture"
}
}
},
new TreeViewItemModel
{
Text = "Decor",
Items = new List<TreeViewItemModel>
{
new TreeViewItemModel()
{
Text = "Bed Linen"
},
new TreeViewItemModel
{
Text = "Curtains & Blinds"
},
new TreeViewItemModel
{
Text = "Carpets"
}
}
}
};
return inline;
}
@(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_TreeViewData", "TreeView")
)
)
)
909
Telerik UI for ASP.NET Core
public static IList<HierarchicalViewModel> GetHierarchicalData()
{
var result = new List<HierarchicalViewModel>()
{
new HierarchicalViewModel() { ID = 1, ParendID = null, HasChildren = true, Name
= "Parent item" },
new HierarchicalViewModel() { ID = 2, ParendID = 1, HasChildren = true, Name =
"Parent item" },
new HierarchicalViewModel() { ID = 3, ParendID = 1, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 4, ParendID = 2, HasChildren = false, Name =
"Item" },
new HierarchicalViewModel() { ID = 5, ParendID = 2, HasChildren = false, Name =
"Item" }
};
return result;
}
public IActionResult Read_TreeViewData(int? id)
{
var result = GetHierarchicalData()
.Where(x => id.HasValue ? x.ParendID == id : x.ParendID == null)
.Select(item => new {
id = item.ID,
Name = item.Name,
expanded = item.Expanded,
imageUrl = item.ImageUrl,
hasChildren = item.HasChildren
});
return Json(result);
}
See Also
Local Data Binding by the TreeView HtmlHelper for ASP.NET Core (Demo)
Remote Data Binding by the TreeView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
910
Telerik UI for ASP.NET Core
Item Properties
When you bind the TreeView through the DataSource() configuration option, each item can acquire
specific properties.
The following JSON example demonstrates how to pass item properties to the TreeView. You can
configure the text, imageUrl, spriteCssClass, and url fields through the DataTextField,
DataImageUrlField, DataSpriteCssClassField, and DataUrlFieldoptions respectively.
{
"text":"Item text",
// If specified, renders the item as a link (<a href=""></a>)
"url":"/",
// Renders a <img class="k-image" src="/images/icon.png" />
"imageUrl":"/images/icon.png",
// Renders a <span class="k-sprite icon save" />
"spriteCssClass":"icon save",
// Specifies whether the node text should be encoded or not.
// Useful when rendering node-specific HTML.
"encoded":false,
// Specifies whether the item is initially expanded.
// Applicable when the item has child nodes.
"expanded":true,
// Specifies whether the item checkbox is initially checked.
// Applicable for items with checkboxes using the default checkbox template.
"checked":true,
// Specifies whether the item is initially selected.
"selected":true,
// Indicates the sub-items of the item.
"items":[{
"text":"Subitem text"
}]
}
See Also
Server-Side API
911
Telerik UI for ASP.NET Core
The functionality also features tooltips that help users indicate where the node will be dropped.
The following example demonstrates how to enable the drag-and-drop functionality for the TreeView
nodes.
@(Html.Kendo().TreeView()
.Name("treeview")
.DragAndDrop(true)
.DataTextField("Name")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Employees", "TreeView")
)
)
)
See Also
Dragging and Dropping in the TreeView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
912
Telerik UI for ASP.NET Core
TreeView Checkboxes
The checkboxes functionality in the TreeView provides various configuration options.
@(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.Checkboxes(true)
.DataSource(dataSource => dataSource
.Read(read => read
.Action("Read_TreeViewData", "TreeView")
)
)
)
See Also
Checkboxes in the TreeView HtmlHelper for ASP.NET Core (Demo)
Server-Side API
913
Telerik UI for ASP.NET Core
TreeView Accessibility
The TreeView is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The TreeView is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The TreeView supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the TreeView HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the TreeView HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
914
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the TreeView is always available.
For a complete example, refer to the demo on keyboard navigation of the TreeView.
See Also
Keyboard Navigation in the TreeView HtmlHelper for ASP.NET Core (Demo)
Accessibility in the TreeView HtmlHelper for ASP.NET Core
915
Telerik UI for ASP.NET Core
The PDFViewer displays PDF files in the browser and consists of a toolbar and a scrollable container
that wraps the page elements. The default tools collection includes the pager, open, and download
tools. For processing files, it supports the PDF.JS Processing and Telerik DPL Processing libraries.
Among the key features the PDFViewer provides are the selection of a PDF processing library, a
built-in paging mechanism, virtualization capabilities, a built-in default toolbar collection, and
responsive capabilities and page scaling.
Using PDF.JS
The following example demonstrates how to initialize the PDFViewer by using PDF.JS.
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script>
<script>
window.pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.worker.js';
</script>
@(Html.Kendo().PDFViewer()
.Name("pdfviewer") // The name of the PDFViewer is mandatory. It specifies the
"id" attribute of the widget.
.PdfjsProcessing(pdf => pdf
.File(Url.Content("~/Content/web/pdfViewer/sample.pdf"))
)
.Height(1200)
)
@(Html.Kendo().PDFViewer()
.Name("pdfviewer") // The name of the PDFViewer is mandatory. It specifies the
"id" attribute of the widget.
.DplProcessing(dpl => {
dpl.Read(r => r.Url(Url.Action("GetInitialPdf", "PdfViewer")));
dpl.Upload(upload => upload.Url(Url.Action("GetPdf",
916
Telerik UI for ASP.NET Core
"PdfViewer")).SaveField("file"));
dpl.LoadOnDemand(true);
})
.Toolbar(toolbar =>
toolbar.Items(items =>
{
items.Add().Command("PageChangeCommand").Type("pager").Name("pager");
items.Add().Name("spacer").Type("spacer");
items.Add().Command("OpenCommand").Type("button").Name("open").Icon("folder-open");
})
)
.Height(1200)
)
Events
For a complete example on basic PDFViewer events, refer to the demo on using the events of the
PDFViewer.
See Also
Basic Usage of the PDFViewer HtmlHelper for ASP.NET Core (Demo)
Using the API of the PDFViewer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
917
Telerik UI for ASP.NET Core
PDFjs Processing
By default, if no processing configuration is defined, the PDFViewer uses the PDF.js library.
Requirements
Add the PDF.js library scripts to the page.
Basic Configuration
The following example demonstrates how to configure the PDFViewer to use PDF.js processing.
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script>
<script>
window.pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.worker.js';
</script>
@(Html.Kendo().PDFViewer()
.Name("pdfviewer")
.PdfjsProcessing(pdf => pdf
.File(Url.Content("~/Content/web/pdfViewer/sample.pdf"))
)
.Height(1200)
)
Browser Support
PDF.js processing is not supported in Internet Explorer 9. To work properly in that browser version,
PDF.js requires additional configuration.
<script>
// Specify the workerSrc property for Internet Explorer support.
window.pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.worker.js';
</script>
See Also
Server-Side API
918
Telerik UI for ASP.NET Core
DPL Processing
You can configure the PDFViewer to use the Telerik Document Processing libraryfor PDF processing.
DPL Processing is in its beta version and has the following limitations:
Requirements
DPL Processing depends on the Telerik.Web.PDF assembly.
To use DPL Processing in a project, it must target 4.6.2 .NET Framework.
The Read.Url option is mandatory, the Open and Download options are mandatory if the
respective tools are displayed in the toolbar.
Basic Configuration
The following example demonstrates how to configure the PDFViewer to use DPL Processing.
@(Html.Kendo().PDFViewer()
.Name("pdfviewer")
.DplProcessing(dpl => {
dpl.Read(r => r.Url(Url.Action("GetInitialPdf", "PdfViewer")));
dpl.Upload(upload => upload.Url(Url.Action("GetPdf",
"PdfViewer")).SaveField("file"));
dpl.LoadOnDemand(true);
})
.Toolbar(toolbar =>
toolbar.Items(items =>
{
items.Add().Command("PageChangeCommand").Type("pager").Name("pager");
items.Add().Name("spacer").Type("spacer");
items.Add().Command("OpenCommand").Type("button").Name("open").Icon("folder-open");
})
)
.Height(1200)
)
See Also
DPL Processing by the PDFViewer HtmlHelper for ASP.NET Core (Demo)
Server-Side API
919
Telerik UI for ASP.NET Core
This approach enables you to use the ToolBar client-side APIand perform all available
customizations.
You can control the number and type of the rendered tools by initializing the items collection only
with the tools that you require. For the full list of configuration options, refer to the client-side API of
the ToolBar items.
pager
zoom
toggleSelection
search
open
download
print
Running an Adblock extension in Chrome might treat the new browser tab for the print dialog as a
potential ad and block it.
The following example demonstrates basic configuration options for the PDFViewer toolbar tools.
You can also add spacer elements, in order to group a preferable set of tools.
@(Html.Kendo().PDFViewer().Name("pdfviewer")
.Toolbar(toolbar =>
toolbar.Items(items =>
{
items.Add().Name("pager");
items.Add().Name("spacer");
items.Add().Name("zoom");
items.Add().Name("toggleSelection");
items.Add().Name("spacer");
items.Add().Name("search");
items.Add().Name("open");
items.Add().Name("download");
items.Add().Name("print");
})
)
)
You can also use the add and remove client-side API methods to programmatically manage the
rendered tools in the PDFViewer.
@(Html.Kendo().PDFViewer()
.Name("pdfviewer")
920
Telerik UI for ASP.NET Core
)
<script>
var pdfviewer = $("#pdfViewer").getKendoPDFViewer();
var printToolElement = $(".k-toolbar").find('a[title="Print"]');
pdfviewer.toolbar.remove(printToolElement);
</script>
See Also
Basic Usage of the PDFViewer HtmlHelper for ASP.NET Core (Demo)
ToolBar Client-Side API
PDFViewer Server-Side API
921
Telerik UI for ASP.NET Core
PDFViewer Accessibility
The PDFViewer is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The PDFViewer is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The PDFViewer supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the PDFViewer HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the PDFViewer HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
922
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the PDFViewer is always available.
For a complete example, refer to the demo on keyboard navigation of the PDFViewer.
See Also
Keyboard Navigation in the PDFViewer HtmlHelper for ASP.NET Core (Demo)
Accessibility in the PDFViewer HtmlHelper for ASP.NET Core
923
Telerik UI for ASP.NET Core
The Calendar renders a graphical calendar that provides navigation and selection functionalities.
@(Html.Kendo().Calendar()
.Name("calendar") // The name of the Calendar is mandatory. It specifies the
"id" attribute of the Calendar.
.Min(new DateTime(2010, 1, 1, 10, 0, 0)) // Set the min time of the Calendar.
.Max(new DateTime(2020, 1, 1, 20, 0, 0)) // Set the min date of the Calendar.
.Value(DateTime.Now) // Set the value of the Calendar.
)
Events
You can subscribe to all Calendar events. For a complete example on basic Calendar events, refer to
the demo on using the events of the Calendar.
@(Html.Kendo().Calendar()
.Name("calendar")
.Events(e => e
.Change("calendar_change")
.Navigate("calendar_navigate")
)
)
<script>
924
Telerik UI for ASP.NET Core
function calendar_navigate(e) {
// Handle the navigate event.
var calendar = e.sender;
}
function calendar_change(e) {
// Alerts the selected date with kendo.alert().
var calendar = e.sender;
kendo.alert(calendar.value());
}
</script>
@(Html.Kendo().Calendar()
.Name("calendar")
.Events(e => e
.Change(@<text>
function(e) {
// Handle the change event inline.
console.log(e.sender.value());
}
</text>)
.Navigate(@<text>
function(e) {
// Handle the navigate event inline.
console.log(e.sender);
}
</text>)
)
)
// Place the following after your Telerik UI Calendar for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the Calendar is used to get its client-side instance.
var calendar = $("#calendar").data("kendoCalendar");
});
</script>
See Also
Basic Usage of the Calendar HtmlHelper for ASP.NET Core (Demo)
Using the API of the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
925
Telerik UI for ASP.NET Core
Date Ranges
You can create a Calendar with a selected date and define a minimum and a maximum date.
As a result, the Calendar does not navigate to a date that is earlier than the specified minimum date
and also restricts the navigation up to the maximum date you specified.
@(Html.Kendo().Calendar()
.Name("calendar")
.Value(DateTime.Now)
.Min(new DateTime(1950, 1, 2))
.Max(new DateTime(2049, 12, 31)))
See Also
Server-Side API
926
Telerik UI for ASP.NET Core
Day Template
The Calendar enables you to customize the rendered day for the month view.
The following example demonstrates how to create a Calendar by using a custom template.
@(Html.Kendo().Calendar()
.Name("calendar")
.MonthTemplate(x=> x.Content("<div class='custom'><#=data.value#></div>")))
The template wraps the value in a <div> HTML element. The structure of the data object that is
passed to the template function:
data = {
date: date, // A date object corresponding to the current cell.
title: kendo.toString(date, "D"),
value: date.getDate(),
dateString: "2011/0/1" // A formatted date based on the yyyy/MM/dd format and a
zero-based month.
};
See Also
Customizing Templates in the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
927
Telerik UI for ASP.NET Core
Week Numbers
You can configure the Calendar to display the week number and also use the week number template
to customize the cells in the Week column.
@(Html.Kendo().Calendar()
.Name("calendar")
.WeekNumber(true)))
You can use these properties in the template to make additional calculations.
@(Html.Kendo().Calendar()
.Name("calendar")
.WeekNumber()
.MonthTemplate(x=> x.WeekNumber("<i>#= data.weekNumber #</i>"))
)
See Also
Rendering the Week Column in the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
928
Telerik UI for ASP.NET Core
Selection
The Calendar enables the user to make single, multiple, range-date, and week selections.
For a runnable example, refer to the demo on multiple selection in the Calendar HtmlHelper .
To perform the multiple date selection, the user can also use the keyboard:
@(Html.Kendo().Calendar()
.Name("calendar")
.Selectable("multiple")
)
The usage of the Shift key allows the user to select a range of dates in the same month or across
different months:
Shift + mouse-clicking specific dates—Selects all dates between the most recently selected
one (with Space or mouse click) and the clicked cell.
Shift + mouse clicking specific dates—If no previous selection was made, selects all dates
from the beginning to the clicked cell.
Week Selection
929
Telerik UI for ASP.NET Core
When the user clicks a specific week number, the Calendar selects the entire week. The week
selection functionality is a special case of range selection which starts from the first day of the week
and selects all dates to the end of the week.
See Also
Multiple Date Selection by the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
930
Telerik UI for ASP.NET Core
Disabled Dates
The Calendar allows you to disable certain days which are not intended to be selected by the end
user such as weekends, national holidays, and others.
Setting an Array
When you set an array, list the days that will be disabled by using the first letters from their names in
English.
@(Html.Kendo().Calendar()
.Name("calendar")
.Value(DateTime.Now)
.DisableDates(new[] {DayOfWeek.Monday })
)
Adding a Function
When you add a function, determine its return value as true for the date that is disabled.
@(Html.Kendo().Calendar()
.Name("calendar")
.Value(DateTime.Now)
.DisableDates("disabledDatesHandler")
)
<script>
function disabledDatesHandler(date) {
var disabled = [13, 14, 20, 21];
if (date && disabled.indexOf(date.getDate()) > -1) {
return true;
} else {
return false;
}
}
</script>
See Also
Disabling Dates in the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
931
Telerik UI for ASP.NET Core
Calendar Accessibility
The Calendar is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Calendar is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The Calendar supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the Calendar HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
932
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Calendar is based on the key-down events on the wrapper element of
the widget.
The logic assumes that everything the user does is in accordance with the currently focused date
cell and not the focused element of the browser.
Depending on selection mode (single or multiple), the Calendar behaves differently in terms of
selecting and navigating with the keyboard.
When the user applies the multiple date selection, the Calendar demonstrates the following
keyboard navigation behavior:
The focusing or selection of a date from another month does not navigate to the
corresponding month. The user can continue the selection of dates from the current view.
The pressing of Space or Enter on a specific date makes a single selection by deselecting
all other selected dates.
The pressing of Space or Enter on a specific date while the user is holding the Ctrl key
adds the date to the current selection. If the date is already selected, it is removed from the
selection.
The pressing of Shift + Enter or Space performs a range selection. It selects all dates
between the most recently selected date (with Space or Enter or a mouse click) and the
date that holds the focused cell.
The pressing of Shift + Up Arrow or Down Arrow extends the selection up or down one
row in the month view respectively.
The pressing of Shift + Right Arrow or Left Arrow adds the next or previous date to the
current selection respectively.
See Also
Keyboard Navigation by the Calendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
933
Telerik UI for ASP.NET Core
The Gantt displays a set of tasks and dependencies which are used to visualize project-planning
data. It provides a TreeList section where the user can edit the tasks, and sort and reorder them in a
grid-like fashion, and a Timeline section where the tasks and dependencies are visualized under an
adjustable time ruler. The user can resize, move, edit and remove them. The Gantt also supports the
display of the Timeline section in the day, week, and month views.
@(Html.Kendo().Gantt<TaskViewModel, DependencyViewModel>()
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.TaskID).Title("ID").Width(50);
columns.Bound(c => c.Title).Editable(true).Sortable(true);
columns.Bound(c => c.Start).Width(100).Editable(true).Sortable(true);
columns.Bound(c => c.End).Width(100).Editable(true).Sortable(true);
})
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
})
.Height(700)
.ShowWorkHours(false)
.ShowWorkDays(false)
.Snap(false)
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.Field(f => f.Expanded).DefaultValue(true);
})
.Read("ReadTasks", "Gantt")
.Create("CreateTask", "Gantt")
.Destroy("DestroyTask", "Gantt")
.Update("UpdateTask", "Gantt")
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
})
934
Telerik UI for ASP.NET Core
.Read("ReadDependencies", "Gantt")
.Create("CreateDependency", "Gantt")
.Destroy("DestroyDependency", "Gantt")
)
)
public partial class GanttController : Controller
{
private IGanttTaskService taskService;
private IGanttDependencyService dependencyService;
public GanttController(
IGanttTaskService ganttTaskService,
IGanttDependencyService ganttDependencyService)
{
taskService = ganttTaskService;
dependencyService = ganttDependencyService;
}
[Demo]
public ActionResult Index()
{
return View();
}
public virtual JsonResult ReadTasks([DataSourceRequest] DataSourceRequest
request)
{
return Json(taskService.GetAll().ToDataSourceResult(request));
}
public virtual JsonResult DestroyTask([DataSourceRequest] DataSourceRequest
request, TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Delete(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult CreateTask([DataSourceRequest] DataSourceRequest
request, TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Insert(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult UpdateTask([DataSourceRequest] DataSourceRequest
request, TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Update(task, ModelState);
}
935
Telerik UI for ASP.NET Core
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult ReadDependencies([DataSourceRequest]
DataSourceRequest request)
{
return Json(dependencyService.GetAll().ToDataSourceResult(request));
}
public virtual JsonResult DestroyDependency([DataSourceRequest]
DataSourceRequest request, DependencyViewModel dependency)
{
if (ModelState.IsValid)
{
dependencyService.Delete(dependency);
}
return Json(new[] { dependency }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult CreateDependency([DataSourceRequest]
DataSourceRequest request, DependencyViewModel dependency)
{
if (ModelState.IsValid)
{
dependencyService.Insert(dependency);
}
return Json(new[] { dependency }.ToDataSourceResult(request, ModelState));
}
}
Basic Configuration
The following example demonstrates the basic configuration of the Gantt HtmlHelper.
@(Html.Kendo().Gantt<TaskViewModel, DependencyViewModel>()
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.Title).Editable(true).Sortable(true);
columns.Resources("resources").Editable(true).Title("Assigned Resources");
columns.Bound(c => c.Start).Width(100).Editable(true).Sortable(true);
columns.Bound(c => c.End).Width(100).Editable(true).Sortable(true);
})
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
})
.Height(700)
.RowHeight(62)
.ShowWorkHours(false)
.ShowWorkDays(false)
.Snap(false)
.Pdf(pdf => pdf
.FileName("Kendo UI Gantt Export.pdf")
.ProxyURL(Url.Action("Pdf_Export_Save", "Gantt"))
936
Telerik UI for ASP.NET Core
)
.Resizable(true)
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.Field(f => f.Expanded).DefaultValue(true);
})
.Read("ReadTasks", "Gantt")
.Create("CreateTask", "Gantt")
.Destroy("DestroyTask", "Gantt")
.Update("UpdateTask", "Gantt")
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
})
.Read("ReadDependencies", "Gantt")
.Create("CreateDependency", "Gantt")
.Destroy("DestroyDependency", "Gantt")
)
.Resources(r => r
.Field("resources")
.DataColorField("Color")
.DataTextField("Name")
.DataSource(d => d
.Custom()
.Schema(s => s
.Model(m => m.Id("ID"))
.Data("Data")
)
.Transport(t =>
{
t.Read("ReadResources", "Gantt");
})
)
)
.Assignments<ResourceAssignmentViewModel>(a => a
.DataTaskIdField("TaskID")
.DataResourceIdField("ResourceID")
.DataValueField("Units")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.ID);
})
.Read("ReadAssignments", "Gantt")
.Create("CreateAssignment", "Gantt")
.Destroy("DestroyAssignment", "Gantt")
.Update("UpdateAssignment", "Gantt")
)
)
)
937
Telerik UI for ASP.NET Core
Columns
Resources
Templates
Accessibility
Events
For a complete example on basic Gantt events, refer to the demo on using the events of the Gantt.
// Place this after the Gantt for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The Name() of the Gantt is used to get its client-side instance.
var gantt = $("#gantt").data("kendoGantt");
});
</script>
See Also
Basic Usage of the Gantt HtmlHelper for ASP.NET Core (Demo)
Using the API of the Gantt HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
938
Telerik UI for ASP.NET Core
Data Binding
By default, the Telerik UI Gantt for ASP.NET MVC performs server-side requests ( HTTP and GET)
when doing paging, sorting, and filtering.
You can also render the view with the data for the tasks and dependences. You have to implement
the IGanttTask and IGanttDependency interfaces in the data models for the GanttTasks and
GantDependencies respectively.
The following example demonstrates how to bind the Gantt through the TaskViewModel.
public class TaskViewModel : IGanttTask
{
public int TaskID { get; set; }
public int? ParentID { get; set; }
public string Title { get; set; }
private DateTime start;
public DateTime Start
{
get
{
return start;
}
set
{
start = value.ToUniversalTime();
}
}
private DateTime end;
public DateTime End
{
get
{
return end;
}
set
{
end = value.ToUniversalTime();
}
}
public bool Summary { get; set; }
public bool Expanded { get; set; }
public decimal PercentComplete { get; set; }
public int OrderId { get; set; }
public GanttTask ToEntity()
{
939
Telerik UI for ASP.NET Core
return new GanttTask
{
ID = TaskID,
ParentID = ParentID,
Title = Title,
Start = Start,
End = End,
Summary = Summary,
Expanded = Expanded,
PercentComplete = PercentComplete,
OrderID = OrderId
};
}
}
The following example demonstrates how to bind the Gantt through the DependencyViewModel.
public class DependencyViewModel : IGanttDependency
{
public int DependencyID { get; set; }
public int PredecessorID { get; set; }
public int SuccessorID { get; set; }
public DependencyType Type { get; set; }
public GanttDependency ToEntity()
{
return new GanttDependency
{
ID = DependencyID,
PredecessorID = PredecessorID,
SuccessorID = SuccessorID,
Type = (int)Type
};
}
}
public IActionResult ServerBinding()
{
var sampleEntities = new SampleEntities();
ViewData["tasks"] = sampleEntities.GanttTasks
.ToList().Select(task => new TaskViewModel
{
TaskID = task.ID,
Title = task.Title,
Start = DateTime.SpecifyKind(task.Start, DateTimeKind.Utc),
End = DateTime.SpecifyKind(task.End, DateTimeKind.Utc),
ParentID = task.ParentID,
PercentComplete = task.PercentComplete,
OrderId = task.OrderID,
Expanded = task.Expanded,
940
Telerik UI for ASP.NET Core
Summary = task.Summary
}).AsQueryable();
ViewData["dependencies"] = sampleEntities.GanttDependencies
.ToList().Select(dependency => new DependencyViewModel
{
DependencyID = dependency.ID,
PredecessorID = dependency.PredecessorID,
SuccessorID = dependency.SuccessorID,
Type = (DependencyType)dependency.Type
}).AsQueryable();
return View();
}
@(Html.Kendo()
.Gantt<TaskViewModel,
DependencyViewModel>((IEnumerable<TaskViewModel>)ViewData["tasks"],
(IEnumerable<DependencyViewModel>)ViewData["dependencies"])
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.TaskID).Title("ID").Width(50);
columns.Bound("title").Editable(true).Sortable(true);
columns.Bound("start").Title("Start
Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(true).Sortable(true);
columns.Bound("end").Title("End
Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(true).Sortable(true);
})
.Editable(false)
.Height(400)
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.OrderId(f => f.OrderId);
m.Field(f => f.Expanded).DefaultValue(true);
})
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
m.Type(f => f.Type);
})
)
)
public IActionResult ServerBinding()
941
Telerik UI for ASP.NET Core
{
var sampleEntities = new SampleEntities();
ViewBag.Tasks = sampleEntities.GanttTasks
.ToList().Select(task => new TaskViewModel
{
TaskID = task.ID,
Title = task.Title,
Start = DateTime.SpecifyKind(task.Start, DateTimeKind.Utc),
End = DateTime.SpecifyKind(task.End, DateTimeKind.Utc),
ParentID = task.ParentID,
PercentComplete = task.PercentComplete,
OrderId = task.OrderID,
Expanded = task.Expanded,
Summary = task.Summary
}).AsQueryable();
ViewBag.Dependencies = sampleEntities.GanttDependencies
.ToList().Select(dependency => new DependencyViewModel
{
DependencyID = dependency.ID,
PredecessorID = dependency.PredecessorID,
SuccessorID = dependency.SuccessorID,
Type = (DependencyType)dependency.Type
}).AsQueryable();
return View();
}
@(Html.Kendo()
.Gantt<TaskViewModel,
DependencyViewModel>((IEnumerable<TaskViewModel>)ViewBag.Tasks,
(IEnumerable<DependencyViewModel>)ViewBag.Dependencies)
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.TaskID).Title("ID").Width(50);
columns.Bound("title").Editable(true).Sortable(true);
columns.Bound("start").Title("Start
Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(true).Sortable(true);
columns.Bound("end").Title("End
Time").Format("{0:MM/dd/yyyy}").Width(100).Editable(true).Sortable(true);
})
.Editable(false)
.Height(400)
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.OrderId(f => f.OrderId);
m.Field(f => f.Expanded).DefaultValue(true);
})
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
942
Telerik UI for ASP.NET Core
m.Type(f => f.Type);
})
)
)
See Also
Basic Usage of the Gantt HtmlHelper for ASP.NET Core (Demo)
Client-Side API
Server-Side API
943
Telerik UI for ASP.NET Core
Columns
The columns in the TreeList section of the Gantt can be individually configured. The following
configuration options are supported:
@(Html.Kendo().Gantt<TaskViewModel, DependencyViewModel>()
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.TaskID).Title("ID").Width(50);
columns.Bound(c => c.Title).Editable(true).Sortable(true);
columns.Bound(c => c.Start).Width(100).Editable(true).Sortable(true);
columns.Bound(c => c.End).Width(100).Editable(true).Sortable(true);
})
.Resizable(true)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.Field(f => f.Expanded).DefaultValue(true);
})
.Read("ReadTasks", "Gantt")
.Destroy("DestroyTask", "Gantt")
.Update(update => update.Action("UpdateTask", "Gantt").Data("onUpdateCreate"))
.Create(create => create.Action("CreateTask", "Gantt").Data("onUpdateCreate"))
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
})
.Read("ReadDependencies", "Gantt")
.Create("CreateDependency", "Gantt")
.Destroy("DestroyDependency", "Gantt")
)
)
<script>
// Send the dates for the newly creted/updated tasks as UTC strings
944
Telerik UI for ASP.NET Core
function onUpdateCreate(e) {
e.End = e.End.toISOString();
e.Start = e.Start.toISOString();
}
</script>
Column Resizing
The columns in the TreeList section of the Gantt can be resized by clicking on the drag handles
between the columns and dragging with the mouse. To enable this behavior, use the
.Resizable(true) configuration option of the Gantt.
See Also
Server-Side API
945
Telerik UI for ASP.NET Core
Resources
The Gantt allows you to assign resources to tasks. A resource is optional metadata that can be
associated with a Gantt task.
Assignements
An assignment is a one-to-one mapping between a Gantt task and a Gantt resource containing the
number of units for which a resource is assigned to a task.
The following example demonstrates how to set resources in the Gantt and how to map them to
tasks by setting assignments.
@(Html.Kendo().Gantt<TaskViewModel, DependencyViewModel>()
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.Title).Editable(true).Sortable(true);
columns.Resources("resources").Editable(true).Title("Assigned Resources");
})
.Views(views =>
{
views.DayView();
views.WeekView();
views.MonthView(monthView => monthView.Selected(true));
})
.Height(700)
.ShowWorkHours(false)
.ShowWorkDays(false)
.Snap(false)
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.ParentId(f => f.ParentID);
m.Field(f => f.Expanded).DefaultValue(true);
})
.Read("ReadTasks", "Gantt")
.Destroy("DestroyTask", "Gantt")
.Update(update => update.Action("UpdateTask", "Gantt").Data("onUpdateCreate"))
.Create(create => create.Action("CreateTask", "Gantt").Data("onUpdateCreate"))
)
.DependenciesDataSource(d => d
.Model(m =>
{
m.Id(f => f.DependencyID);
m.PredecessorId(f => f.PredecessorID);
m.SuccessorId(f => f.SuccessorID);
})
.Read("ReadDependencies", "Gantt")
.Create("CreateDependency", "Gantt")
946
Telerik UI for ASP.NET Core
.Destroy("DestroyDependency", "Gantt")
)
.Resources(r => r
.Field("resources")
.DataColorField("Color")
.DataTextField("Name")
.DataSource(d => d
.Custom()
.Schema(s => s
.Model(m => m.Id("ID"))
.Data("Data")
)
.Transport(t =>
{
t.Read("ReadResources", "Gantt");
})
)
)
.Assignments<ResourceAssignmentViewModel>(a => a
.DataTaskIdField("TaskID")
.DataResourceIdField("ResourceID")
.DataValueField("Units")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.ID);
})
.Read("ReadAssignments", "Gantt")
.Create("CreateAssignment", "Gantt")
.Destroy("DestroyAssignment", "Gantt")
.Update("UpdateAssignment", "Gantt")
)
)
)
<script>
// Send the dates for the newly creted/updated tasks as UTC strings
function onUpdateCreate(e) {
e.End = e.End.toISOString();
e.Start = e.Start.toISOString();
}
</script>
For a complete example on using resources in the Gantt, refer to the Resources demo.
See Also
Server-Side API
947
Telerik UI for ASP.NET Core
Templates
To customize the way the tasks of the Gantt are rendered, use the TaskTemplateId configuration
option.
@(Html.Kendo().Gantt<TaskViewModel, DependencyViewModel>()
.Name("gantt")
.Columns(columns =>
{
columns.Bound(c => c.Title).Editable(true).Sortable(true);
columns.Resources("resources").Editable(true).Title("Assigned Resources");
})
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
})
.Height(700)
.TaskTemplateId("task-template")
.RowHeight(62)
)
<!-- Template -->
<script id="task-template" type="text/x-kendo-template">
# if (resources[0]) { #
<div class="template" style="background-color: #= resources[0].color #;">
<img class="resource-img"
src="../shared/web/gantt/resources/#:resources[0].id#.jpg" alt="#: resources[0].id #"
/>
<div class="wrapper">
<strong class="title">#= title # </strong>
<span class="resource">#= resources[0].name #</span>
</div>
<div class="progress" style="width:#= (100 * parseFloat(percentComplete)) #%">
</div>
</div>
# } else { #
<div class="template">
<div class="wrapper">
<strong class="title">#= title # </strong>
<span class="resource">no resource assigned</span>
</div>
<div class="progress" style="width:#= (100 * parseFloat(percentComplete)) #%">
</div>
</div>
# } #
</script>
For more information on the capabilities and syntax of the templates, refer to the Kendo UI Templates
Overview documentation article.
See Also
948
Telerik UI for ASP.NET Core
949
Telerik UI for ASP.NET Core
Gantt Accessibility
The Gantt is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Gantt is compliant with the Section 508 requirements. For more information, refer to the article
on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The Gantt supports the standards for providing accessible web content which are set by the Web
Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1 compliance
in UI for ASP.NET Core
See Also
Keyboard Navigation by the Gantt HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Gantt HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
950
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Gantt is always available.
For a complete example, refer to the demo on keyboard navigation of the Gantt.
See Also
Keyboard Navigation in the Gantt HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Gantt HtmlHelper for ASP.NET Core
951
Telerik UI for ASP.NET Core
The MultiViewCalendar renders a graphical Gregorian calendar with multiple horizontal views.
public ActionResult Index()
{
return View();
}
3. Add a MultiViewCalendar.
```Razor
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar") // The name of the MultiViewCalendar is
mandatory. It specifies the "id" attribute of the widget.
.Min(new DateTime(2010, 1, 1, 10, 0, 0)) // Set the min time of the
MultiViewCalendar.
.Max(new DateTime(2010, 1, 1, 20, 0, 0)) // Set the min date of the
MultiViewCalendar.
.Value(DateTime.Now) // Set the value of the MultiViewCalendar.
)
```
952
Telerik UI for ASP.NET Core
Events
You can subscribe to all MultiViewCalendar events.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Events(e => e
.Change("calendar_change")
.Navigate("calendar_navigate")
)
)
<script>
function calendar_navigate() {
// Handle the navigate event.
}
function calendar_change() {
// Handle the change event.
}
</script>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Events(e => e
.Change(@<text>
function() {
// Handle the change event inline.
}
</text>)
.Navigate(@<text>
function() {
// Handle the navigate event inline.
}
</text>)
)
)
See Also
Basic Usage of the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Using the API of the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
953
Telerik UI for ASP.NET Core
Active View
To define the first view which the MultiViewCalendar initially renders, use the Start option.
The following example demonstrates how to create a MultiViewCalendar that allows users to select
a month.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
)
See Also
Server-Side API
954
Telerik UI for ASP.NET Core
Multiple Views
The Telerik UI MultiViewCalendar allows you to define the number of views and months that are
displayed at a time.
In some scenarios it might be necessary to display more than two months. This is especially helpful
when performing range selection between months.
@(Html.Kendo().NumericTextBox()
.Name("numberOfViews")
.RestrictDecimals(true)
.Decimals(0)
.Min(2)
.Max(10)
.Value(2)
.Format("{0:n0}")
)
@(Html.Kendo().Button()
.Name("numberOfViewsBtn")
.Content("Apply Changes")
.Events(ev => ev.Click("click"))
)
@(Html.Kendo().MultiViewCalendar()
.Name("multiViewCalendar")
)
<script>
function click() {
var numberOfViews = $("#numberOfViews").data().kendoNumericTextBox.value();
if (numberOfViews > 0) {
$("#multiViewCalendar").data().kendoMultiViewCalendar.setOptions({
numberOfVies: numberOfViews });
}
}
</script>
See Also
Multiple Views in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
View Selection in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
955
Telerik UI for ASP.NET Core
Selection
The Telerik UI MultiViewCalendar allows the user to select multiple dates by using the multiple-view
MultiViewCalendar selection mode.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Selectable("range")
)
See Also
Selection in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
956
Telerik UI for ASP.NET Core
Day Template
The MultiViewCalendar enables you to customize the rendered day for the month view.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.MonthTemplate("<div class='custom'><#=data.value#></div>")
)
The template wraps the value in a <div> HTML element. The structure of the data object that is
passed to the template function.
data = {
date: date, // A date object that corresponds to the current cell.
title: kendo.toString(date, "D"),
value: date.getDate(),
dateString: "2011/0/1" // The formatted date by using the yyyy/MM/dd format and
the month is zero-based.
};
See Also
Server-Side API
957
Telerik UI for ASP.NET Core
Disabled Dates
The MultiViewCalendar allows you to disable certain days which are not intended to be selected by
the end user such as weekends, national holidays, and others.
Setting an Array
When you set an array, list the days that need to be disabled by using the first letters from their
names in English.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.DisableDates(new[] {"we", "th" })
)
Adding a Function
When you add a function, determine its return value as true for the date that is disabled.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.DisableDates("handler")
)
<script>
function handler(date) {
var disabled = [13,14,20,21];
if (date && disabled.indexOf(date.getDate()) > -1 ) {
return true;
} else {
return false;
}
}
</script>
See Also
Disabled Dates in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
958
Telerik UI for ASP.NET Core
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.WeekNumber(true)
)
See Also
Week Column in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
959
Telerik UI for ASP.NET Core
MultiViewCalendar Accessibility
The MultiViewCalendar is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG
2.1, and keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The MultiViewCalendar is compliant with the Section 508 requirements. For more information, refer
to the article on Section 508 support in Telerik UI for ASP.NET Core.
WCAG 2.1
The MultiViewCalendar supports the standards for providing accessible web content which are set
by the Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in Telerik UI for ASP.NET Core.
See Also
Keyboard Navigation by the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Accessibility in Telerik UI for ASP.NET Core
960
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the MultiViewCalendar is always available.
Shortcut Description
Up Arrow Highlights the same day from the previous
week.
Down Arrow Highlights the same day from the next week.
Left Arrow Highlights the previous day.
Right Arrow Highlights the next day.
Enter Selects the focused date.
Home Focuses the first date in the month.
End Focuses the last date in the month.
Ctrl+Up Arrow Navigates to the previous view.
Ctrl+Down Arrow Navigates to the next view.
Ctrl+Down Left Navigates to the previous month.
Ctrl+Down Right Navigates to the next month.
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Selectable("multiple")
)
See Also
Keyboard Navigation in the MultiViewCalendar HtmlHelper for ASP.NET Core (Demo)
Server-Side API
961
Telerik UI for ASP.NET Core
The Scheduler displays a set of events, appointments, or tasks. It supports the display of scheduled
events in different views—single days, whole weeks, or months, or as a list of tasks which need to be
accomplished.
As of the R1 2017 release, exceptions are no longer automatically removed when the user edits a
series. Changes that are made to specific occurrences are persisted during series editing. If a series
contains an exception, the Scheduler renders a Reset Series button within the Edit dialog of the
series which allows the user to reset the series by removing existing exceptions.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.TimelineView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.OwnerID).DefaultValue(1);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Read", "Scheduler")
.Create("Create", "Scheduler")
.Destroy("Destroy", "Scheduler")
.Update("Update", "Scheduler")
)
)
public class SchedulerController : Controller
{
962
Telerik UI for ASP.NET Core
private ISchedulerEventService<TaskViewModel> taskService;
public SchedulerController(
ISchedulerEventService<TaskViewModel> schedulerTaskService)
{
taskService = schedulerTaskService;
}
public IActionResult Index()
{
return View();
}
public virtual JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
return Json(taskService.GetAll().ToDataSourceResult(request));
}
public virtual JsonResult Destroy([DataSourceRequest] DataSourceRequest
request, TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Delete(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Create([DataSourceRequest] DataSourceRequest request,
TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Insert(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Update([DataSourceRequest] DataSourceRequest request,
TaskViewModel task)
{
//example custom validation:
if (task.Start.Hour < 8 || task.Start.Hour > 22)
{
ModelState.AddModelError("start", "Start date must be in working hours (8h -
22h)");
}
if (ModelState.IsValid)
{
taskService.Update(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
}
Basic Configuration
963
Telerik UI for ASP.NET Core
The following example demonstrates the basic configuration of the Scheduler HtmlHelper.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.MeetingViewModel>()
.Name("scheduler")
.CurrentTimeMarker(true)
.Editable(true)
.Date(new DateTime(2013, 6, 13))
.Pdf(pdf => pdf
.FileName("SchedulerExport.pdf")
.ProxyURL(Url.Action("Pdf_Export_Save", "Scheduler"))
)
.Timezone("Etc/UTC")
.Toolbar(t => t.Pdf())
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView();
views.MonthView(monthView => monthView.Selected(true));
views.AgendaView();
views.TimelineView();
})
.Group(group => { group.Resources("Rooms"); group.Date(true); })
.Resources(resource =>
{
resource.Add(m => m.RoomID)
.Title("Room")
.Name("Rooms")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Meeting Room 101", Value = 1, Color = "#6eb3fa" },
new { Text = "Meeting Room 201", Value = 2, Color = "#f58a8a" }
});
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Date_Grouping_Read", "Scheduler")
.Create("Date_Grouping_Create", "Scheduler")
.Destroy("Date_Grouping_Destroy", "Scheduler")
.Update("Date_Grouping_Update", "Scheduler")
)
)
964
Telerik UI for ASP.NET Core
Events
You can subscribe to all Scheduler events. For a complete example on basic Scheduler events, refer
to the demo on using the events of the Scheduler. For a runnable example on the move and resize
events, refer to the demo on the specific events.
The following example demonstrates how to subscribe to the dataBound and dataBinding events.
@(Html.Kendo().Scheduler<KendoUISchedulerDemo.Models.Projection>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 10, 00, 00))
.EndTime(new DateTime(2013, 6, 13, 23, 00, 00))
.Editable(false)
.Height(600)
.BindTo(Model)
.Events(e => {
e.DataBound("scheduler_dataBound");
e.DataBinding("scheduler_dataBinding");
})
)
<script>
function scheduler_dataBound(e) {
//Handle the dataBound event.
}
function scheduler_dataBinding(e) {
//Handle the dataBinding event.
}
</script>
// Place the following after your Telerik UI Scheduler for ASP.NET Core declaration.
<script>
$(document).ready(function() {
// The Name() of the Scheduler is used to get its client-side instance.
var scheduler = $("#scheduler").data("kendoScheduler");
});
</script>
See Also
Basic Usage of the Scheduler HtmlHelper for ASP.NET Core (Demo)
Using the API of the Scheduler HtmlHelper for ASP.NET Core (Demo)
Server-Side API
965
Telerik UI for ASP.NET Core
Ajax Binding
You can configure the Scheduler HtmlHelper for Ajax binding.
For a complete example, refer to the demo on binding the Scheduler to remote data.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.TimelineView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.OwnerID).DefaultValue(1);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Read", "Scheduler")
.Create("Create", "Scheduler")
.Destroy("Destroy", "Scheduler")
.Update("Update", "Scheduler")
)
)
public class SchedulerController : Controller
{
private ISchedulerEventService<TaskViewModel> taskService;
public SchedulerController(
ISchedulerEventService<TaskViewModel> schedulerTaskService)
{
taskService = schedulerTaskService;
}
public IActionResult Index()
{
return View();
}
public virtual JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
return Json(taskService.GetAll().ToDataSourceResult(request));
}
public virtual JsonResult Destroy([DataSourceRequest] DataSourceRequest
request, TaskViewModel task)
{
966
Telerik UI for ASP.NET Core
if (ModelState.IsValid)
{
taskService.Delete(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Create([DataSourceRequest] DataSourceRequest request,
TaskViewModel task)
{
if (ModelState.IsValid)
{
taskService.Insert(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
public virtual JsonResult Update([DataSourceRequest] DataSourceRequest request,
TaskViewModel task)
{
//example custom validation:
if (task.Start.Hour < 8 || task.Start.Hour > 22)
{
ModelState.AddModelError("start", "Start date must be in working hours (8h -
22h)");
}
if (ModelState.IsValid)
{
taskService.Update(task, ModelState);
}
return Json(new[] { task }.ToDataSourceResult(request, ModelState));
}
}
See Also
Binding the Scheduler HtmlHelper for ASP.NET Core to Remote Data (demo)
Server-Side API
967
Telerik UI for ASP.NET Core
Server Binding
You can bind the Scheduler to a model.
public class Projection : ISchedulerEvent
{
public string Title { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public string Description { get; set; }
public bool IsAllDay { get; set; }
string StartTimezone { get; set; }
string EndTimezone { get; set; }
public string RecurrenceRule { get; set; }
public string RecurrenceException { get; set; }
}
2. Create a new action method which passes the List of projections to the view.
public IActionResult Index()
{
List<Projection> cinemaSchedule = new List<Projection> {
new Projection {
Title = "Fast and furious 6",
Start = new DateTime(2013,6,13,17,00,00),
End= new DateTime(2013,6,13,18,30,00)
},
new Projection {
Title= "The Internship",
Start= new DateTime(2013,6,13,14,00,00),
End= new DateTime(2013,6,13,15,30,00)
},
new Projection {
Title = "The Perks of Being a Wallflower",
Start = new DateTime(2013,6,13,16,00,00),
End = new DateTime(2013,6,13,17,30,00)
}};
return View(cinemaSchedule);
}
3. Add a Scheduler.
@(Html.Kendo().Scheduler<KendoUISchedulerDemo.Models.Projection>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 10, 00, 00))
.EndTime(new DateTime(2013, 6, 13, 23, 00, 00))
.Editable(false)
968
Telerik UI for ASP.NET Core
.Height(600)
.BindTo(Model)
)
See Also
Server-Side API
969
Telerik UI for ASP.NET Core
Adaptive Rendering
The Scheduler supports adaptive enhancements such as changes in styling and behavior in order to
remain consistent with the specific user device experience.
For example, when editing on a mobile device, the edit container will slide in a new screen for the
user, which is a departure from the more desktop-like popup behaviors.
If set to MobileMode.Auto, the widget will use adaptive rendering when viewed on a mobile
browser.
If set to MobileMode.Phone", the widget will be forced to use adaptive rendering regardless
of the browser type.
Important: With the mobile rendering mode make sure to setup the height option as well.
The following example demonstrates how to configure the adaptive rendering mode of the
Scheduler.
@(Html.Kendo().Scheduler<KendoSchedulerAjaxEditing.Models.TaskViewModel>()
.Name("scheduler")
.Mobile(MobileMode.Auto)
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
views.AgendaView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m => {
m.Id(f => f.TaskID);
m.Field(f => f.OwnerID).DefaultValue(1);
m.RecurrenceId(f => f.RecurrenceID);
})
.Read("Tasks_Read", "Home")
.Create("Tasks_Create", "Home")
.Destroy("Tasks_Destroy", "Home")
.Update("Tasks_Update", "Home")
)
)
970
Telerik UI for ASP.NET Core
you need to define an explicit pixel Scheduler height by setting the height option.
@(Html.Kendo().Scheduler<KendoSchedulerAjaxEditing.Models.TaskViewModel>()
...
.Mobile(MobileMode.Phone)
.Height(600)
)
See Also
Adaptive Rendering by the Scheduler HtmlHelper for ASP.NET Core (Demo)
Server-Side API
971
Telerik UI for ASP.NET Core
Resources
The Scheduler HtmlHelper allows you to assign events to a set of predefined resources.
You can assign multiple instances of the same resource type to a single Scheduler event and also
assign resources through the Scheduler event edit form. For a runnable example, refer to the demo
on setting the Scheduler HtmlHelper resources.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.MeetingViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
})
.Timezone("Etc/UTC")
.Resources(resource =>
{
resource.Add(m => m.RoomID) // The field of the Scheduler event which contains
the resource identifier.
.Title("Room") // The label displayed in the Scheduler edit form for this
resource.
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Meeting Room 101", Value = 1, Color = "#6eb3fa" },
new { Text = "Meeting Room 201", Value = 2, Color = "#f58a8a" }
});
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Meetings_Read", "Scheduler")
.Create("Meetings_Create", "Scheduler")
.Destroy("Meetings_Destroy", "Scheduler")
.Update("Meetings_Update", "Scheduler")
)
)
972
Telerik UI for ASP.NET Core
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.MeetingViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.Resources(resource =>
{
resource.Add(m => m.Attendees) // The field of the Scheduler event, which
contains the resource identifier.
.Title("Attendees") // The label displayed in the Scheduler edit form for this
resource.
.Multiple(true) // Indicate that this is a multiple instance resource.
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Alex", Value = 1, Color = "#f8a398" },
new { Text = "Bob", Value = 2, Color = "#51a0ed" },
new { Text = "Charlie", Value = 3, Color = "#56ca85" }
});
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Meetings_Read", "Scheduler")
.Create("Meetings_Create", "Scheduler")
.Destroy("Meetings_Destroy", "Scheduler")
.Update("Meetings_Update", "Scheduler")
)
)
973
Telerik UI for ASP.NET Core
The Scheduler supports multiple resource types. For example, you can combine single and multiple
instance resources at the same time.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.MeetingViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.Resources(resource =>
{
// First resource type definition
resource.Add(m => m.RoomID) // The field of the Scheduler event, which contains
the resource identifier.
.Title("Room") // The label displayed in the Scheduler edit form for this
resource.
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Meeting Room 101", Value = 1, Color = "#6eb3fa" },
new { Text = "Meeting Room 201", Value = 2, Color = "#f58a8a" }
});
// Second resource type definition
resource.Add(m => m.Attendees) // The field of the Scheduler event which
contains the resource identifier.
.Title("Attendees") // The label displayed in the Scheduler edit form for this
resource.
.Multiple(true) // Indicate that this is a multiple instance resource.
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Alex", Value = 1, Color = "#f8a398" },
new { Text = "Bob", Value = 2, Color = "#51a0ed" },
new { Text = "Charlie", Value = 3, Color = "#56ca85" }
});
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Meetings_Read", "Scheduler")
.Create("Meetings_Create", "Scheduler")
.Destroy("Meetings_Destroy", "Scheduler")
.Update("Meetings_Update", "Scheduler")
)
)
974
Telerik UI for ASP.NET Core
See Also
Server-Side API
975
Telerik UI for ASP.NET Core
Timezones
A timezonerefers to any of the 24 regions loosely divided by longitude and which keep the same time
standard.
Getting Started
To set a timezone to the Scheduler, set the timezone option. timezone indicates the desired
timezone to be applied when the Scheduler displays the appointment dates. By default, the
timezone option is not set and, as a result, the event dates will be created based on the current
client timezone offset. This means that users from different timezones will see different start and
end times. On the other hand, setting the Scheduler timezone will display the same start and end
times regardless of the timezone of the user.
When you use remote binding, the Scheduler expects to receive UTC dates. Respectively, it
will send them back to the server in UTC. The service in use is responsible for keeping the
dates in UTC, without offsetting them against its local time.
When you bind the Scheduler to a remote service, keep the timezone option always set to,
for example, "Etc/UTC".
When the timezone option of the Scheduler is not set, the current system timezone offset is
used.
The recommended Date format for sending and receiving Scheduler event dates is ISO 8601
with a Z zone designator (UTC date). The same format is used by the JSON.stringify
method, which converts JavaScript Date objects to JSON strings.
The following example demonstrates how to set "Etc/UTC" timezone to the Scheduler.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.MeetingViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Meetings_Read", "Scheduler")
.Create("Meetings_Create", "Scheduler")
.Destroy("Meetings_Destroy", "Scheduler")
.Update("Meetings_Update", "Scheduler")
)
976
Telerik UI for ASP.NET Core
)
The SchedulerEvent instances are serialized by using JSON.stringify. In the process, the dates
are converted to UTC and then formatted according to the ISO8601 format.
See Also
Server-Side API
977
Telerik UI for ASP.NET Core
Server filtering
This article explains how to implement server-side filtering for the Scheduler component.
The server-side filtering allows the user to load only the events that are part of the currently loaded
View without the need to fetch all the available data from the datasource. The server-side filtering
approach is very useful for situations where there are a lot of events/meetings in the database
allowing us to fetch the needed data only - leading to better performance and faster loading.
The code snippets below are extracted from a demo project of Scheduler with Server Filtering in
ASP.NET Core that can be downloaded from this repository. The current article discussed the more
difficult steps of the server filtering implementation. For more details, please refer to the
above-linked repository.
.Read(read => read.Action("Read", "Scheduler").Data("getAdditionalData"))
@(Html.Kendo().Scheduler<SqlServerDataBase.Models.TaskViewModel>()
.Name("scheduler")
.StartTime(6, 30, 0)
.Height(600)
.WorkWeekStart(1)
.WorkWeekEnd(7)
.Views(views =>
{
views.DayView();
views.WorkWeekView(workWeekView => workWeekView.Selected(true));
views.WeekView();
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.TaskID);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
})
.ServerOperation(true)
978
Telerik UI for ASP.NET Core
.Read(read => read.Action("Read", "Scheduler").Data("getAdditionalData"))
.Create("Create", "Scheduler")
.Destroy("Destroy", "Scheduler")
.Update("Update", "Scheduler")
)
)
Get the Start and End dates of the current Scheduler view
To be sure that the server will return only the events visible in the current Scheduler View, we have to
pass to it the timespan that is currently visible. The timespan data is sent to the server using the
Data parameter mentioned in the above section.
function getAdditionalData() {
var scheduler = $("#scheduler").data("kendoScheduler");
var timezone = scheduler.options.timezone;
var startDate = kendo.timezone.convert(scheduler.view().startDate(), timezone,
"Etc/UTC");
var endDate = kendo.timezone.convert(scheduler.view().endDate(), timezone,
"Etc/UTC");
var startTime = 0;
var endTime = 0;
if (scheduler.view().startTime) {
console.log('in')
//optionally add startTime / endTime of the view
startTime = kendo.date.getMilliseconds(scheduler.view().startTime());
endTime = kendo.date.getMilliseconds(scheduler.view().endTime());
endTime = endTime == 0 ? kendo.date.MS_PER_DAY : endTime;
}
var result = {
Start: new Date(startDate.getTime() - (startDate.getTimezoneOffset() *
kendo.date.MS_PER_MINUTE) + startTime),
End: new Date(endDate.getTime() - (endDate.getTimezoneOffset() *
kendo.date.MS_PER_MINUTE) + endTime)
}
return result;
}
public virtual JsonResult Read([DataSourceRequest] DataSourceRequest request,
FilterRange range)
{
var data = taskService.GetRange(range.Start, range.End);
return Json(data.ToDataSourceResult(request));
979
Telerik UI for ASP.NET Core
}
The Start and End properties of the range object are then passed to the GetRange method and it
returns all events that are between the start and end date of the client View.
public virtual IEnumerable<TaskViewModel> GetRange(DateTime start, DateTime end)
{
var result = GetAll().ToList().Where(t => (t.RecurrenceRule != null || (t.Start >=
start && t.Start <= end) || (t.End >= start && t.End <= end)));
return result;
}
980
Telerik UI for ASP.NET Core
Scheduler Accessibility
The Scheduler is accessible by screen readers and provides WAI-ARIA, Section 508, WCAG 2.1, and
keyboard support.
WAI-ARIA
The component follows the WAI-ARIA Authoring Practices for implementing the keyboard navigation
for its component role and is tested against the popular screen readers. For more information, refer
to the article on WAI-ARIA support in Telerik UI for ASP.NET Core.
Section 508
The Scheduler is compliant with the Section 508 requirements. For more information, refer to the
article on Section 508 support in Kendo UI for ASP.NET Core.
WCAG 2.1
The Scheduler supports the standards for providing accessible web content which are set by the
Web Content Accessibility Guidelines 2.1. For more information, refer to the article on WCAG 2.1
compliance in UI for ASP.NET Core
See Also
Keyboard Navigation by the Scheduler HtmlHelper for ASP.NET Core (Demo)
Keyboard Navigation by the Scheduler HtmlHelper for ASP.NET Core
Accessibility in Telerik UI for ASP.NET Core
981
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Scheduler is always available.
For a complete example, refer to the demo on keyboard navigation of the Scheduler.
See Also
Keyboard Navigation in the Scheduler HtmlHelper for ASP.NET Core (Demo)
Accessibility in the Scheduler HtmlHelper for ASP.NET Core
982
Telerik UI for ASP.NET Core
Tag Helpers can be added and further configured through predefined strongly typed attributes and
also allow you to handle the events of the widgets in ASP.NET Core projects.
@addTagHelper "*, Kendo.Mvc"
The following example demonstrates how to configure the NumericTextBox tag helper.
<kendo-numerictextbox name="currency" format="c" min="0"
enable="true" max="100" value="30">
</kendo-numerictextbox>
The following example demonstrates how to set the change event of a NumericTextBox.
<kendo-numerictextbox name="currency" on-change="changeEvent">
</kendo-numerictextbox>
Known Issues
Tag Helpers might need to be disabled on pages where widgets render custom content—for
983
Telerik UI for ASP.NET Core
example, the Button, Editor, Splitter, Tooltip, or Window. Some Tag Helpers, such as the href
one, are processed automatically and result in invalid HTML.
@removeTagHelper "*, Microsoft.AspNet.Mvc.Razor"
@removeTagHelper "*, Microsoft.AspNetCore.Mvc.Razor"
See Also
Introduction to UI for ASP.NET Core
First Steps on Visual Studio for Windows (Online Guide)
First Steps on Visual Studio for Mac (Online Guide)
First Steps with CLI (Online Guide)
984
Telerik UI for ASP.NET Core
<kendo-barcode name="BarCode"></kendo-barcode>
Basic Configuration
The Barcode TagHelper configuration options are passed as attributes of the tag.
<kendo-barcode name="barcode" value="10110110" type="BarcodeSymbology.Code128"
width="200" height="100">
<border color="red" width="2"/>
</kendo-barcode>
@(Html.Kendo().Barcode()
.Name("gudbrands")
.Value("10110110")
.Encoding(BarcodeSymbology.Code128)
.Width(200)
.Height(100)
.Border(border => border.Color("red").Width(2)))
)
See Also
Basic Usage of the Barcode TagHelper for ASP.NET Core (Demo)
Server-Side API
985
Telerik UI for ASP.NET Core
The QRCode generates Canvasand Scalable Vector Graphics (SVG)images that represent Quick
Response (QR) codes.
QR codes take a piece of information from a transitory media, place it into the cell phone, and enable
the cell phone to quickly read these generated images. All graphics are rendered on the client by
using Canvas or SVG.
<kendo-qrcode name="qrcode"></kendo-qrcode>
Basic Configuration
The QRCode TagHelper configuration options are passed as attributes of the tag.
<kendo-qrcode name="qrUrl" value="https://docs.telerik.com/aspnet-core/introduction"
error-correction="QRErrorCorrectionLevel.M size=" 150">
<border color="#AA11AA" width="2" />
</kendo-qrcode>
Html.Kendo().QRCode()
.Name("qrUrl")
.Value("https://docs.telerik.com/aspnet-core/introduction")
.ErrorCorrection(QRErrorCorrectionLevel.M)
.Size(150)
.Border(border => border.Color("#AA11AA").Width(2))
)
)
See Also
Basic Usage of the QRCode TagHelper for ASP.NET Core (Demo)
Server-Side API
986
Telerik UI for ASP.NET Core
The Chart uses modern browser technologies to render high-quality data visualizations. All graphics
are rendered on the client by using Scalable Vector Graphics (SVG)with a fallback to Canvas. The
Charts support a set of series typessuch as Bar, Line, Area, Bullet, Pie, Scatter, Bubble, Polar, and
other.
<kendo-chart name="chart"></kendo-chart>
Basic Configuration
The Chart TagHelper configuration options are passed as attributes of the tag. In the following
example, the tagHelper and razor configurations are equivalent.
<kendo-chart name="chart">
<chart-title text="Gross domestic product growth /GDP annual %/"></title>
<chart-legend position="ChartLegendPosition.Top"></legend>
<series-defaults type="ChartSeriesType.Column"></series-defaults>
<series>
<series-item name="India" data="new double[] { 3.907, 7.943, 7.848, 9.284,
9.263, 9.801, 3.890, 8.238, 9.552, 6.855 }"></series-item>
<series-item name="Russian Federation" data="new double[] { 4.743, 7.295,
7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3 }"></series-item>
<series-item name="Germany" data="new double[] { 0.010, -0.375, 1.161, 0.684,
3.7, 3.269, 1.083, -5.127, 3.690, 2.995 }"></series-item>
<series-item name="World" data="new double[] { 1.988, 2.733, 3.994, 3.464,
4.001, 3.939, 1.333, -2.245, 4.339, 2.727 }"></series-item>
</series>
<value-axis>
<value-axis-item>
<labels format="{0}%"></labels>
<line visible="false" />
</value-axis-item>
</value-axis>
<category-axis>
<category-axis-item categories='new string[] { "2002", "2003", "2004", "2005",
"2006", "2007", "2008", "2009", "20010", "2011", }'>
<labels>
<chart-category-axis-labels-padding top="135" />
987
Telerik UI for ASP.NET Core
</labels>
<line visible="false" />
</category-axis-item>
</category-axis>
<tooltip visible="true" format="{0}%" template="#= series.name #: #= value
#"></tooltip>
</kendo-chart>
@(Html.Kendo().Chart()
.Name("chart")
.Title("Gross domestic product growth /GDP annual %/")
.Legend(legend => legend
.Position(ChartLegendPosition.Top)
)
.ChartArea(chartArea => chartArea
.Background("transparent")
)
.Series(series =>
{
series.Column(new double[] { 3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890,
8.238, 9.552, 6.855 }).Name("India");
series.Column(new double[] { 4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247,
-7.832, 4.3, 4.3 }).Name("Russian Federation");
series.Column(new double[] { 0.010, -0.375, 1.161, 0.684, 3.7, 3.269, 1.083,
-5.127, 3.690, 2.995 }).Name("Germany");
series.Column(new double[] { 1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333,
-2.245, 4.339, 2.727 }).Name("World");
})
.CategoryAxis(axis => axis
.Name("series-axis")
.Line(line => line.Visible(false))
)
.CategoryAxis(axis => axis
.Name("label-axis")
.Categories("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
"2010", "2011")
)
.ValueAxis(axis => axis
.Numeric()
.Labels(labels => labels.Format("{0}%"))
// Move the label-axis all the way down the value axis.
.AxisCrossingValue(0, int.MinValue)
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
.Template("#= series.name #: #= value #")
)
)
See Also
Basic Usage of the Kendo UI Area Charts Tag Helper for ASP.NET Core (Demo)
Server-Side API
988
Telerik UI for ASP.NET Core
<kendo-treemap datasource-id="dataSource" name="treeMap" text-field="name"
value-field="value"></kendo-treemap>
<script>
var dataSource = new kendo.data.HierarchicalDataSource({
data: [{
name: "foo",
value: 1
}]
});
</script>
<kendo-treemap name="treemap" text-field="name" value-field="value">
<hierarchical-datasource>
<transport>
<read url="/treemap/_populationusa" />
</transport>
<schema>
<hierarchical-model children="items"></hierarchical-model>
</schema>
</hierarchical-datasource>
</kendo-treemap>
@(Html.Kendo().TreeMap()
.Name("treeMap")
.DataSource(dataSource => dataSource
.Read(read => read
.Action("_PopulationUSA", "TreeMap")
)
.Model(m => m.Children("Items"))
)
989
Telerik UI for ASP.NET Core
.ValueField("Value")
.TextField("Name")
.HtmlAttributes(new { style = "height:600px; font-size: 12px;" })
)
See Also
Basic Usage of the TreeMap TagHelper for ASP.NET Core (Demo)
Server-Side API
990
Telerik UI for ASP.NET Core
The Chat allows the user to participate in chat sessions with other users or with chat bots. It
provides support for default cards and actions, and enables the configuration of custom templates
and custom components.
<kendo-chat name="chat"></kendo-chat>
Basic Configuration
The following example demonstrates the configuration options that are available for the Chat
TagHelper.
<!-- Initializing the Chat and attaching the event handlers -->
<kendo-chat name="chat"
on-post="onPost"
on-action-click="onActionClick"
on-send-message="onSendMessage"
on-typing-start="onTypingStart"
on-typing-end="onTypingEnd">
<!-- The Chat User configuration -->
<user name="ChatBot Name"
icon-url="https://demos.telerik.com/kendo-ui/content/chat/avatar.png" />
<!-- Configuring the Placeholder message -->
<messages placeholder="Type your message" />
</kendo-chat>
See Also
Basic Usage of Chat HtmlHelper for ASP.NET Core (Demo)
Server-Side API
991
Telerik UI for ASP.NET Core
Peer-to-Peer Chat
You can configure a Chat TagHelper for ASP.NET Core and a .Net Core SignalRservice to create a
Peer-to-Peer Chat application.
To create the Peer-to-Peer Chat you have to implement the SignalR Hub server and, then, to
implement the application client:
Create a new Telerik UI for ASP.NET Core application form the Standard template
Create a new .Net Core application in Visual Studio and include the Telerik UI for ASP.NET Core
package
Create a new .Net Core application with the CLI and include the Telerik UI for ASP.NET Core
package
namespace CoreSignalR
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
// Add the SignalR service
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
992
Telerik UI for ASP.NET Core
...
// Point to the route that will return the SignalR Hub
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chat");
});
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace CoreSignalR
{
// The Hub class has to inherit from the Microsoft.AspNet.SignalR.Hub.
public class ChatHub : Hub
{
public async Task Send(object sender, string message)
{
// Broadcast the message to all clients except the sender.
await Clients.Others.SendAsync("broadcastMessage", sender, message);
}
public async Task SendTyping(object sender)
{
// Broadcast the typing notification to all clients except the sender.
await Clients.Others.SendAsync("typing", sender);
}
}
}
@{
var name = Guid.NewGuid().ToString();
}
<kendo-chat name="chat"
on-post="onPost"
on-typing-start="onTypingStart">
<user name="@name"
icon-url="https://demos.telerik.com/kendo-ui/content/chat/avatar.png" />
</kendo-chat>
993
Telerik UI for ASP.NET Core
<script>
function onTypingStart() {
// The `typingStart` will notify the SignallR Hub that the current client is
typing.
// The Hub, in turn, will notify all the other clients that the user has
started typing.
chatHub.invoke("sendTyping", chat.getUser());
}
function onPost(args) {
// The `post` handler will send the user data and the typed text to the SignalR
Hub.
// The Hub will then forward that info to the other clients.
chatHub.invoke("send", chat.getUser(), args.text);
}
</script>
npm install @aspnet/signalr
2. Copy the @aspnet/signalr folder from the node_modules directory to the wwwroot/lib
folder of the Core project.
3. Include the SignalR script on the HTML page.
<script src="lib/signalr/dist/browser/signalr.min.js"></script>
// Point to the Hub remote endpoint.
window.chatHub = new signalR.HubConnectionBuilder()
.withUrl('/chat')
.build();
chatHub.start()
.catch(function(err) {
console.error(err.toString());
});
6. Attach the event handlers for the respective remote hub actions.
994
Telerik UI for ASP.NET Core
$(document).ready(function() {
window.chat = $("#chat").getKendoChat();
chatHub.on('broadcastMessage', function(sender, message) {
var message = {
type: 'text',
text: message
};
// Render the received message in the Chat.
chat.renderMessage(message, sender);
});
chatHub.on('typing', function(sender) {
// Display typing notification in the Chat.
chat.renderMessage({ type: 'typing' }, sender);
});
});
See Also
Basic Usage of the Kendo UI Chat Widget (Demo)
Server-Side API
995
Telerik UI for ASP.NET Core
The Filter is a unified control for filtering data-bound components that have a data source. The user
interface of the Filter is useful for data-bound components that do not have a built-in UI for filtering
but are required to provide filter options—for example, the ListView, Chart, and Scheduler.
You can add or remove the fields by which the data will be filtered and select the global logic of the
filters (AND or OR) and the filter operator for each field (contains or equals). You can apply the
filtering through a built-in button or through an API call. You can also select the name by which the
fields will be displayed to the user and localizethe filter operators and messages.
<kendo-datasource type="DataSourceTagHelperType.Ajax" name="dataSource1"
server-operation="false">
<transport>
<read url="@Url.Action("GetPeople", "Filter")" />
</transport>
</kendo-datasource>
@{
@using Kendo.Mvc
var InitialExpression = new CompositeFilterDescriptor
{
LogicalOperator = FilterCompositionLogicalOperator.And
};
InitialExpression.FilterDescriptors.Add(new FilterDescriptor { Member = "Age",
Value = 30, Operator = FilterOperator.IsGreaterThanOrEqualTo });
InitialExpression.FilterDescriptors.Add(new FilterDescriptor { Member = "Name",
Value = "Doe", Operator = FilterOperator.Contains });
}
<kendo-filter name="filter" apply-button="true" expression-preview="true"
datasource-id="dataSource1" expression="@InitialExpression">
<fields>
<filter-field name="Name" type="string" label="Name"></filter-field>
<filter-field name="Age" type="number" label="Age"></filter-field>
996
Telerik UI for ASP.NET Core
<filter-field name="IsOnLeave" type="boolean" label="On
Vacation"></filter-field>
</fields>
</kendo-filter>
<kendo-grid name="grid" datasource-id="dataSource1">
<columns>
<column field="Name" title="Employee Name" />
<column field="Age" title="Employee Age" />
<column field="IsOnLeave" title="On Vacation" />
</columns>
</kendo-grid>
<script>
$(document).ready(function () {
// Apply filtering immediately after the widget initialization because an
initial filter is set.
$("#filter").getKendoFilter().applyFilter();
});
</script>
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
public class FilterController : BaseController
{
public IActionResult GetPeople([DataSourceRequest]DataSourceRequest request)
{
var people = new List<SampleData>() {
new SampleData() { Name = "Jane Doe", Age = 25, IsOnLeave = false },
new SampleData() { Name = "John Doe", Age = 33, IsOnLeave = true },
new SampleData() { Name = "John Smith", Age = 37, IsOnLeave = true },
new SampleData() { Name = "Nathan Doe", Age = 42, IsOnLeave = false }
};
return Json(people.ToDataSourceResult(request));
}
public IActionResult Index()
{
return View();
}
}
public class SampleData
{
public int Age { get; set; }
public string Name { get; set; }
public bool IsOnLeave { get; set; }
}
See Also
Basic Usage of the Filter TagHelper for ASP.NET Core (Demo)
Server-Side API
997
Telerik UI for ASP.NET Core
The Grid is a powerful control for displaying data in a tabular format. It provides options for
executing data operations, such as paging, sorting, filtering, grouping, and editing, which determine
the way the data is presented and manipulated. The Grid supports data binding to local and remote
sets of data by using the Kendo UI for jQuery DataSource component.
<kendo-grid name="grid"></kendo-grid>
Basic Configuration
The Grid TagHelper configuration options are passed as attributes of the tag. The Grid uses the
DataSource tag helperto bind its data.
To parse the value to a proper data type, set a type field in the DataSource schema model of the
Grid TagHelper.
<kendo-grid name="grid" height="550">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders" />
</transport>
<schema>
<model>
<fields>
<field name="OrderDate" type="Date"></field>
</fields>
</model>
</schema>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<filterable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<columns>
<column field="OrderID" width="120" />
<column field="OrderDate" title="Order Date" format="{0:MM/dd/yyyy}" />
<column field="ShipName" title="Ship Name" width="300" />
<column field="ShipCity" title="Ship City" width="250" />
998
Telerik UI for ASP.NET Core
</columns>
</kendo-grid>
@(Html.Kendo().Grid<TelerikAspNetCoreApp4.Models.OrderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.OrderID).Width(120);
columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.ShipName).Width(300);
columns.Bound(p => p.ShipCity).Width(250);
})
.Groupable()
.Sortable()
.Filterable()
.Pageable(pageable => pageable
.ButtonCount(5)
.Refresh(true)
.PageSizes(new[] { 5, 10, 20 }))
.DataSource(dataSource => dataSource
.Custom()
.Transport(transport => transport
.Read(read => read.Action("Orders_Read", "Grid")))
.Schema(schema => schema
.Data("Data")
.Model(model => {
model.Field("OrderDate", typeof(DateTime));
})
)
)
)
Events
You can subscribe to all Grid events.
<kendo-grid name="grid" height="550" on-change="onChange" selectable="true">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
999
Telerik UI for ASP.NET Core
<filterable enabled="true" />
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
<script>
function onChange(e) {
var selectedRow = this.select();
var dataItem = this.dataItem(selectedRow);
console.log(dataItem)
}
</script>
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.CustomerViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.ContactName).Title("Contact
Name").Width(240).Filterable(ftb => ftb.Multi(true));
columns.Bound(c => c.ContactTitle).Title("Contact Title");
columns.Bound(c => c.CompanyName).Title("Company Name");
columns.Bound(c => c.Country).Title("Country").Width(150);
})
.Groupable()
.Events(events => events
.Change("onChange")
)
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Orders_Read", "Grid"))
.PageSize(20)
)
)
<script>
function onChange(e) {
var selectedRow = this.select();
var dataItem = this.dataItem(selectedRow);
console.log(dataItem)
}
</script>
See Also
Basic Usage of the Grid TagHelper for ASP.NET Core (Demo)
Server-Side API
1000
Telerik UI for ASP.NET Core
Hierarchy
The Grid supports hierarchy and requires a DetailInit function.
That function initializes the detail Grids by using the Kendo UI Grid for jQuery.
<kendo-grid name="grid" height="550" selectable="true" on-detail-init="onDetailInit">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
/>
</transport>
</datasource>
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="FirstName" title="First Name" width="240" />
<column field="LastName" title="Last Name" />
<column field="Country" title="Country" width="150" />
<column field="City" title="City" width="150" />
</columns>
</kendo-grid>
<script>
function onDetailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
filter: { field: "EmployeeID", operator: "eq", value: e.data.EmployeeID }
},
scrollable: false,
sortable: true,
pageable: true,
columns: [
{ field: "OrderID", width: "110px" },
{ field: "ShipCountry", title: "Ship Country", width: "110px" },
{ field: "ShipAddress", title: "Ship Address" },
{ field: "ShipName", title: "Ship Name", width: "300px" }
]
});
}
</script>
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("grid")
1001
Telerik UI for ASP.NET Core
.Columns(columns =>
{
columns.Bound(e => e.FirstName).Width(130);
columns.Bound(e => e.LastName).Width(130);
columns.Bound(e => e.Country).Width(130);
columns.Bound(e => e.City).Width(110);
columns.Bound(e => e.Title);
})
.Sortable()
.Pageable()
.Scrollable()
.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:600px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("HierarchyBinding_Employees", "Grid"))
)
)
<script id="template" type="text/kendo-tmpl">
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>()
.Name("grid_#=EmployeeID#") // template expression, to be evaluated in the
master context
.Columns(columns =>
{
columns.Bound(o => o.OrderID).Width(110);
columns.Bound(o => o.ShipCountry).Width(150);
columns.Bound(o => o.ShipAddress).ClientTemplate("\\#= ShipAddress \\#"); //
escaped template expression, to be evaluated in the child/detail context
columns.Bound(o => o.ShipName).Width(300);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("HierarchyBinding_Orders", "Grid", new { employeeID =
"#=EmployeeID#" }))
)
.Pageable()
.Sortable()
.ToClientTemplate()
)
</script>
See Also
Basic Usage of the Grid TagHelper for ASP.NET Core (Demo)
Server-Side API
1002
Telerik UI for ASP.NET Core
Editing
The Grid supports data editing operations (create, update, destroy) by configuring its data source.
Getting Started
To enable the data editing capabilities:
<kendo-grid name="grid" height="550">
<datasource page-size="20" type="DataSourceTagHelperType.Custom"
custom-type="odata" batch="true">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
/>
<update
url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products/Update" />
<destroy
url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products/Destroy" />
<create
url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products/Create" />
</transport>
<schema >
<model id="ProductID">
<fields>
<field name="ProductName"></field>
<field name="UnitPrice" type="number"></field>
<field name="UnitsInStock" type="number"></field>
</fields>
</model>
</schema>
</datasource>
<editable mode="incell" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<toolbar>
<toolbar-button name="create" text="Add new record"></toolbar-button>
<toolbar-button name="save" text="Save Changes"></toolbar-button>
<toolbar-button name="cancel" text="Cancel Changes"></toolbar-button>
</toolbar>
<columns>
<column field="ProductName" title="Product Name" width="240" />
<column field="UnitPrice" title="Unit Price" />
<column field="UnitsInStock" title="Units In Stock" />
<column field="Discontinued" title="Discontinued" width="150" />
<column>
<commands>
<column-command text="Delete" name="destroy"></column-command>
</commands>
</column>
</columns>
1003
Telerik UI for ASP.NET Core
</kendo-grid>
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("Grid")
.Columns(columns => {
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Width(140);
columns.Bound(p => p.UnitsInStock).Width(140);
columns.Bound(p => p.Discontinued).Width(100);
columns.Command(command => command.Destroy()).Width(150);
})
.ToolBar(toolbar => {
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.ProductID))
.Create("Editing_Create", "Grid")
.Read("Editing_Read", "Grid")
.Update("Editing_Update", "Grid")
.Destroy("Editing_Destroy", "Grid")
)
)
Custom Editors
The following example demonstrates how to set a Kendo UI DropDownList as a custom column
editor for the Grid by specifying the editor field of the ProductName column. The value of this field
points to a JavaScript function which instantiates the column editor for the corresponding column
cells.
<kendo-grid name="grid" height="550">
<datasource page-size="20">
<transport>
<read url="/Grid/Editing_Read" />
<update url="/Grid/Editing_Update" type="POST" />
</transport>
<schema data="Data" total="Total">
<model id="ProductID">
<fields>
<field name="ProductName" type="string"></field>
<field name="UnitPrice" type="number"></field>
<field name="UnitsInStock" type="number"></field>
<field name="Discontinued" type="boolean"></field>
</fields>
1004
Telerik UI for ASP.NET Core
</model>
</schema>
</datasource>
<groupable enabled="true" />
<editable mode="inline" enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ProductName" editor="productNameEditor" title="Product Name"
width="240" />
<column field="UnitPrice" title="UnitPrice" />
<column field="UnitsInStock" title="UnitsInStock" />
<column field="Discontinued" title="Discontinued" width="150" />
<column>
<commands>
<column-command name="edit"></column-command>
</commands>
</column>
</columns>
</kendo-grid>
<script>
function productNameEditor(container, options) {
var grid = $('#grid').data('kendoGrid');
$('<input required name="' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataSource: {
data: grid.dataSource.data().map(function (x) {
return x.ProductName;
}).filter(function (value,index, self) {
return self.indexOf(value) === index;
})
}
});
}
</script>
See Also
Basic Usage of the Grid TagHelper for ASP.NET Core (Demo)
Server-Side API
1005
Telerik UI for ASP.NET Core
Columns
The Grid allows for a flexible customization of its columns in terms of layout and appearance
through its column template feature.
Templates
The following example demonstrates how to specify your own custom layout for the Grid columns
by using images and property bindings from the underlying data source. The templates are defined
by using JavaScript functions.
<kendo-grid name="grid" height="550">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ContactName" template="#=template(data)#" title="Contact Name"
width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
<script>
function template(data) {
return `<div class='customer-photo'
style= 'background-image:
url(http://demos.telerik.com/kendo-ui/content/web/Customers/${data.CustomerID}.jpg);'
></div >
<div class='customer-name'>${ data.ContactName} </div>
`
}
</script>
<style type="text/css">
.customer-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
1006
Telerik UI for ASP.NET Core
margin-left: 5px;
}
.customer-name {
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
</style>
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.Customer>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c =>
c.ContactName).Width(140).ClientTemplate("#=template(data)#");
columns.Bound(c => c.ContactTitle).Width(190);
columns.Bound(c => c.CompanyName);
columns.Bound(c => c.Country).Width(110);
})
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Groupable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Customers_Read", "Grid"))
)
)
<script>
function template(data) {
return `<div class='customer-photo'
style= 'background-image:
url(http://demos.telerik.com/kendo-ui/content/web/Customers/${data.CustomerID}.jpg);'
></div >
<div class='customer-name'>${ data.ContactName} </div>
`
}
</script>
<style type="text/css">
.customer-photo {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: 32px 35px;
background-position: center center;
vertical-align: middle;
line-height: 32px;
box-shadow: inset 0 0 1px #999, inset 0 0 10px rgba(0,0,0,.2);
margin-left: 5px;
}
.customer-name {
1007
Telerik UI for ASP.NET Core
display: inline-block;
vertical-align: middle;
line-height: 32px;
padding-left: 3px;
}
</style>
Multi-Column Headers
The Grid supports multi-column headers by specifying column groups which incorporate inner
column structures.
In the following example, the Contact Info and Location columns have nested columns that are
depicted by a nested column tag helpers. Operations like sorting and filtering are supported on each
column level regardless of the selected multi-header pattern.
<kendo-grid name="grid" reorderable="true"resizable="true" height="550">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<column-menu enabled="true"/>
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column title="Contact Info" >
<columns>
<column field="ContactTitle" title="Contact Title" width="200" />
<column field="ContactName" title="Contact Name" width="200" />
<column title="Location">
<columns>
<column field="Country" width="200" />
<column field="City" width="200" />
</columns>
</column>
<column field="Phone" />
</columns>
</column>
</columns>
</kendo-grid>
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.CustomerViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.CompanyName).Width(420);
columns.Group(group => group
.Title("Contact Info")
.Columns(info => {
info.Bound(x => x.ContactTitle).Width(200);
1008
Telerik UI for ASP.NET Core
info.Bound(x => x.ContactName).Width(200);
info.Group(g => g.Title("Location")
.Columns(location =>
{
location.Bound(c => c.Country).Width(200);
location.Bound(c => c.City).Width(200);
})
);
info.Bound(x => x.Phone);
})
);
})
.ColumnMenu()
.Resizable(resizable => resizable.Columns(true))
.Reorderable(reorderable => reorderable.Columns(true))
.HtmlAttributes(new { style = "height: 550px;" })
.Scrollable()
.Groupable()
.Sortable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("MultiColumn_Customers_Read", "Grid"))
)
)
Virtualization
The Grid provides a built-in option for virtualizing its columns. To enable it, set the
scollable.virtual property to "columns". As a result, the columns outside the current visible
aria of the Grid will not be rendered and this will improve the rendering performance. When scrolling
is performed the visual subset of columns is changed accordingly.
To work properly, the column virtualization requires you to set the widths of the columns.
To enable virtualized columns:
<kendo-grid name="grid" height="550">
<scrollable virtual=@("columns")/>
</kendo-grid>
<kendo-grid name="grid" height="550">
<scrollable virtual=@("rows, columns")/>
</kendo-grid>
See Also
Basic Usage of the Grid TagHelper for ASP.NET Core (Demo)
Server-Side API
1009
Telerik UI for ASP.NET Core
Search Panel
Out of the box, the Grid enables the users to search through its data by using the search panel.
Under the hood, the search panel uses filtering to show only the relevant records in the Grid.
Getting Started
To enable the search panel functionality, include the Search option to the toolbar configuration.
When the server operations are enabled, you can search only by using string fields. Using the
Contains filter operation is available only for string types.
<kendo-grid name="grid" height="550">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
</datasource>
<toolbar>
<toolbar-button name="search"></toolbar-button>
</toolbar>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
You can also customize which fields to search through the data when a value is entered in the
search input.
...
<kendo-grid name="grid" height="550">
<search fields="@(new string[] { "ContactName", "Country"})">
</search>
Known Limitations
When filtering is enabled in the filter textboxes for all Grid columns will be populated with the value
entered in the search textbox.
1010
Telerik UI for ASP.NET Core
See Also
Server-Side API
Knowledge Base Section
1011
Telerik UI for ASP.NET Core
Selection
By default, the selection functionality of the Telerik UI Grid for ASP.NET Core is disabled.
Getting Started
To control the selection in the Grid, use the selectable property.
<kendo-grid name="grid" height="550" on-change="onChange" selectable="true">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
<script>
function onChange(e) {
var selectedRow = this.select();
var dataItem = this.dataItem(selectedRow);
console.log(dataItem)
}
</script>
Select Modes
The Grid supports the following select modes:
You can set the select mode to Multiple or Single. Additionally, the Grid provides the Row and
Cell select types which allow multiple or single selection of rows or cells.
The Grid TagHelper accepts the following values for its selectable property:
1012
Telerik UI for ASP.NET Core
<kendo-grid name="grid" height="550" on-change="onChange" selectable="multiple,
cell">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read
url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers" />
</transport>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10,
20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
<script>
function onChange(e) {
var selectedRow = this.select();
var dataItem = this.dataItem(selectedRow);
console.log(dataItem)
}
</script>
To persist the selection in the Grid, you also need to configure the ID field in the schema of the
DataSource. For a runnable example, refer to the demo on persisting the state of the Grid.
<kendo-grid name="grid" height="550" on-change="onChange" persist-selection="true">
<datasource type="DataSourceTagHelperType.Custom" custom-type="odata"
page-size="20">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
/>
</transport>
<schema>
<model id="CustomerID">
<fields>
1013
Telerik UI for ASP.NET Core
<field name="ContactName" type="string"></field>
<field name="ContactTitle" type="string"></field>
<field name="CompanyName" type="string"></field>
<field name="Country" type="string"></field>
</fields>
</model>
</schema>
</datasource>
<groupable enabled="true" />
<sortable enabled="true" />
<pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
</pageable>
<filterable enabled="true" />
<columns>
<column field="ContactName" title="Contact Name" width="240" />
<column field="ContactTitle" title="Contact Title" />
<column field="CompanyName" title="Company Name" />
<column field="Country" title="Country" width="150" />
</columns>
</kendo-grid>
<script>
function onChange(e) {
var selectedRow = this.select();
var dataItem = this.dataItem(selectedRow);
console.log(dataItem)
}
</script>
See Also
Selection by the Kendo UI for jQuery Grid (Demo)
API Reference of selectable in Kendo UI for jQuery
Server-Side API
1014
Telerik UI for ASP.NET Core
<kendo-pivotconfigurator name="configurator"
datasource-id="pivotSource"></kendo-pivotconfigurator>
<kendo-pivotgrid name="pivotgrid" datasource-id="pivotSource"></kendo-pivotgrid>
Basic Configuration
The PivotGrid TagHelper configuration options are passed as attributes of the tag.
<kendo-pivotdatasource type=@(PivotDataSourceType.Xmla) name="pivotSource">
<columns>
<pivot-datasource-column name="[Date].[Calendar]"
expand="true"></pivot-datasource-column>
<pivot-datasource-column name="[Product].[Category]"></pivot-datasource-column>
</columns>
<rows>
<row name="[Geography].[City]"></row>
</rows>
<schema type="xmla"/>
<measures values=@(new string[] {"[Measures].[Reseller Freight Cost]"} )
></measures>
<transport>
<read url="https://demos.telerik.com/olap/msmdpump.dll" datatype="text"
content-type="text/xml" type="POST" />
<connection catalog="Adventure Works DW 2008R2" cube="Adventure
Works"></connection>
</transport>
</kendo-pivotdatasource>
<kendo-pivotconfigurator name="configurator" datasource-id="pivotSource">
</kendo-pivotconfigurator>
<kendo-pivotgrid name="pivotgrid" datasource-id="pivotSource">
</kendo-pivotgrid>
@(Html.Kendo().PivotConfigurator()
.Name("configurator")
.Filterable(true)
.Sortable()
.Height(570)
1015
Telerik UI for ASP.NET Core
)
@(Html.Kendo().PivotGrid()
.Name("pivotgrid")
.ColumnWidth(200)
.Height(570)
.Filterable(true)
.Sortable()
.Configurator("#configurator")
.DataSource(dataSource => dataSource.
Xmla()
.Columns(columns => {
columns.Add("[Date].[Calendar]").Expand(true);
columns.Add("[Product].[Category]");
})
.Rows(rows => rows.Add("[Geography].[City]"))
.Measures(measures => measures.Values(new string[]{"[Measures].[Reseller
Freight Cost]"}))
.Transport(transport => transport
.Connection(connection => connection
.Catalog("Adventure Works DW 2008R2")
.Cube("Adventure Works"))
.Read(read => read
.Url("https://demos.telerik.com/olap/msmdpump.dll")
.DataType("text")
.ContentType("text/xml")
.Type(HttpVerbs.Post)
)
)
.Events(e => e.Error("onError"))
)
)
See Also
Basic Usage of the PivotGrid TagHelper for ASP.NET Core (Demo)
Server-Side API
1016
Telerik UI for ASP.NET Core
The Spreadsheet allows you to edit and visualize tabular data by using cell formatting options,
styles, and themes.
<kendo-spreadsheet name="spreadsheet"></kendo-spreadsheet>
Basic Configuration
The Spreadsheet TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().Spreadsheet()
.Name("spreadsheet")
.HtmlAttributes(new { style = "width:100%" })
.Excel(excel => excel
.ProxyURL(Url.Action("Index_Save", "Spreadsheet"))
)
.Pdf(pdf => pdf
.ProxyURL(Url.Action("Index_Save", "Spreadsheet"))
)
.Sheets(sheets =>
{
sheets.Add()
.Name("Food Order")
.MergedCells("A1:G1", "C15:E15")
.Columns(columns =>
{
columns.Add().Width(100);
columns.Add().Width(215);
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(115);
columns.Add().Width(155);
})
.Rows(rows =>
{
rows.Add().Height(70).Cells(cells =>
{
cells.Add()
.Value("Invoice #52 - 06/23/2015")
.FontSize(32)
.Background("rgb(96,181,255)")
1017
Telerik UI for ASP.NET Core
.TextAlign(SpreadsheetTextAlign.Center)
.Color("white");
});
rows.Add().Height(25).Cells(cells =>
{
cells.Add()
.Value("ID")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Product")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Quantity")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Price")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Tax")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Amount")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Background("rgb(167,214,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(216321)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Calzone")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
1018
Telerik UI for ASP.NET Core
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(12.39)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C3*D3*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C3*D3+E3")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(546897)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Margarita")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(2)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(8.79)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C4*D4*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C4*D4+E4")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
1019
Telerik UI for ASP.NET Core
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(456231)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Pollo Formaggio")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(13.99)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C5*D5*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C5*D5+E5")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(455873)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Greek Salad")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
1020
Telerik UI for ASP.NET Core
.Value(9.49)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C6*D6*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C6*D6+E6")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(456892)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Spinach and Blue Cheese")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(3)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(11.49)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C7*D7*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C7*D7+E7")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
1021
Telerik UI for ASP.NET Core
{
cells.Add()
.Value(546564)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Rigoletto")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(1)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(10.99)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C8*D8*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C8*D8+E8")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(789455)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Creme Brulee")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(5)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(6.99)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
1022
Telerik UI for ASP.NET Core
.Format("$#,##0.00");
cells.Add()
.Formula("C9*D9*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C9*D9+E9")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(123002)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Radeberger Beer")
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(4)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(4.99)
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C10*D10*0.2")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)")
.Formula("C10*D10+E10")
.Format("$#,##0.00");
cells.Add()
.Background("rgb(229,243,255)");
});
rows.Add().Cells(cells =>
{
cells.Add()
.Value(564896)
1023
Telerik UI for ASP.NET Core
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value("Budweiser Beer")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Value(3)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Center);
cells.Add()
.Value(4.49)
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)")
.Format("$#,##0.00");
cells.Add()
.Formula("C11*D11*0.2")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Formula("C11*D11+E11")
.Format("$#,##0.00")
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)");
});
rows.Add().Index(11).Cells(cells =>
{
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
1024
Telerik UI for ASP.NET Core
cells.Add()
.Background("rgb(229,243,255)")
.Color("rgb(0,62,117)");
});
rows.Add().Index(12).Cells(cells =>
{
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
cells.Add()
.Background("rgb(255,255,255)")
.Color("rgb(0,62,117)");
});
rows.Add().Index(13).Cells(cells =>
{
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Background("rgb(167,214,255)");
cells.Add()
.Value("Tip")
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.TextAlign(SpreadsheetTextAlign.Right);
cells.Add()
.Background("rgb(167,214,255)")
.Color("rgb(0,62,117)")
.Formula("SUM(F3:F11)*0.1")
.Format("$#,##0.00")
1025
Telerik UI for ASP.NET Core
.Bold(true);
cells.Add()
.Background("rgb(167,214,255)");
});
rows.Add().Index(14).Height(50).Cells(cells =>
{
cells.Add()
.Index(0)
.Background("rgb(193,226,255)");
cells.Add()
.Index(1)
.Background("rgb(193,226,255)");
cells.Add()
.Value("Total Amount")
.Index(2)
.TextAlign(SpreadsheetTextAlign.Right)
.Color("rgb(0,62,117)")
.FontSize(20)
.Background("rgb(193,226,255)");
cells.Add()
.Index(5)
.Background("rgb(193,226,255)")
.Color("rgb(0,62,117)")
.Formula("SUM(F3:F14)")
.Format("$#,##0.00")
.FontSize(20)
.Bold(true);
cells.Add()
.Index(6)
.Background("rgb(193,226,255)");
});
});
})
)
<kendo-spreadsheet name="spreadsheet" style="width: 100%">
<excel proxy-url="@Url.Action(" TagHelper_Save", "Spreadsheet" )" />
<pdf proxy-url="@Url.Action("TagHelper_Save", "Spreadsheet")" />
<sheets>
<sheet name="FoodOrder" merged-cells="@mergedCells">
<columns>
<sheet-column width="100" />
<sheet-column width="215" />
<sheet-column width="115" />
<sheet-column width="115" />
<sheet-column width="115" />
<sheet-column width="155" />
</columns>
<rows>
<sheet-row height="70">
<cells>
<cell value="Invoice #52 - 06/23/2015" font-size="32" background="rgb(96, 181,
255)" text-align="SpreadsheetTextAlign.Center" color="white">
</cell>
</cells>
1026
Telerik UI for ASP.NET Core
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="ID" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell value="Product" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell value="Quantity" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell value="Price" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell value="Tax" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell value="Amount" background="rgb(167,214,255)" color="rgb(0,62,117)"
text-align="SpreadsheetTextAlign.Center"></cell>
<cell background="rgb(167,214,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="216321" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="Calzone" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="1" background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
<cell value="12.39" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C3*D3*0.2" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C3*D3+E3" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="546897" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="Margarita" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="2" background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell value="8.79" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C4*D4*0.2" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C4*D4+E4" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="456231" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="Pollo Formaggio" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="1" background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
<cell value="13.99" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C5*D5*0.2" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C5*D5+E5" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
1027
Telerik UI for ASP.NET Core
<cell background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="455873" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="Greek Salad" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="1" background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell value="9.49" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C6*D6*0.2" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C6*D6+E6" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="456892" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="Spinach and Blue Cheese" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="1" background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
<cell value="11.49" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C7*D7*0.2" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C7*D7+E7" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="546564" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="Rigoletto" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="1" background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell value="10.99" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C8*D8*0.2" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C8*D8+E8" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="789455" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="Creme Brulee" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="5" background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
<cell value="6.99" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C9*D9*0.2" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C9*D9+E9" format="$#,##0.00" background="rgb(255,255,255)"
1028
Telerik UI for ASP.NET Core
color="rgb(0,62,117)"></cell>
<cell background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="123002" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="Radeberger Beer" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell value="4" background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell value="4.99" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C10*D10*0.2" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C10*D10+E10" format="$#,##0.00" background="rgb(229,243,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell value="564896" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="Budweiser Beer" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell value="3" background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
<cell value="4.49" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C11*D11*0.2" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell formula="C11*D11+E11" format="$#,##0.00" background="rgb(255,255,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(255,255,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(229,243,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="25">
<cells>
<cell background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell value="Tip:" text-align="SpreadsheetTextAlign.Right"
vertical-align="SpreadsheetVerticalAlign.Bottom" background="rgb(193,226,255)"
color="rgb(0,62,117)"></cell>
<cell formula="SUM(F3:F11)*0.1" bold="true" format="$#,##0.00"
vertical-align="SpreadsheetVerticalAlign.Bottom" background="rgb(193,226,255)"
color="rgb(0,62,117)"></cell>
<cell background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
<sheet-row height="50">
1029
Telerik UI for ASP.NET Core
<cells>
<cell index="0" background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell index="1" background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell index="2" value="Total Amount: " text-align="SpreadsheetTextAlign.Right"
background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
<cell index="5" formula="SUM(F3:F13)" bold="true" format="$#,##0.00"
vertical-align="SpreadsheetVerticalAlign.Bottom" background="rgb(193,226,255)"
color="rgb(0,62,117)"></cell>
<cell index="6" background="rgb(193,226,255)" color="rgb(0,62,117)"></cell>
</cells>
</sheet-row>
</rows>
</sheet>
</sheets>
</kendo-spreadsheet>
See Also
Basic Usage of the Spreadsheet TagHelper for ASP.NET Core (Demo)
Server-Side API
1030
Telerik UI for ASP.NET Core
Data Binding
You can bind the individual sheets of the Spreadsheet to a DataSource instance.
<kendo-spreadsheet name="spreadsheet" style="width: 100%">
<excel proxy-url="@Url.Action(" TagHelper_Save", "Spreadsheet" )" />
<pdf proxy-url="@Url.Action("TagHelper_Save", "Spreadsheet")" />
<sheets>
<sheet name="Products">
<datasource batch="true">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Products"
datatype="jsonp" />
<create url="https://demos.telerik.com/kendo-ui/service/Products/Create"
datatype="jsonp" />
<update url="https://demos.telerik.com/kendo-ui/service/Products/Update"
datatype="jsonp" />
<destroy url="https://demos.telerik.com/kendo-ui/service/Products/Destroy"
datatype="jsonp" />
</transport>
<schema>
<model id="ProductID">
<fields>
<field type="number" name="ProductID"></field>
<field type="string" name="ProductName"></field>
<field type="number" name="UnitPrice"></field>
<field type="boolean" name="Discontinued"></field>
<field type="number" name="UnitsInStock"></field>
</fields>
</model>
</schema>
</datasource>
</sheet>
</sheets>
</kendo-spreadsheet>
See Also
Basic Usage of the Spreadsheet TagHelper for ASP.NET Core (Demo)
Server-Side API
1031
Telerik UI for ASP.NET Core
The TreeList enables the display of self-referencing tabular data and allows sorting, filtering, and
data editing.
<kendo-treelist name="treelist">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<kendo-treelist datasource-id="dataSource" name="treelist">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<script>
$(function () {
// Get reference to the kendo.ui.TreeList instance
var treelist = $("#treelist").data("kendoTreeList");
})
1032
Telerik UI for ASP.NET Core
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
@(Html.Kendo().TreeList<dynamic>()
.Name("treelist")
.Columns(x =>
{
x.Add().Field("Name");
x.Add().Field("Position");
})
.DataSource("dataSource")
)
<script>
$(function () {
// Get a reference to the kendo.ui.TreeList instance.
var treelist = $("#treelist").data("kendoTreeList");
})
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
See Also
Basic Usage of the TreeList TagHelper for ASP.NET Core (Demo)
Server-Side API
1033
Telerik UI for ASP.NET Core
Data Binding
The TreeList provides options for binding it to local and remote data.
Local Data
The following example demonstrates how to initialize and bind the TreeList to local data.
<kendo-treelist datasource-id="dataSource" name="treelist">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<script>
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
@(Html.Kendo().TreeList<dynamic>()
.Name("treelist")
.Columns(x=> {
x.Add().Field("Name");
x.Add().Field("Position");
})
.DataSource("dataSource")
)
<script>
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
Remote Data
To bind the TreeListDataSource to remote data and make it load items from a web service, use
the remote data binding functionality. It enables the retrieval of data from the server and the saving
of the TreeList data items in the server database.
1034
Telerik UI for ASP.NET Core
The following example demonstrates how to enable the remote binding for the TreeList by setting
the DataSource transport. The parentId is mapped from the ReportsTo field by the
<treelist-model id="EmployeeId" parent-id="ReportsTo" expanded="true"> line. The
TreeList renders its hierarchy based on the parentId-id relationship.
When you use the schema.model.fields configuration, list all fields. Set the field which represents
the id of the event through the schema.model.id. If these are not set, they will still work for
displaying the data, but will post incomplete objects on the server when the items are edited.
<kendo-treelist name="treelist" height="540">
<treelist-datasource name="dataSource" >
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/EmployeeDirectory/All"
datatype="jsonp" />
</transport>
<schema type="json">
<treelist-model id="EmployeeId" parent-id="ReportsTo" expanded="true">
<fields>
<field name="ReportsTo" nullable="true"></field>
<field name="EmployeeId" type="number"></field>
<field name="Extension" type="number"></field>
</fields>
</treelist-model>
</schema>
</treelist-datasource>
<columns>
<treelist-column field="FirstName" title="First Name"
width="280px"></treelist-column>
<treelist-column field="LastName" title="Last Name"
width="160px"></treelist-column>
<treelist-column field="Position"></treelist-column>
<treelist-column field="Phone" width="200px"></treelist-column>
<treelist-column field="Extension" width="140px"></treelist-column>
<treelist-column field="Address"></treelist-column>
</columns>
</kendo-treelist>
@(Html.Kendo().TreeList<Kendo.Mvc.Examples.Models.TreeList.EmployeeDirectoryRemoteMode
l>()
.Name("treelist")
.Columns(x=> {
x.Add().Field(f=> f.FirstName).Title("First Name").Width(200);
x.Add().Field(f=> f.LastName).Title("Last Name").Width(160);
x.Add().Field(f=> f.Position);
x.Add().Field(f=> f.Phone).Width(200);
x.Add().Field(f=> f.Extension).Width(140);
x.Add().Field(f=> f.Address);
})
.DataSource(x=>
x.Read(read => read.Action("Index", "EmployeeDirectory"))
.Model(m=> {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
m.Field(f => f.FirstName);
m.Field(f => f.LastName);
m.Field(f => f.ReportsTo);
m.Field(f => f.Position);
m.Field(f => f.Phone);
1035
Telerik UI for ASP.NET Core
m.Field(f => f.Extension);
m.Field(f => f.Address);
})
)
)
See Also
Basic Usage of the TreeList TagHelper for ASP.NET Core (Demo)
Server-Side API
1036
Telerik UI for ASP.NET Core
Client-Side Paging
The TreeList supports client-side paging for large sets of data.
Remember to set a PageSize. You can define a PageSize in the Pageable or in the DataSource
settings. If an already existing dataSource instance is passed to the TreeList, then the PageSize
option has to be set in the dataSource settings and not in the Pageable settings.
<kendo-treelist name="treelist" height="540">
<treelist-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/EmployeeDirectory/All"
datatype="jsonp" />
</transport>
<schema type="json">
<treelist-model id="EmployeeId" parent-id="ReportsTo" expanded="true">
<fields>
<field name="ReportsTo" nullable="true"></field>
<field name="EmployeeId" type="number"></field>
<field name="Extension" type="number"></field>
</fields>
</treelist-model>
</schema>
</treelist-datasource>
<columns>
<treelist-column field="FirstName" title="First Name" width="280px"
template-id="photo-template"></treelist-column>
<treelist-column field="LastName" title="Last Name"
width="160px"></treelist-column>
<treelist-column field="Position"></treelist-column>
<treelist-column field="Phone" width="200px"></treelist-column>
<treelist-column field="Extension" width="140px"></treelist-column>
<treelist-column field="Address"></treelist-column>
</columns>
<pageable page-size="15" page-sizes="new int[] { 5,15,20}"></pageable>
</kendo-treelist>
@(Html.Kendo().TreeList<EmployeeDirectoryModel>()
.Name("treelist")
.Columns(columns =>
{
columns.Add().Field(e => e.FirstName).Width(220).TemplateId("photo-template");
columns.Add().Field(e => e.LastName).Width(160);
columns.Add().Field(e => e.Position);
columns.Add().Field(e => e.Phone).Width(200);
columns.Add().Field(e => e.Extension).Width(140);
columns.Add().Field(e => e.Address);
})
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Read(read => read.Action("All", "EmployeeDirectory"))
1037
Telerik UI for ASP.NET Core
.ServerOperation(false)
.Model(m => {
m.Id(f => f.EmployeeId);
m.ParentId(f => f.ReportsTo);
m.Expanded(true);
m.Field(f => f.FirstName);
m.Field(f => f.LastName);
m.Field(f => f.ReportsTo);
})
)
.Height(540)
.Pageable(p => p.PageSize(15)
.PageSizes(true)
)
)
</script>
The root TreeList items have their parentId field set to the default value for no parent. By default,
the value is null and can be configured through the
dataSource.schema.model.fields[FIELD_NAME].defaultValue option.
If you use client-side paging together with editing, the user adds an item, and the id field of the
model has to be nullable (for example, int?), then you have to configure the model so that it
features a default id field value on the client-side which is different from the default parentId field
value. In such cases, the default value of the id field (null) will equal the default parentId field
value (null) which creates a circular dependency. To avoid this issue, set the default id field to a
different value—for example, zero.
<kendo-treelist name="treelist" height="540">
<treelist-datasource>
...
<schema type="json">
<treelist-model id="EmployeeId" parent-id="ReportsTo" expanded="true">
<fields>
<field name="EmployeeId" type="number" default-value="0"></field>
<field name="ReportsTo" nullable="true"></field>>
</fields>
</treelist-model>
</schema>
</treelist-datasource>
...
</kendo-treelist>
See Also
Basic Usage of the TreeList TagHelper for ASP.NET Core (Demo)
Server-Side API
1038
Telerik UI for ASP.NET Core
<kendo-treelist datasource-id="dataSource" name="treelist">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<script>
$(function () {
// Get a reference to the kendo.ui.TreeList instance.
var treelist = $("#treelist").data("kendoTreeList");
// Use the expand method to expand the first row.
treelist.expand($("#treelist tbody>tr:eq(0)"));T
})
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
@(Html.Kendo().TreeList<dynamic>()
.Name("treelist")
.Columns(x=> {
x.Add().Field("Name");
x.Add().Field("Position");
})
.DataSource("dataSource")
)
<script>
$(function () {
// Get a reference to the kendo.ui.TreeList instance.
var treelist = $("#treelist").data("kendoTreeList");
// Use the expand method to expand the first row.
treelist.expand($("#treelist tbody>tr:eq(0)"));T
})
var dataSource = new kendo.data.TreeListDataSource({
1039
Telerik UI for ASP.NET Core
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
Events
The TreeList supports a set of eventsto which you can subscribe.
Specify the JavaScript function which will handle the event during the initialization of the
widget, or
Use the bind method of the widget after initialization.
The event handler is the JavaScript function which is invoked when the event is fired. The argument
of the event handler is a JavaScript object which contains event-specific data. Get a reference of the
widget, which fired the event, through the sender field of the event argument. The function context
of the event handler, which is available through the this keyword, is set to the instance of the
widget which fired the event.
The following example demonstrates how to subscribe to a TreeList event during the initialization of
the widget.
<kendo-treelist datasource-id="dataSource" name="treelist" on-data-bound="dataBound">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<script>
function dataBound(e) {
console.log("dataBound");
}
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
@(Html.Kendo().TreeList<dynamic>()
.Name("treelist")
.Columns(x =>
1040
Telerik UI for ASP.NET Core
{
x.Add().Field("Name");
x.Add().Field("Position");
})
.DataSource("dataSource")
.Events(x=> x.DataBound("dataBound"))
)
<script>
function dataBound(e) {
console.log("dataBound");
}
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
The following example demonstrates how to subscribe to a TreeList event by using the bind
method.
<kendo-treelist datasource-id="dataSource" name="treelist">
<columns>
<treelist-column field="Name"></treelist-column>
<treelist-column field="Position"></treelist-column>
</columns>
</kendo-treelist>
<script>
$(function () {
$("#treelist").data("kendoTreeList").bind('dataBound', dataBound);
})
function dataBound(e) {
console.log("dataBound");
}
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
@(Html.Kendo().TreeList<dynamic>()
.Name("treelist")
.Columns(x =>
{
x.Add().Field("Name");
x.Add().Field("Position");
1041
Telerik UI for ASP.NET Core
})
.DataSource("dataSource")
)
<script>
$(function () {
$("#treelist").data("kendoTreeList").bind('dataBound', dataBound);
})
function dataBound(e) {
console.log("dataBound");
}
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ id: 1, parentId: null, Name: "Jane Smith", Position: "CEO" },
{ id: 2, parentId: 1, Name: "Alex Sells", Position: "EVP Sales" },
{ id: 3, parentId: 1, Name: "Bob Price", Position: "EVP Marketing" }
]
})
</script>
See Also
Basic Usage of the TreeList TagHelper for ASP.NET Core (Demo)
Server-Side API
1042
Telerik UI for ASP.NET Core
Search Panel
Out of the box, the TreeList enables the users to search through its data by using the search panel.
Under the hood, the search panel uses filtering to show only the relevant records in the TreeList.
Getting Started
To enable the search panel functionality, include the Search option to the toolbar configuration.
When the server operations are enabled, you can search only by using string fields. Using the
Contains filter operation is available only for string types.
<kendo-treelist name="treelist" height="550">
<toolbar>
<toolbar-button name="search"></toolbar-button>
</toolbar>
</kendo-treelist>
You can also customize which fields to search through the data when a value is entered in the
search input.
...
<kendo-treelist name="treelist " height="550">
<search fields="@(new string[] { "ContactName", "Country"})">
</search>
Known Limitations
When filtering is enabled in the filter textboxes for all TreeList columns will be populated with the
value entered in the search textbox.
See Also
Server-Side API
Knowledge Base Section
1043
Telerik UI for ASP.NET Core
<kendo-datasource name="datasource"></kendo-datasource >
Basic Configuration
The DataSource TagHelper configuration options are passed as attributes of the tag. The
DataSource is an abstraction for binding the Kendo UI widgets to local and remote data and to
handle various data operations with the databound Tag Helpers.
<kendo-datasource name="dataSource" type="DataSourceTagHelperType.Ajax"
server-operation="false" page-size="5">
<transport>
<read url="/DataSource/Products_Read" />
</transport>
<sorts>
<sort field="fieldName" direction="asc" />
</sorts>
</kendo-datasource>
@(Html.Kendo().DataSource<Kendo.Mvc.Examples.Models.ProductViewModel>()
.Name("dataSource1")
.Ajax(dataSource => dataSource
.Read(read => read.Action("Products_Read", "DataSource"))
.ServerOperation(false)
.PageSize(5)
.Sort(sort => sort.Add("FieldName").Ascending())
)
)
1044
Telerik UI for ASP.NET Core
See Also
Basic Usage of the DataSource TagHelper for ASP.NET Core (Demo)
Server-Side API
1045
Telerik UI for ASP.NET Core
DataSource Types
The DataSource HtmlHelper supports built-in types of data binding.
Ajax
WebApi
Custom
Ajax DataSource
You have to set the server operations together by using the server-operation property. This
approach is also applicable for the WebAPI type of binding.
<kendo-datasource name="dataSource" type="DataSourceTagHelperType.Ajax"
server-operation="false" page-size="5">
<transport>
<read url="/DataSource/Products_Read" />
</transport>
</kendo-datasource>
WebAPI DataSource
When you use the WebAPI DataSource type of data binding in an editable Grid, define the field types
in the schema to use the correct editors for the field.
<kendo-datasource name="dataSource1" type="DataSourceTagHelperType.WebApi"
server-operation="true">
<transport>
<read url="/api/Product" />
</transport>
<schema>
<model id="ProductID">
<fields>
<field name="ProductID" type="number"></field>
</fields>
</model>
</schema>
</kendo-datasource>
Custom DataSource
The Custom DataSource type of data binding is the default type of binding and provides full control
over the client-side API options of the Kendo UI for jQuery DataSource . For example, instead of using
the serverOperation property, which is only applicable for the Ajax and WebApi types of data
binding, you have to separately state the server operations (server-filtering, server-sorting,
1046
Telerik UI for ASP.NET Core
The custom DataSource type of data binding is suitable for working with the oData and oData-v4
services because of the typeproperty and of the usage of predefined transport and schema settings
for consuming such services. Since the custom type binding is the default type, you can omit it in the
DataSource declaration.
The following example demonstrates how to consume an OData service.
<kendo-datasource name="dataSource1" custom-type="odata">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders" />
</transport>
</kendo-datasource>
<kendo-grid name="grid" datasource-id="dataSource1">
<pageable enabled="true">
</pageable>
<columns>
<column field="ShipName"></column>
<column field="ShipCity"></column>
</columns>
<scrollable enabled="true" />
</kendo-grid>
<kendo-datasource name="dataSource1">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Products"
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json"
for same-domain requests.
/>
</transport>
</kendo-datasource>
<kendo-grid name="grid" datasource-id="dataSource1">
<pageable enabled="true">
</pageable>
<columns>
<column field="ProductName"></column>
<column field="UnitPrice" format="{0:c}"></column>
<column field="UnitsInStock"></column>
<column field="Discontinued"></column>
</columns>
<scrollable enabled="true" />
</kendo-grid>
See Also
Server-Side API
1047
Telerik UI for ASP.NET Core
The Map displays geospatial information organized in layers and is supported for both desktop and
mobile devices. The layers which the Map supports are tile, shape (vector), and marker layers.
<kendo-map name="map" center="new double[] { 30.268107, -97.744821 }"
zoom="3"></kendo-map>
Basic Configuration
The Map TagHelper configuration options are passed as attributes of the tag.
<kendo-map name="map" center="new double[] { 30.268107, -97.744821 }" zoom="3">
<layer-defaults>
<map-marker>
<tooltip>
<popup-animation>
<open duration="1200" effects="zoom:in" />
</popup-animation>
</tooltip>
</map-marker>
</layer-defaults>
<markers>
<map-marker location="new double[] { 30.268107, -97.744821 }"
shape="MapMarkersShape.PinTarget">
<tooltip content="Austin, TX"></tooltip>
</map-marker>
</markers>
<layers>
<layer type="MapLayerType.Bing"
imagery-set="MapLayersImagerySet.AerialWithLabels"
key="AqaPuZWytKRUA8Nm5nqvXHWGL8BDCXvK8onCl2PkC581Zp3T_fYAQBiwIphJbRAK">
</layer>
</layers>
</kendo-map>
@(Html.Kendo().Map()
.Name("map")
.Center(30.268107, -97.744821)
.Zoom(3)
.Layers(layers =>
1048
Telerik UI for ASP.NET Core
{
layers.Add()
.Type(MapLayerType.Bing)
.ImagerySet(MapLayersImagerySet.AerialWithLabels)
.Key("AqaPuZWytKRUA8Nm5nqvXHWGL8BDCXvK8onCl2PkC581Zp3T_fYAQBiwIphJbRAK");
})
.Markers(markers =>
{
markers.Add()
.Location(30.268107, -97.744821)
.Shape(MapMarkersShape.PinTarget)
.Tooltip(tooltip => tooltip.Content("Austin, TX"));
})
)
See Also
Basic Usage of the Map TagHelper for ASP.NET Core (Demo)
Server-Side API
1049
Telerik UI for ASP.NET Core
The AutoComplete provides suggestions depending on the typed text and allows multiple value
entries.
<kendo-autocomplete name="products"
filter="FilterType.StartsWith"></kendo-autocomplete>
Basic Configuration
The AutoComplete TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().AutoComplete()
.Name("products2")
.DataTextField("ProductName")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.DataSource(source =>
{
source
.Read(read =>
{
read.Action("GetProducts", "Home")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
<script>
function onAdditionalData() {
return {
text: $("#products").val()
};
}
</script>
<kendo-autocomplete name="products" filter="FilterType.Contains"
datatextfield="ProductName"
1050
Telerik UI for ASP.NET Core
min-length="3" style="width: 100%;">
<datasource type="DataSourceTagHelperType.Custom" server-filtering="true">
<transport>
<read url="@Url.Action("GetProducts", "Home")" data="onAdditionalData" />
</transport>
</datasource>
</kendo-autocomplete>
<script>
function onAdditionalData() {
return {
text: $("#products").val()
};
}
</script>
See Also
Basic Usage of the AutoComplete TagHelper for ASP.NET Core (Demo)
Server-Side API
1051
Telerik UI for ASP.NET Core
The ColorPicker provides suggestions depending on the typed text and allows multiple value entries.
<kendo-colorpicker name="picker">
<messages apply="Change" cancel="Close" />
</kendo-colorpicker>
Basic Configuration
The ColorPicker TagHelper configuration options are passed as attributes of the tag and through
nested tags (<messages>).
@(Html.Kendo().ColorPicker()
.Name("picker")
.Value("#fff")
.Messages(m => m.Apply("Change").Cancel("Close"))
.Events(events => events.Select("preview"))
)
<kendo-colorpicker name="picker" value="#fff" on-select="preview">
<messages apply="Change" cancel="Close" />
</kendo-colorpicker>
The ColorPalette tag helper configuration options are passed as attributes of the tag and through
nested tags (<tile-size>).
@(Html.Kendo().ColorPalette()
.Name("palette")
.Columns(4)
.TileSize(s => s.Width(34).Height(19))
.Palette(new string[] {
"#f0d0c9", "#e2a293", "#d4735e", "#65281a",
"#eddfda", "#dcc0b6", "#cba092", "#7b4b3a",
"#fcecd5", "#f9d9ab", "#f6c781", "#c87d0e",
"#e1dca5", "#d0c974", "#a29a36", "#514d1b",
"#c6d9f0", "#8db3e2", "#548dd4", "#17365d"
1052
Telerik UI for ASP.NET Core
})
.Events(events => events.Change("preview"))
)
@{
string[] colorPickerPalette = new string[] {
"#f0d0c9", "#e2a293", "#d4735e", "#65281a",
"#eddfda", "#dcc0b6", "#cba092", "#7b4b3a",
"#fcecd5", "#f9d9ab", "#f6c781", "#c87d0e",
"#e1dca5", "#d0c974", "#a29a36", "#514d1b",
"#c6d9f0", "#8db3e2", "#548dd4", "#17365d"
};
}
<kendo-colorpalette name="palette" columns="4" on-change="preview"
palette-colors="colorPickerPalette">
<tile-size height="19" width="34" />
</kendo-colorpalette>
See Also
Basic Usage of the ColorPicker TagHelper for ASP.NET Core (Demo)
Server-Side API
1053
Telerik UI for ASP.NET Core
The ComboBox displays a list of values and allows for a single selection from the list.
<kendo-combobox name="products" filter="FilterType.StartsWith"></kendo-combobox>
Basic Configuration
The ComboBox TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().ComboBox()
.Name("products")
.Placeholder("Select product")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%;" })
.Filter(FilterType.Contains)
.AutoBind(false)
.MinLength(3)
.DataSource(source => source
.Read(read => read.Action("GetProducts", "Home"))
)
)
<kendo-combobox name="products" filter="FilterType.Contains"
placeholder="Select product"
datatextfield="ProductName"
datavaluefield="ProductID"
auto-bind="false"
min-length="3" style="width: 100%;">
<datasource type="DataSourceTagHelperType.Custom">
<transport>
<read url="@Url.Action("GetProducts", "Home")" />
</transport>
</datasource>
</kendo-combobox>
1054
Telerik UI for ASP.NET Core
See Also
Basic Usage of the ComboBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1055
Telerik UI for ASP.NET Core
The DateInput represents an input field that recognizes and formats scheduling values such as
dates.
<kendo-dateinput name="dateinput1"></kendo-dateinput>
Basic Configuration
The DateInput TagHelper configuration options are passed as attributes of the tag.
<kendo-dateinput name="dateinput1" format="MMMM yyyy" value="DateTime.Now">
</kendo-dateinput>
@(Html.Kendo().DateInput()
.Name("dateinput1")
.Format("MMMM yyyy")
.Value(DateTime.Now)
)
Events
You can subscribe to all DateInput events.
<kendo-dateinput name="dateinput" style='width: 100%;' on-change="onChangeHandler">
</kendo-dateinput>
<script>
function onChangeHandler(e) {
// Add your logic here.
}
</script>
1056
Telerik UI for ASP.NET Core
@(Html.Kendo().DateInput()
.Name("dateinput")
.Events(e => e
.Change("dateInput_change")
)
)
<script>
function dateInput_change() {
//Handle the change event
}
</script>
// Place the following after the DateInput for ASP.NET Core declaration.
<script>
$(function() {
// The Name() of the DateInput is used to get its client-side instance.
var dateInput = $("#dateinput").data("kendoDateInput");
});
</script>
See Also
Basic Usage of the DateInput TagHelper for ASP.NET Core (Demo)
Server-Side API
1057
Telerik UI for ASP.NET Core
<kendo-datepicker name="datepicker1"></kendo-datepicker>
Basic Configuration
The DatePicker TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().DatePicker()
.Name("monthpicker")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
.Format("MMMM yyyy")
.Value(DateTime.Now)
)
<kendo-datepicker name="monthpicker" start="CalendarView.Year"
depth="CalendarView.Year"
format="MMMM yyyy" value="DateTime.Now">
</kendo-datepicker>
The ParseFormats option is of type string[] and can be assigned either by a ViewBag property or
by a property of the model.
@{
ViewBag.ParseDates = new string[] { "MMMM yyyy", "MMMM" };
}
<kendo-datepicker name="datepicker"
parse-formats="ViewBag.ParseDates"></kendo-datepicker>
See Also
1058
Telerik UI for ASP.NET Core
1059
Telerik UI for ASP.NET Core
The DateTimePicker allows the user to select a value from a calendar, a time drop-down list, or
through direct input.
<kendo-datetimepicker name="timepicker1"></kendo-datetimepicker>
Basic Configuration
The DateTimePicker TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().DateTimePicker()
.Name("end")
.Value(DateTime.Today)
.Min(DateTime.Today)
.Events(e => e.Change("endChange"))
)
<kendo-datetimepicker name="end" value="DateTime.Today"
min="DateTime.Today" on-change="endChange">
</kendo-datetimepicker>
The ParseFormats option is of type string[] and can be assigned either by a ViewBag property or
by a property of the model.
@{
ViewBag.ParseDates = new string[] { "MMMM yyyy", "MMMM" };
}
<kendo-datetimepicker name="datetimepicker"
parse-formats="ViewBag.ParseDates"></kendo-datetimepicker>
See Also
Basic Usage of the DateTimePicker TagHelper for ASP.NET Core (Demo)
1060
Telerik UI for ASP.NET Core
Server-Side API
1061
Telerik UI for ASP.NET Core
The DropDownList displays a list of values and allows for a single selection from the list. The user
input is restricted within the predefined options.
<kendo-dropdownlist name="products"
filter="FilterType.StartsWith"></kendo-dropdownlist>
Basic Configuration
The DropDownList TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().DropDownList()
.Name("products")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%;" })
.Filter(FilterType.Contains)
.DataSource(source => source
.Read(read => read.Action("GetProducts", "Home"))
)
)
<kendo-dropdownlist name="products" filter="FilterType.Contains"
placeholder="Select product"
datatextfield="ProductName"
datavaluefield="ProductID"
style="width: 100%;">
<datasource type="DataSourceTagHelperType.Custom">
<transport>
<read url="@Url.Action("GetProducts", "Home")" />
</transport>
</datasource>
</kendo-dropdownlist>
See Also
Basic Usage of the DropDownList TagHelper for ASP.NET Core (Demo)
1062
Telerik UI for ASP.NET Core
Server-Side API
1063
Telerik UI for ASP.NET Core
The DropDownTree represents an editor of hierarchical data, rendered in a tree-like structure, which
provides multiple selection option and custom nodes.
<kendo-dropdowntree name="dropdowntree1">
</kendo-dropdowntree>
Basic Configuration
The DropDownTree TagHelper configuration options are passed as attributes of the tag. You can
configure the items by binding the widget to <hierarchical-datasource>.
<kendo-dropdowntree name="dropdowntree1" datatextfield="FullName">
<hierarchical-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Employees"
datatype="jsonp" />
</transport>
<schema type="json">
<hierarchical-model id="EmployeeId" has-children="HasEmployees">
</hierarchical-model>
</schema>
</hierarchical-datasource>
</kendo-dropdowntree>
@(Html.Kendo().DropDownTree()
.Name("dropdowntree")
.Items(dropdowntree =>
{
dropdowntree.Add().Text("My Web Site")
.SpriteCssClasses("folder")
.Expanded(true)
.Items(root =>
{
root.Add().Text("images")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(images =>
{
1064
Telerik UI for ASP.NET Core
images.Add().Text("logo.png")
.SpriteCssClasses("image");
});
root.Add().Text("resources")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(resources =>
{
resources.Add().Text("pdf")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(pdf =>
{
pdf.Add().Text("prices.pdf")
.SpriteCssClasses("pdf");
});
resources.Add().Text("zip")
.SpriteCssClasses("folder");
});
root.Add().Text("about.html")
.SpriteCssClasses("html");
root.Add().Text("index.html")
.SpriteCssClasses("html");
});
})
)
See Also
Basic Usage of the DropDownTree TagHelper for ASP.NET Core (Demo)
Server-Side API
1065
Telerik UI for ASP.NET Core
The Editor allows you to create rich textual content through a What-You-See-Is-What-You-Get
(WYSIWYG) interface and generate widget value as an XHTML markup.
<kendo-editor name="editor">
</kendo-editor>
Basic Configuration
The tools collection of the Editor TagHelper is passed through the nest <tools> tag.
<kendo-editor name="editor">
<tools>
<tool name="bold" />
<tool name="italic" />
<tool name="underline" />
<tool name="fontName" />
</tools>
</kendo-editor>
@(Html.Kendo().Editor()
.Name("editor")
.Tools(tools => tools
.Clear()
.Bold()
.Italic()
.Underline()
.FontName()
)
)
You can adjust and set up the tools in the tools collection through the <tools> tag. To define their
items collection, use the <tool-items> and <tool-item> tags.
<kendo-editor name="editor">
<tools>
<tool name="fontName">
<tool-items>
1066
Telerik UI for ASP.NET Core
<tool-item text="Default site font" value="Arial,Verdana,sans-serif" />
<tool-item text="Monospaced font" value="monospace" />
</tool-items>
</tool>
</tools>
</kendo-editor>
@(Html.Kendo().Editor()
.Name("editor")
.Tools(tools => {
tools.Clear();
tools.FontName(items => items
.Add("Default site font", "Arial, Verdana, sans - serif")
.Add("Monospaced", "monospace")
);
})
)
To specify a chunk of content in the Editor TagHelper, use the <content> tag or the value attribute.
<kendo-editor name="editor">
<content>
<p>Some content.</p>
</content>
</kendo-editor>
@(Html.Kendo().Editor()
.Name("editor")
.Value(@<text>
<p>Some content.</p>
</text>)
)
The ImageBrowser and FileBrowser dialogs are configured through the <image-browser> and
<file-browser> tags.
<kendo-editor name="editor">
<image-browser file-types="*.png,*.gif,*.jpg,*.jpeg">
<transport upload-url="/ImageBrowser/Upload"
image-url="/shared/UserFiles/Images/{0}">
<create url="/ImageBrowser/Create"/>
<read url="/ImageBrowser/Read" />
<destroy url="/ImageBrowser/Destroy" />
</transport>
</image-browser>
<file-browser>
<transport upload-url="/FileBrowser/Upload"
file-url="/shared/UserFiles/Images/{0}">
<create url="/FileBrowser/Create" />
<read url="/FileBrowser/Read" />
<destroy url="/FileBrowser/Destroy" />
</transport>
</file-browser>
</kendo-editor>
1067
Telerik UI for ASP.NET Core
@(Html.Kendo().Editor()
.Name("editor")
.ImageBrowser(imageBrowser => imageBrowser
.Image("~/shared/UserFiles/Images/{0}")
.Read("Read", "ImageBrowser")
.Create("Create", "ImageBrowser")
.Destroy("Destroy", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
)
.FileBrowser(fileBrowser => fileBrowser
.File("~/shared/UserFiles/Images/{0}")
.Read("Read", "FileBrowser")
.Create("Create", "FileBrowser")
.Destroy("Destroy", "FileBrowser")
.Upload("Upload", "FileBrowser")
)
)
The serialization, deserialization and paste-cleanup settings are configured with the
<serialization>, <deserialization>, and <paste-cleanup> tags respectively.
<kendo-editor name="editor">
<deserialization custom="myDeserialization" />
<serialization custom="mySerialization" entities="false" />
<paste-cleanup custom="myPasteCleanup" keep-new-lines="true" />
</kendo-editor>
@(Html.Kendo().Editor()
.Name("editor")
.Deserialization(deserialization => deserialization.Custom("myDeserialization"))
.Serialization(serialization =>
serialization.Custom("mySerialization").Entities(false))
.PasteCleanup(pasteCleanup =>
pasteCleanup.Custom("myPasteCleanup").KeepNewLines(true))
)
To configure other Editor options, such as PDF export, immutables, rezisability or messages, use the
respective inner tags—<pdf>, <immutables>, <resizable>, or <messages>.
<kendo-editor name="editor">
<immutables enabled="true" />
<resizable toolbar="true" content="true" />
<pdf paper-size="A4" />
<messages bold="Strong" />
</kendo-editor>
@(Html.Kendo().Editor()
.Name("editor")
.Immutables(true)
.Resizable(resizable => resizable.Toolbar(true).Content(true))
.Pdf(pdf => pdf.PaperSize("A4"))
.Messages(messages => messages.Bold("Strong"))
)
1068
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Editor TagHelper for ASP.NET Core (Demo)
Server-Side API
1069
Telerik UI for ASP.NET Core
The ListBox provides suggestions depending on the typed text and allows multiple value entries.
displays a list of data that is contained in a box and allows single or multiple selection, reordering of
selected items, and deleting items and features keyboard navigation as well as the dragging and
dropping of items. You can also connect the ListBox with another list-box and customize the widget
with the use of templates, toolbar positioning, placeholder and hint, and localization of its command
buttons messages.
<kendo-listbox name="optional" connect-with="selected"
bind-to="ViewBag.Attendees">
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] {moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
<kendo-listbox name="selected" selectable="ListBoxSelectable.Multiple"
bind-to="new List<string>()">
</kendo-listbox>
@(Html.Kendo().ListBox().Name("optional")
.ConnectWith("selected")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.BindTo(ViewBag.Attendees)
)
@(Html.Kendo().ListBox().Name("selected")
.Selectable(ListBoxSelectable.Multiple)
.BindTo(new List<string>())
)
1070
Telerik UI for ASP.NET Core
See Also
Basic Usage of the ListBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1071
Telerik UI for ASP.NET Core
Data Binding
The ListBox provides options for binding it to server-side arrays, client-side arrays, and to remote data.
Server-Side Arrays
When you use complex data objects, apply the dataTextField and dataValueField properties to
notify the widget of your preferred binding behavior.
The following example demonstrates how to initialize the ListBox and bind it to a server-side array.
var data = new string[] {
"Washington",
"London",
"Canberra",
"Ottawa",
"Sofia",
"Moscow",
"Madrid"
};
<kendo-listbox name="listbox" bind-to="data">
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] { "moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
var data = new string[] {
"Washington",
"London",
"Canberra",
"Ottawa",
"Sofia",
"Moscow",
"Madrid"
};
@(Html.Kendo().ListBox().Name("listbox")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.BindTo(data)
)
1072
Telerik UI for ASP.NET Core
Client-Side Arrays
The following example demonstrates how to initialize the ListBox and bind it to a client-side array.
<kendo-listbox name="listbox" datasource-id="dataSource">
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] { "moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
<script>
var dataSource = new kendo.data.DataSource({
data: [
"Washington",
"London",
"Canberra",
"Ottawa",
"Sofia",
"Moscow",
"Madrid"]
})
</script>
@(Html.Kendo().ListBox().Name("listbox")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.DataSource("dataSource")
)
<script>
var dataSource = new kendo.data.DataSource({
data: [
"Washington",
"London",
"Canberra",
"Ottawa",
"Sofia",
"Moscow",
"Madrid"]
})
</script>
Remote Data
The following example demonstrates how to bind the Kendo UI ListBox TagHelper to a remote
service.
1073
Telerik UI for ASP.NET Core
<kendo-listbox name="listbox" datatextfield="ProductName"
datavaluefield="ProductID">
<datasource>
<transport>
<read datatype="jsonp"
url="https://demos.telerik.com/kendo-ui/service/Products" />
</transport>
</datasource>
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] { "moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
@(Html.Kendo().ListBox().Name("listbox")
.DataTextField("ProductName")
.DataValueField("ProductID")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.DataSource(x=>
x.Custom()
.Transport(y=> y.Read(z=>
z.Url("https://demos.telerik.com/kendo-ui/service/Products").DataType("jsonp"))))
)
See Also
Basic Usage of the ListBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1074
Telerik UI for ASP.NET Core
Selection
The ListBox provides a single and a multiple selection mode.
By default, the single selection mode of the ListBox is enabled. To set the multiple selection mode,
add selectable="ListBoxSelectable.Multiple". When the multiple selectino mode is
enabled, all selected items move together, that is, the selected items are transferred to another
Telerik UI ListBox TagHelper together or reordered as a set among other items.
You can reorder selected items by using any of the following approaches:
Currently, the ListBox does not support the drag-and-drop feature for multiple selected items.
<kendo-listbox name="listbox" datatextfield="ProductName"
datavaluefield="ProductID">
<datasource>
<transport>
<read datatype="jsonp"
url="https://demos.telerik.com/kendo-ui/service/Products" />
</transport>
</datasource>
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] { "moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
@(Html.Kendo().ListBox().Name("listbox")
.DataTextField("ProductName")
.Selectable(ListBoxSelectable.Multiple)
.DataValueField("ProductID")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.DataSource(x=>
x.Custom()
.Transport(y=> y.Read(z=>
z.Url("https://demos.telerik.com/kendo-ui/service/Products").DataType("jsonp"))))
)
1075
Telerik UI for ASP.NET Core
See Also
Basic Usage of the ListBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1076
Telerik UI for ASP.NET Core
You can also customize the drag-and-drop behavior of the widget by using its
draggable.placeholder and draggable.hint options.
<kendo-listbox name="listbox" template-id="template"
selectable="ListBoxSelectable.Multiple" datatextfield="ProductName"
datavaluefield="ProductID">
<draggable hint="hint" enabled="true" placeholder="placeholder" />
<datasource>
<transport>
<read datatype="jsonp"
url="https://demos.telerik.com/kendo-ui/service/Products" />
</transport>
</datasource>
<toolbar position="ListBoxToolbarPosition.Right"
tools='new string[] { "moveUp", "moveDown", "transferTo", "transferFrom",
"transferAllTo", "transferAllFrom", "remove"}' />
</kendo-listbox>
<script type="text/kendo-x-tmpl" id="template">
<h5 style="background-color:aqua">#=ProductName#</h5>
</script>
@(Html.Kendo().ListBox().Name("listbox")
.DataTextField("ProductName")
.TemplateId("template")
.Selectable(ListBoxSelectable.Multiple)
.DataValueField("ProductID")
.Toolbar(x => x.Position(ListBoxToolbarPosition.Right)
.Tools(y =>
{
y.MoveUp();
y.MoveDown();
y.TransferTo();
y.TransferFrom();
y.TransferAllTo();
y.TransferAllFrom();
y.Remove();
}))
.DataSource(x =>
x.Custom()
.Transport(y => y.Read(z =>
z.Url("https://demos.telerik.com/kendo-ui/service/Products").DataType("jsonp"))))
)
<script type="text/kendo-x-tmpl" id="template">
<h5 style="background-color:aqua">#=ProductName#</h5>
</script>
1077
Telerik UI for ASP.NET Core
See Also
Basic Usage of the ListBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1078
Telerik UI for ASP.NET Core
The MaskedTextBox enables a controlled text input that is based on a specific format.
<kendo-maskedtextbox name="ssn" mask="000-00-0000"
value="003-12-3456"></kendo-maskedtextbox>
Basic Configuration
The MaskedTextBox TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().MaskedTextBox()
.Name("phone_number")
.Mask("(999) 000-0000")
.Value("555 123 4567")
)
<kendo-maskedtextbox name="phone_number" mask="(999) 000-0000" value="555 123
4567"></kendo-maskedtextbox>
See Also
Basic Usage of the MaskedTextBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1079
Telerik UI for ASP.NET Core
MultiColumnComboBox TagHelper
Overview
The Telerik UI MultiColumnComboBox TagHelper for ASP.NET Core is a server-side wrapper for the
Kendo UI MultiColumnComboBox widget.
<kendo-multicolumncombobox name="products"
filter="FilterType.StartsWith"></kendo-multicolumncombobox>
Basic Configuration
The MultiColumnComboBox TagHelper configuration options are passed as attributes of the tag.
<kendo-multicolumnmulticolumncombobox name="products" filter="FilterType.Contains"
placeholder="Select product"
datatextfield="ProductName"
datavaluefield="ProductID"
auto-bind="false"
min-length="3" style="width: 100%;">
<datasource type="DataSourceTagHelperType.Custom">
<transport>
<read url="@Url.Action("GetProducts", "Home")" />
</transport>
</datasource>
</kendo-multicolumnmulticolumncombobox>
@(Html.Kendo().ComboBox()
.Name("products")
.Placeholder("Select product")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%;" })
.Filter(FilterType.Contains)
.AutoBind(false)
.MinLength(3)
.DataSource(source => source
.Read(read => read.Action("GetProducts", "Home"))
)
)
1080
Telerik UI for ASP.NET Core
See Also
Basic Usage of the MultiColumnComboBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1081
Telerik UI for ASP.NET Core
The MultiSelect displays a list of options and allows multiple selections from this list. The widget
represents a richer version of the <select> element and provides support for local and remote data
binding, item and tag templates, and configurable options for controlling the list behavior.
<kendo-multiselect name="products" filter="FilterType.StartsWith"></kendo-multiselect>
Basic Configuration
The MultiSelect TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().MultiSelect()
.Name("products")
.DataTextField("ProductName")
.DataValueField("ProductID")
.HtmlAttributes(new { style = "width:100%;" })
.Filter(FilterType.Contains)
.DataSource(source => source
.Read(read => read.Action("GetProducts", "Home"))
)
)
<kendo-multiselect name="products" filter="FilterType.Contains"
placeholder="Select product"
datatextfield="ProductName"
datavaluefield="ProductID"
style="width: 100%;">
<datasource type="DataSourceTagHelperType.Custom">
<transport>
<read url="@Url.Action("GetProducts", "Home")" />
</transport>
</datasource>
</kendo-multiselect>
See Also
1082
Telerik UI for ASP.NET Core
1083
Telerik UI for ASP.NET Core
The NumericTextBox converts an input element into a numeric, percentage, or currency textbox.
<kendo-numerictextbox name="numeric"></kendo-numerictextbox>
You can also bind the NumericTextBox to a particular model field by using the for attribute. This is
equivalent to using the Html.Kendo().NumericTextBoxFor<decimal>() HtmlHelper.
@model Kendo.Mvc.Examples.Models
<kendo-numerictextbox for="CustomerID"></kendo-numerictextbox>
Basic Configuration
The NumericTextBox TagHelper supports all the configuration options that the HtmlHelper does.
They are passed as attributes of the tag.
@(Html.Kendo().NumericTextBox<decimal>()
.Name("currency")
.Format("c")
.Min(0)
.Enable(true)
.Max(100)
.Value(30)
)
<kendo-numerictextbox name="currency" format="c" min="0"
enable="true" max="100" value="30">
</kendo-numerictextbox>
See Also
Basic Usage of the NumericTextBox TagHelper for ASP.NET Core (Demo)
Server-Side API
1084
Telerik UI for ASP.NET Core
The Rating allows to intuitively rate by selecting number of items stars from a predefined maximum
number of items.
<kendo-rating name="rating"></kendo-rating>
Basic Configuration
The Rating tag helper configuration options are passed as attributes of the tag.
<kendo-rating name="rating" min="1" max="6" value="3"></kendo-rating>
Events
You can subscribe to all Rating events.
<kendo-rating name="rating" on-change="onChange" on-select="onSelect"></kendo-rating>
<script>
function onChange(e) {
console.log(e);
}
function onSelect(e) {
console.log(e);
}
</script>
1085
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Rating Tag Helper for ASP.NET Core (Demo)
Server-Side API
1086
Telerik UI for ASP.NET Core
Selection
The Rating allows to control the selection behavior of the items by configuring the Selection
property:
Continuous Selection
This is the default selection behavior of the Rating. If not configured, the widget will automatically
set the Selectionproperty to "continuous":
<kendo-rating name="rating" selection="continuous"></kendo-rating>
Single Selection
Single selection can be configured by setting the Selectionproperty to "single":
<kendo-rating name="rating" min="1" max="6" value="3"
selection="single"></kendo-rating>
See Also
Server-Side API
1087
Telerik UI for ASP.NET Core
Precision
The widget allows to control the precision with which an item is selected by configuring the
Precisionproperty:
Item Precision
This is the default precision of the Rating. If not configured, the widget will automatically set the
Precisionproperty to "item":
<kendo-rating name="rating" precision="item"></kendo-rating>
Half Precision
Half precision can be configured by setting the Precisionproperty to "half":
With half precision the Rating widget allows to set decimal values. The passed value is rounded
during the rendering phase for the purpose of displaying full or half item based on the value:
<kendo-rating name="rating"
min="1"
max="6"
value="3.2"
precision="half">
</kendo-rating>
<br>
<kendo-rating name="rating2"
min="1"
max="6"
value="3.5"
precision="half">
</kendo-rating>
<br>
<kendo-rating name="rating3"
min="1"
max="6"
value="3.7"
precision="half">
</kendo-rating>
See Also
1088
Telerik UI for ASP.NET Core
Server-Side API
1089
Telerik UI for ASP.NET Core
Label
The Rating displays a label by default that shows the current value out of the max value in the format
3 / 5. If the widget does not have a selected value, the label will not be displayed initially and will be
toggled after an item is selected.
Default Label
<kendo-rating name="rating" min="1" max="6" value="3"></kendo-rating>
By default, the template automatically receives the value and maxValue in the data object. This
allows those properties to be used inside the template through the Kendo UI Templates syntax.
<kendo-rating name="rating" min="1" max="6" value="3">
<label template-id="rating-label-template" />
</kendo-rating>
<script id="rating-label-template" type="text/x-kendo-template">
<span>
#: value # out of #: maxValue #
</span>
</script>
<kendo-rating name="rating" min="1" max="6" value="3">
<label enabled="false" />
</kendo-rating>
See Also
Server-Side API
1090
Telerik UI for ASP.NET Core
Tooltip
Each Rating item displays a tooltip that is enabled by default and contains text equal to the item's
value.
Default Tooltips
<kendo-rating name="rating" min="1" max="6" value="3"></kendo-rating>
<kendo-rating name="rating" min="1" max="6" value="3" tooltip="false"></kendo-rating>
See Also
Server-Side API
1091
Telerik UI for ASP.NET Core
Templates
By default each Rating item is rendered with a star icon from the Kendo Web Font Icons. Modifying
the default icon could be achieved through the ItemTemplate, SelectedTemplateand
HoveredTemplateproperties.
Item Template
Specifies the template which is used for rendering the items of the Rating.
If the SelectedTemplate is not specified, the widget will use the default start icon for selected
items. Therefore, it is recommended to specify the SelectedTemplate when the ItemTemplate
option is used.
<kendo-rating name="rating"
min="1"
max="6"
value="3"
item-template-id="rating-item-template"
selected-template-id="rating-selected-template">
</kendo-rating>
<script id="rating-item-template" type="text/x-kendo-template">
<i class='k-icon k-i-heart-outline'></i>
</script>
<script id="rating-selected-template" type="text/x-kendo-template">
<i class='k-icon k-i-heart'></i>
</script>
Selected Template
Specifies the template which is used for rendering the selected state of the items.
If the ItemTemplate is not specified, the widget will use the default start icon for displaying the
normal state of the items. Therefore, it is recommended to specify the ItemTemplate when the
SelectedTemplate option is used.
Important
<kendo-rating name="rating"
min="1"
max="6"
value="3"
item-template-id="rating-item-template"
selected-template-id="rating-selected-template">
</kendo-rating>
<script id="rating-item-template" type="text/x-kendo-template">
<i class='k-icon k-i-heart-outline'></i>
1092
Telerik UI for ASP.NET Core
</script>
<script id="rating-selected-template" type="text/x-kendo-template">
<i class='k-icon k-i-heart'></i>
</script>
Hovered Template
Specifies the template which is used for rendering the hovered state of the items.
If the itemTemplate is not specified, the widget will use the default start icon for displaying the
normal and selected state of the items.
Important
<kendo-rating name="rating"
min="1"
max="6"
value="3"
hovered-template-id="rating-selected-template">
</kendo-rating>
<script id="rating-hovered-template" type="text/x-kendo-template">
<i class='k-icon k-i-heart'></i>
</script>
See Also
Server-Side API
1093
Telerik UI for ASP.NET Core
The Slider provides a rich input for selecting numeric values nd can be either a Slider which presents
one handle and two opposing buttons for selecting a single numeric value or a Slider which presents
two handlers for defining a range of numeric values.
<kendo-slider name="slider"
increase-button-title="Right"
decrease-button-title="Left"
min="0" max="30"
small-step="1"
large-step="10"
value="18" class="temperature" title="slider"></kendo-slider>
Basic Configuration
The Slider TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().Slider()
.Name("slider")
.IncreaseButtonTitle("Right")
.DecreaseButtonTitle("Left")
.Min(0)
.Max(30)
.SmallStep(1)
.LargeStep(10)
.Value(18)
.HtmlAttributes(new { @class = "temperature" }))
<kendo-slider name="slider"
increase-button-title="Right"
decrease-button-title="Left"
min="0" max="30"
small-step="1"
large-step="10"
value="18" class="temperature" title="slider"></kendo-slider>
The following example demonstrates how to define the RangeSlider by using the RangeSlider
TagHelper.
1094
Telerik UI for ASP.NET Core
<kendo-rangeslider name="rangeslider" class="humidity"
min="0" max="10"
small-step="1"
large-step="10"></kendo-rangeslider>
See Also
Basic Usage of the Slider TagHelper for ASP.NET Core (Demo)
Server-Side API
1095
Telerik UI for ASP.NET Core
The Switch displays two exclusive choices. With the new Switch variables introduced in the Kendo UI
for jQuery R1 2019 release, the default styling of the Switch component for each of the Sass-based
Kendo UI for jQuery themescan be modified to match the desired custom layout.
<kendo-switch name="switch"
checked="true"></kendo-switch>
Basic Configuration
The configuration options of the Switch TagHelper are passed as attributes of the tag.
<kendo-switch name="switch"
checked="true"
enabled="true"></kendo-switch>
@(Html.Kendo().Switch()
.Name("switch")
.Checked(true)
.Enabled(true))
See Also
Basic Usage of the Switch TagHelper for ASP.NET Core (Demo)
Server-Side API
1096
Telerik UI for ASP.NET Core
The TimePicker enables users to select time values from a predefined list or enter new ones.
<kendo-timepicker name="timepicker1"></kendo-timepicker>
Basic Configuration
The TimePicker TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().TimePicker()
.Name("end")
.Value("8:30 AM")
.Min("8:00 AM")
.Max("7:30 AM")
)
<kendo-timepicker name="end" value="new DateTime(1900, 1, 1, 8, 30, 0)"
min="new DateTime(1900, 1, 1, 8, 0, 0)" max="new DateTime(1900, 1, 1, 7, 30,
0)">
</kendo-timepicker>
The ParseFormats option is of type string[] and can be assigned either by a ViewBag property or
by a property of the model.
@{
ViewBag.ParseDates = new string[] { "MMMM yyyy", "MMMM" };
}
<kendo-timepicker name="timepicker"
parse-formats="ViewBag.ParseDates"></kendo-timepicker>
See Also
Basic Usage of the TimePicker TagHelper for ASP.NET Core (Demo)
1097
Telerik UI for ASP.NET Core
Server-Side API
1098
Telerik UI for ASP.NET Core
The Upload uses progressive enhancement to deliver the best possible uploading experience to
users, without requiring extra developer effort.
To ensure the tag-naming consistency across the Telerik UI for ASP.NET Core suite, the Kendo UI R1
2018 release introduces a change in the tag names of the Upload. As of the Kendo UI R1 2018
release:
<kendo-upload drop-zone="drop-zone1" name="test">
<async auto-upload="true" />
<validation allowed-extensions="@Model.Extensions" />
<files>
<file name="dummy" size="1024" />
</files>
</kendo-upload>
Basic Configuration
The Upload TagHelper configuration options are passed as attributes of the tag or attributes of the
nested composite and collection properties.
@(Html.Kendo().Upload()
.Name("upload1")
.DropZone("drop-zone1")
.Validation(v => v.AllowedExtensions(Model.Extensions))
.Files(f => f.Add().Name("dummy").Size(1024))
)
<kendo-upload drop-zone="drop-zone1" name="test">
<async auto-upload="true" />
<validation allowed-extensions="@Model.Extensions" />
<files>
<file name="dummy" size="1024" />
</files>
</kendo-upload>
1099
Telerik UI for ASP.NET Core
See Also
Basic Usage of the Upload TagHelper for ASP.NET Core (Demo)
Server-Side API
1100
Telerik UI for ASP.NET Core
@{
var messages = new Dictionary<string, string>() { { "custom", "Please choose
another Start Time." } };
var rules = new Dictionary<string, string>() { { "custom", "customFunction" }
};
}
<form id="ticketsForm" kendo-validator="true" kendo-messages="messages"
kendo-rules="rules">
<ul id="fieldlist">
<li>
<label for="fullname" class="required">Your Name</label>
@(Html.Kendo().TextBox()
.Name("fullname")
.HtmlAttributes(new { placeholder = "Full name", required = "required", style =
"width:220px" })
)
</li>
</ul>
</form>
See Also
Basic Usage of the Validator Helper for ASP.NET Core (Demo)
1101
Telerik UI for ASP.NET Core
<kendo-arclgauge name="gauge"></kendo-arcgauge>
Basic Configuration
The ArcGauge TagHelper configuration options are passed as attributes of the tag.
<kendo-arcgauge name="gauge" center-template="#:value#%" value="65">
<scale min="0" max="100">
</scale>
</kendo-arcgauge>
@(Html.Kendo().ArcGauge()
.Name("arcGauge")
.Value(65)
.Scale(x => x.Min(0).Max(100))
.CenterTemplate("#:value#%")
)
See Also
Basic Usage of the ArcGauge TagHelper for ASP.NET Core (Demo)
Server-Side API
1102
Telerik UI for ASP.NET Core
<kendo-lineargauge name="gauge"></kendo-lineargauge>
Basic Configuration
The LinearGauge TagHelper configuration options are passed as attributes of the tag.
<kendo-lineargauge name="gauge">
<lineargauge-pointers>
<pointer value="10"></pointer>
</lineargauge-pointers>
<scale major-unit="20" minor-unit="2" min="-40" max="60">
<lineargauge-scale-ranges>
<range color="#2798df" from="-40" to="-20">
</range>
<range color="#ffc700" from="30" to="45">
</range>
<range color="#c20000" from="45" to="60">
</range>
</lineargauge-scale-ranges>
</scale>
</kendo-lineargauge>
@(Html.Kendo().LinearGauge()
.Name("gauge")
.Pointer(pointer => pointer.Value(10))
.Scale(scale => scale
.MajorUnit(20)
.MinorUnit(2)
.Min(-40)
.Max(60)
.Ranges(ranges =>
{
ranges.Add().From(-40).To(-20).Color("#2798df");
ranges.Add().From(30).To(45).Color("#ffc700");
ranges.Add().From(45).To(60).Color("#c20000");
}
1103
Telerik UI for ASP.NET Core
)
)
)
See Also
Basic Usage of the LinearGauge TagHelper for ASP.NET Core (Demo)
Server-Side API
1104
Telerik UI for ASP.NET Core
<kendo-radialgauge name="gauge"></kendo-radialgauge>
Basic Configuration
The RadialGauge TagHelper configuration options are passed as attributes of the tag.
<kendo-radialgauge name="gauge">
<radialgauge-pointers>
<pointer value="65"></pointer>
</radialgauge-pointers>
<scale minor-unit="5" start-angle="-30" end-angle="210" max="180">
</scale>
</kendo-radialgauge>
@(Html.Kendo().RadialGauge()
.Name("gauge")
.Pointer(pointer => pointer.Value(65))
.Scale(scale => scale
.MinorUnit(5)
.StartAngle(-30)
.EndAngle(210)
.Max(180)
)
)
See Also
Basic Usage of the RadialGauge TagHelper for ASP.NET Core (Demo)
Server-Side API
1105
Telerik UI for ASP.NET Core
The kendoDraggable and the kendoDropTarget combine together to enable the implementation
of the drag-and-drop scenarios.
<div id="droptarget" class="k-header"
kendo-droptarget="true"
on-kendo-dragenter="droptargetOnDragEnter"
on-kendo-dragleave="droptargetOnDragLeave"
on-kendo-drop="droptargetOnDrop" >Drag the small circle here.</div>
<div id="draggable"
kendo-draggable="true"
kendo-hint="draggableHint"
on-kendo-dragstart="draggableOnDragStart"
on-kendo-dragend="draggableOnDragEnd"></div>
See Also
Client-Side API
1106
Telerik UI for ASP.NET Core
The ProgressBar offers rich functionalities for displaying and tracking the progress of a task. It
supports multiple types, horizontal and vertical orientation, and also different directions.
<kendo-progressbar name="fastAndFurious" type="ProgressBarType.Percent" />
Basic Configuration
The ProgressBar TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().ProgressBar()
.Name("fastAndFurious")
.Type(ProgressBarType.Percent)
.Animation(a => a.Duration(600))
)
<kendo-progressbar name="fastAndFurious"
type="ProgressBarType.Percent" animation-duration="600" />
See Also
Basic Usage of the ProgressBar TagHelper for ASP.NET Core (Demo)
Server-Side API
1107
Telerik UI for ASP.NET Core
<kendo-sortable name="sortable-basic"></kendo-sortable>
Basic Configuration
The Sortable TagHelper configuration options are passed as attributes of the tag.
<kendo-sortable name="sortable-basic" hint="hint" placeholder="placeholder">
</kendo-sortable>
@(Html.Kendo().Sortable()
.For("#sortable-basic")
.HintHandler("hint")
.PlaceholderHandler("placeholder")
)
See Also
Basic Usage of the Sortable TagHelper for ASP.NET Core (Demo)
Server-Side API
1108
Telerik UI for ASP.NET Core
Badge Overview
The Badge is an absolutely positioned element that is used to decorate avatars, navigation menus,
or other components in the application when the visual notification is needed.
It also provides customizing its content through templates, setting different types and layouts.
<a class="k-button">
<kendo-badge name="badge" value="42" appearance="rectangle">
</kendo-badge>
</a>
Basic Configuration
The badge also provides the choice to be inline or overlay and set its type. To make the badge
overlay add the k-badge-overlay class to the parent parent element.
<a class="k-button k-badge-overlay">
<kendo-badge name="badge" value="42" type="warning" appearance="rectangle">
</kendo-badge>
</a>
Using templates
With the badge you can customize the content using templates.
<a class="k-button k-badge-overlay">
<kendo-badge name="badge" value="42" type="warning" appearance="rectangle"
template="#= +value > 10 ? '9+' : value #">
</kendo-badge>
</a>
1109
Telerik UI for ASP.NET Core
<a class="k-button k-badge-overlay">
<kendo-badge name="badge" value="42" type="warning" appearance="rectangle">
</kendo-badge>
</a>
<script>
var badge = $('#badge').data('kendoBadge');
</script>
See Also
Basic Usage of the Badge TagHelper for ASP.NET Core (Demo)
Server-Side API
1110
Telerik UI for ASP.NET Core
The Dialog is a modal popup that brings information to the user. It also provides actions through its
action buttons to prompt the user for input or to ask for a decision. The component can also contain
more complex UI elements that require the focus of the user. The Dialog is a subset of the Kendo UI
for jQuery Windowwhere the most prominent difference is the added functionality for actions and
predefined dialogs.
To enable more complex widget configuration scenarios, the Kendo UI R1 2018 release introduces a
change in the tags of the Dialog. Previously, it was possible to nest content directly in the
<kendo-dialog> tag while now, after the release, the content must be nested within a <content>
tag.
<kendo-dialog name="dialog1">
<content>Dialog contents</content>
</kendo-dialog>
Basic Configuration
The Dialog TagHelper configuration options are passed as attributes of the tag. Its content is placed
within a <content> tag.
@(Html.Kendo().Dialog()
.Name("dialog")
.Title("Software Update")
.Content("<p>A new version of <strong>Kendo UI</strong> is available. Would you
like to download and install it now?<p>")
.Modal(false)
.Actions(actions =>
{
actions.Add().Text("Skip this version");
actions.Add().Text("Remind me later");
actions.Add().Text("Install update").Primary(true);
})
.Events(ev => ev.Close("dialog_close"))
)
<kendo-dialog name="dialog" title="Software Update" modal="false"
on-close="dialog_close">
1111
Telerik UI for ASP.NET Core
<content>
<p>A new version of <strong>Kendo UI</strong> is available. Would you like to
download and install it now?<p>
</content>
<actions>
<action text="Skip this version">
</action>
<action text="Remind me later">
</action>
<action primary="true" text="Install update">
</action>
</actions>
</kendo-dialog>
<kendo-dialog name="dialog" title="Software Update" content="Some
content"></kendo-dialog>
See Also
Basic Usage of the Dialog TagHelper for ASP.NET Core (Demo)
Server-Side API
1112
Telerik UI for ASP.NET Core
The Notification provides a styled UI widget with arbitrary content which can provide information to
the user on various occasions.
<kendo-notification name="notification" auto-hide-after="0"></kendo-notification>
Basic Configuration
The Notification TagHelper configuration options are passed as attributes of the tag and through
nested tags.
@(Html.Kendo().Notification()
.Name("notification")
.Position(p => p.Pinned(true).Top(30).Right(30))
.Stacking(NotificationStackingSettings.Down)
.AutoHideAfter(0)
.Templates(t =>
{
t.Add().Type("info").ClientTemplateID("emailTemplate");
t.Add().Type("error").ClientTemplateID("errorTemplate");
t.Add().Type("upload-success").ClientTemplateID("successTemplate");
})
.Animation(a => a.Open(e => e.Duration(500)).Close(e => e.Duration(0)))
)
<kendo-notification name="notification"
stacking="NotificationStackingSettings.Down"
auto-hide-after="0">
<position pinned="true" top="30" right="30" />
<templates>
<notification-template type="info" template-id="emailTemplate" />
<notification-template type="error" template-id="errorTemplate" />
<notification-template type="upload-success" template-id="successTemplate" />
</templates>
<popup-animation>
<open duration="500" />
<close duration="0" />
</popup-animation>
1113
Telerik UI for ASP.NET Core
</kendo-notification>
See Also
Basic Usage of the Notification TagHelper for ASP.NET Core (Demo)
Server-Side API
1114
Telerik UI for ASP.NET Core
The following example demonstrates how to define the popup animation configuration of the Telerik
UI Tooltip tag helper.
<kendo-tooltip name="agglomerations" filter="span" position="top" width="120">
<popup-animation>
<open effects="fade:in" duration="300" />
</popup-animation>
</kendo-tooltip>
1115
Telerik UI for ASP.NET Core
The ResponsivePanel allows you to hide part of a page content on small screens.
<kendo-responsivepanel name="slidebar" breakpoint="1000" orientation="left">
<div id="profile" class="widget">
<h3>Profile</h3>
<div>
<div class="profile-photo"></div>
<h4>Lynda Schleifer</h4>
<p>Sales Associate</p>
</div>
</div>
<div id="teammates" class="widget">
<h3>Teammates</h3>
<div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/andrew.jpg")" alt="Andrew
Fuller">
<h4>Andrew Fuller</h4>
<p>Team Lead</p>
</div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/nancy.jpg")" alt="Nancy
Leverling">
<h4>Nancy Leverling</h4>
<p>Sales Associate</p>
</div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/robert.jpg")" alt="Robert King">
<h4>Robert King</h4>
<p>Business System Analyst</p>
</div>
</div>
</div>
</kendo-responsivepanel>
Basic Configuration
The configuration options of the ResponsivePanel TagHelper are passed as attributes of the tag.
@(Html.Kendo().ResponsivePanel()
1116
Telerik UI for ASP.NET Core
.Name("sidebar")
.Breakpoint(1000)
.Orientation("left")
.Content(@<text>
<div id="profile" class="widget">
<h3>Profile</h3>
<div>
<div class="profile-photo"></div>
<h4>Lynda Schleifer</h4>
<p>Sales Associate</p>
</div>
</div>
<div id="teammates" class="widget">
<h3>Teammates</h3>
<div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/andrew.jpg")" alt="Andrew
Fuller">
<h4>Andrew Fuller</h4>
<p>Team Lead</p>
</div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/nancy.jpg")" alt="Nancy
Leverling">
<h4>Nancy Leverling</h4>
<p>Sales Associate</p>
</div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/robert.jpg")" alt="Robert King">
<h4>Robert King</h4>
<p>Business System Analyst</p>
</div>
</div>
</div>
</text>)
)
<kendo-responsivepanel name="slidebar" breakpoint="1000" orientation="left">
<div id="profile" class="widget">
<h3>Profile</h3>
<div>
<div class="profile-photo"></div>
<h4>Lynda Schleifer</h4>
<p>Sales Associate</p>
</div>
</div>
<div id="teammates" class="widget">
<h3>Teammates</h3>
<div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/andrew.jpg")" alt="Andrew
Fuller">
<h4>Andrew Fuller</h4>
<p>Team Lead</p>
</div>
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/nancy.jpg")" alt="Nancy
Leverling">
<h4>Nancy Leverling</h4>
<p>Sales Associate</p>
</div>
1117
Telerik UI for ASP.NET Core
<div class="team-mate">
<img src="@Url.Content("~/content/web/panelbar/robert.jpg")" alt="Robert King">
<h4>Robert King</h4>
<p>Business System Analyst</p>
</div>
</div>
</div>
</kendo-responsivepanel>
See Also
Basic Usage of the ResponsivePanel TagHelper for ASP.NET Core (Demo)
1118
Telerik UI for ASP.NET Core
The Splitter provides a dynamic layout of resizable and collapsible panes. It converts the children of
an HTML element into an interactive layout by adding resize and collapse handles depending on its
configuration. The vertical and horizontal orientation of the Splitter can be combined to build
complex layouts.
To ensure the tag-naming consistency across the Telerik UI for ASP.NET Core suite, the Kendo UI for
jQuery R1 2018 release introduces a change in the tag names of the Splitter. Previously, the tag
name of the pane was <kendo-splitter-pane> while now, after the release, it is changed to
<pane>.
The following example demonstrates how to define the Splitter by using the Splitter TagHelper.
<kendo-splitter name="vertical" orientation="SplitterOrientation.Vertical">
<pane scrollable="false" collapsible="false">
<div id="top-pane">
<kendo-splitter name="horizontal" style="height: 100%; width:100%;"
orientation="SplitterOrientation.Horizontal">
<pane size="220px" collapsible="true">
<div id="left-pane">
<div class="pane-content">
<h3>Inner splitter / left pane</h3>
<p>Resizable and collapsible.</p>
</div>
</div>
</pane>
<pane>
<div id="center-pane">
<div class="pane-content">
<h3>Inner splitter / center pane</h3>
<p>Resizable only.</p>
</div>
</div>
</pane>
<pane size="220px" collapsible="true">
<div id="right-pane">
<div class="pane-content">
<h3>Inner splitter / right pane</h3>
<p>Resizable and collapsible.</p>
</div>
1119
Telerik UI for ASP.NET Core
</div>
</pane>
</kendo-splitter>
</div>
</pane>
<pane size="100px" collapsible="false">
<div id="middle-pane">
<div class="pane-content">
<h3>Outer splitter / middle pane</h3>
<p>Resizable only.</p>
</div>
</div>
</pane>
<pane size="100px" collapsible="false" resizable="false">
<div id="bottom-pane">
<div class="pane-content">
<h3>Outer splitter / bottom pane</h3>
<p>Non-resizable and non-collapsible.</p>
</div>
</div>
</pane>
</kendo-splitter>
Basic Configuration
The Splitter TagHelper supports all the configuration options that the HtmlHelper does. They are
passed as attributes of the tag.
@(Html.Kendo().Splitter()
.Name("splitter1")
.Orientation(SplitterOrientation.Vertical)
.Panes(p =>
{
p.Add()
.HtmlAttributes(new { id = "top-pane" })
.Collapsed(false)
.CollapsedSize("240px")
.Collapsible(true)
.LoadContentFrom("optionalUrl")
.MaxSize("240px")
.MinSize("240px")
.Resizable(true)
.Scrollable(true)
.Size("240px")
.Content(@<div class="pane-content">
Top Pane Content
</div>);
})
)
<kendo-splitter name="splitter1" orientation="SplitterOrientation.Vertical">
<pane collapsed="false" collapsed-size="240px" collapsible="true"
content-url="optionalUrl" max-size="240px" min-size="240px"
resizable="true" scrollable="true" size="240px">
<div id="top-pane">
<div class="pane-content">
Top Pane Content
</div>
1120
Telerik UI for ASP.NET Core
</div>
</pane>
</kendo-splitter>
See Also
Basic Usage of the Splitter TagHelper for ASP.NET Core (Demo)
Server-Side API
1121
Telerik UI for ASP.NET Core
The Tooltip displays a popup hint for a given html element. Its content can be defined either as static
text or loaded dynamically with AJAX.
<kendo-tooltip name="agglomerations" filter="span"></kendo-tooltip>
Basic Configuration
The Tooltip TagHelper configuration options are passed as attributes of the tag and through nested
tags.
@(Html.Kendo().Tooltip()
.For("#agglomerations")
.Filter("span")
.Position(TooltipPosition.Top)
.Width(120)
.Animation(a => a.Open(e => e.Fade(FadeDirection.In).Duration(300)))
)
<kendo-tooltip name="agglomerations" filter="span" position="top" width="120">
<popup-animation>
<open effects="fade:in" duration="300" />
</popup-animation>
</kendo-tooltip>
See Also
Basic Usage of the Tooltip TagHelper for ASP.NET Core (Demo)
Server-Side API
1122
Telerik UI for ASP.NET Core
The Window displays content in a modal or non-modal HTML window. By default, the user can move,
resize, and close a Window. Its content can also be defined either as static HTML or dynamically
loaded with AJAX.
To ensure the tag-naming consistency across the Telerik UI for ASP.NET Core suite, the Kendo UI for
jQuery R1 2018 release introduces a change in the tag names of the Window. Previously, it was
possible to nest content directly in the <kendo-window> tag while now, after the release, the
content must be nested within a <content> tag.
<kendo-window name="window1">
<content>Window contents</content>
</kendo-window>
Basic Configuration
The Window TagHelper configuration options are passed as attributes of the tag. The Window
contents is placed between the opening and closing tag.
@(Html.Kendo().Window()
.Name("window")
.Title("About Alvar Aalto")
.Content(@<text>
<div class="armchair">
<img src="@Url.Content("~/shared/web/window/armchair-402.png")"
alt="Artek Alvar Aalto - Armchair 402" />
Artek Alvar Aalto - Armchair 402
</div>
<p>
Alvar Aalto is one of the greatest names in modern architecture and design.
Glassblowers at the iittala factory still meticulously handcraft the legendary
vases that are variations on one theme, fluid organic shapes that let the end
user
ecide the use. Interpretations of the shape in new colors and materials add to
the
growing Alvar Aalto Collection that remains true to his original design.
</p>
</text>)
.Draggable()
1123
Telerik UI for ASP.NET Core
.Width(600)
.Events(ev => ev.Close("onClose"))
)
<kendo-window name="window" title="About Alvar Aalto" draggable="true"
width="400" on-close="onClose">
<content>
<div class="armchair">
<img src="@Url.Content("~/shared/web/window/armchair-402.png")"
alt="Artek Alvar Aalto - Armchair 402" />
Artek Alvar Aalto - Armchair 402
</div>
<p>
Alvar Aalto is one of the greatest names in modern architecture and design.
Glassblowers at the iittala factory still meticulously handcraft the legendary
vases that are variations on one theme, fluid organic shapes that let the end
user
ecide the use. Interpretations of the shape in new colors and materials add to
the
growing Alvar Aalto Collection that remains true to his original design.
</p>
</content>
</kendo-window>
See Also
Basic Usage of the Window TagHelper for ASP.NET Core (Demo)
Server-Side API
1124
Telerik UI for ASP.NET Core
ScrollView Overview
The Telerik UI ScrollView TagHelper for ASP.NET Core is a server-side wrapper for the Kendo UI
ScrollView widget.
The ScrollView displays a horizontal collection of content or image views with built-in navigation
between them. It can be scrolled through dragging, gestures, arrow click or page click or tap. Among
the key features of the ScrollView are data-source binding, customizable template, built-in pager,
adjustable bounce effects and scroll velocity.
From HTML
1. Use its items tag.
2. Define the content for each page.
<kendo-scrollview name="scrollView" content-height="100%"
template-id="scrollview-template" style="height:600px; width:890px; max-width: 100%;">
<items>
<scrollview-item>
<content><h1>One</h1></content>
</scrollview-item>
<scrollview-item>
<content><h1>Two</h1></content>
</scrollview-item>
<scrollview-item>
<content><h1>Three</h1></content>
</scrollview-item>
</items>
</kendo-scrollview>
<style>
h1 {
margin-top: 30%;
text-align:center;
}
</style>
Make sure that the template provides the pageSize of the data source. If serverPaging is enabled,
the ScrollView will request the data in advance so it becomes available before it is required, thus
1125
Telerik UI for ASP.NET Core
improving user experience. The ScrollView uses virtualization when it is bound to a data source and
it only has three pages at all times—the current, the previous, and the next.
<kendo-scrollview name="scrollView" content-height="100%"
template-id="scrollview-template" style="height:600px; width:890px; max-width: 100%;">
<datasource custom-type="odata" page-size="3" server-paging="true">
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Northwind.svc/Products"
/>
</transport>
</datasource>
</kendo-scrollview>
<script id="scrollview-template" type="text/x-kendo-template">
<div class="img-wrapper">
# for (var i = 0; i < data.length; i++) { #
<div>
<div style="width: 140px; height: 140px; background-image:
#=setBackground(data[i].ProductID)#; background-repeat:no-repeat; background-size:
cover;"></div>
<p>#= data[i].ProductName #</p>
</div>
# } #
</div>
</script>
See Also
Basic Usage of the ScrollView TagHelper for ASP.NET Core (Demo)
Server-Side API
1126
Telerik UI for ASP.NET Core
The Breadcrumb is an intuitive UI component that allows navigation within a folder structure or web
page. It provides an easy way to navigate backwards by one or multiple steps.
<kendo-breadcrumb name="breadcrumb"></kendo-breadcrumb>
Basic Configuration
The following example demonstrates the basic configuration for the Breadcrumb tag helper.
<kendo-breadcrumb name="breadcrumb">
<kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.RootItem" text="All Components"
href="https://demos.telerik.com/kendo-ui/" show-text="true" icon="home"
show-icon="true"></kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Breadcrumb"
href="/breadcrumb"></kendo-breadcrumb-item>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Tag Helper"
href="/tag-helper"></kendo-breadcrumb-item>
</kendo-breadcrumb-items>
</kendo-breadcrumb>
Events
You can subscribe to all Breadcrumb events.
<kendo-breadcrumb name="breadcrumb"
1127
Telerik UI for ASP.NET Core
on-change="onChange"
on-click="onClick">
<kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.RootItem" text="All Components"
href="https://demos.telerik.com/kendo-ui/" show-text="true" icon="home"
show-icon="true"></kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Breadcrumb"
href="/breadcrumb"></kendo-breadcrumb-item>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Tag Helper"
href="/tag-helper"></kendo-breadcrumb-item>
</kendo-breadcrumb-items>
</kendo-breadcrumb>
<script>
function onClick(e) {
kendoConsole.log("Clicked. :: target: " + e.item.text + ". Type :: " +
e.item.type);
}
function onChange(e) {
kendoConsole.log("Changed. New Value :: " + e.value);
}
</script>
See Also
Basic Usage of the Breadcrumb Tag Helper for ASP.NET Core (Demo)
1128
Telerik UI for ASP.NET Core
Items
The items configuration allows you to set specific attributes to the Breadcrumb items. You can set
the text and the icon of an element and determine whether they would be visible or not. The
configuration also allows you to add classes for the different elements which are rendered when
initializing the widget.
The following example demonstrates how the attributes of the Breadcrumb items can be set through
the items configuration.
<kendo-breadcrumb name="breadcrumb">
<kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.RootItem" text="All Components"
href="https://demos.telerik.com/kendo-ui/" show-text="true" icon="home"
show-icon="true"></kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Breadcrumb"
href="/breadcrumb"></kendo-breadcrumb-item>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Tag Helper"
href="/tag-helper"></kendo-breadcrumb-item>
</kendo-breadcrumb-items>
</kendo-breadcrumb>
1129
Telerik UI for ASP.NET Core
Icons
The Breadcrumb allows to configure the icons of the items and the delimiters.
Root Icon
The root icon is the first icon and is rendered as a home icon. It can be changed through the
items.icon configuration. It is also clickable and it will reset the value of the component.
Item Icon
The icons rendered for each element after the root icon. It is also clickable and can be configured
through the items.icon.
Delimiter Icon
The icons that separate the items of the Breadcrumb.
Example
The following example demonstrates how to configure different icons.
<kendo-breadcrumb name="breadcrumb"
delimiter-icon="line">
<kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.RootItem" text="All Components"
href="https://demos.telerik.com/kendo-ui/" show-text="true" icon="globe"
show-icon="true"></kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Breadcrumb"
href="/breadcrumb" icon="gear" show-icon="true"></kendo-breadcrumb-item>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Tag Helper"
href="/tag-helper" icon="cloud" show-icon="true"></kendo-breadcrumb-item>
</kendo-breadcrumb-items>
</kendo-breadcrumb>
1130
Telerik UI for ASP.NET Core
Editing
The path set through the Breadcrumb widget can be edited if the Editable configuration is enabled.
When clicking in an empty area of the component or on the current page, the Breadcrumb will enter
into editing mode. That will also happen when enter is pressed if the Breadcrumb is focused.
Editing mode shows an input field containing the current value of the widget. Users are allowed to
type a new path.
<kendo-breadcrumb name="breadcrumb"
editable="true">
<kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.RootItem" text="All Components"
href="https://demos.telerik.com/kendo-ui/" show-text="true" icon="home"
show-icon="true"></kendo-breadcrumb-items>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Breadcrumb"
href="/breadcrumb"></kendo-breadcrumb-item>
<kendo-breadcrumb-item type="BreadcrumbItemType.Item" text="Tag Helper"
href="/tag-helper"></kendo-breadcrumb-item>
</kendo-breadcrumb-items>
</kendo-breadcrumb>
1131
Telerik UI for ASP.NET Core
Navigation
The Navigationalconfiguration determines whether automatic navigation will be enabled. The
default value is false. When set to true, the url will be added to the href attribute of the Breadcrumb
items.
<kendo-breadcrumb name="breadcrumb"
bindToLocation="true"
navigational="true">
</kendo-breadcrumb>
The BindToLocation configuration sets the value ot the widget to the current url (the location
object). In addition, that url will be added to the href attribute of the Breadcrumb items through the
Navigational configuration.
When the configuration is disabled, you need to implement the navigation programmatically.
1132
Telerik UI for ASP.NET Core
The Button provides a styled clickable UI functionality with arbitrary content. Apart from consistent
Kendo UI for jQuery styling, the Button provides keyboard operability for elements, which natively do
not have it—for example, span.
<kendo-button name="button1">Click here!</kendo-button>
Basic Configuration
The Button TagHelper configuration options are passed as attributes of the tag.
@(Html.Kendo().Button()
.Name("imageButton")
.HtmlAttributes(new { type = "button" })
.ImageUrl(Url.Content("/shared/icons/sports/snowboarding.png"))
.Content("Image icon"))
<kendo-button name="button1" type="button"
image-url="/shared/icons/sports/snowboarding.png">Image icon</kendo-button>
See Also
Basic Usage of the Button TagHelper for ASP.NET Core (Demo)
Server-Side API
1133
Telerik UI for ASP.NET Core
<kendo-buttongroup name="buttonGroup">
<buttongroup-items>
<item text="Click here!"></item>
</buttongroup-items>
</kendo-buttongroup>
Basic Configuration
The Button tag helper configuration options are passed as attributes of the tag. The buttons are
specified in the buttongroup-items child tag collection.
<kendo-buttongroup name="player">
<buttongroup-items>
<item icon="play" text="Play" selected="true"></item>
<item icon="pause" text="Pause" enabled="false"></item>
<item icon="stop" text="Stop"></item>
</buttongroup-items>
</kendo-buttongroup>
@(Html.Kendo().ButtonGroup()
.Name("player")
.Items(t =>
{
t.Add().Text("Play").Icon("play").Selected(true);
t.Add().Text("Pause").Icon("pause").Enabled(false);
t.Add().Text("stop").Icon("stop");
})
)
See Also
Basic Usage of the ButtonGroup TagHelper for ASP.NET Core (Demo)
Server-Side API
1134
Telerik UI for ASP.NET Core
The Drawer is a dismissible panel used for navigation in responsive web applications or for changing
a content of a section in the page.
<kendo-drawer name="drawer" template-id="template" mode="overlay" position="left">
</kendo-drawer>
<script id="template" type="text/x-kendo-template">
<ul>
<li data-role='drawer-item'>First Item</li>
<li data-role='drawer-separator'></li>
<li data-role='drawer-item'>Second Item</li>
<li data-role='drawer-item' class='k-state-selected'>Third Item</li>
</ul>
Basic Configuration
The Drawer TagHelper configuration options are passed as strongly-typed attributes of the tag that
come with IntelliSense.
<kendo-drawer name="drawer" template-id="template" mode="push" position="left"
min-height="330" swipe-to-open="true" on-item-click="onItemClick">
<mini enabled="true"/>
<content>
<h1 class="my-content">Swipe or drag me to the right <span class="k-icon
k-i-arrow-chevron-right"></span></h1>
</content>
</kendo-drawer>
<script>
function onItemClick(e) {
// Logs the selected drawer item text.
console.log(e.item.text());
}
</script>
<script id="template" type="text/x-kendo-template">
1135
Telerik UI for ASP.NET Core
<ul>
<li data-role='drawer-item' class='k-state-selected'><span class='k-icon
k-i-inbox'></span><span class='k-item-text'>Inbox</span></li>
<li data-role='drawer-separator'></li>
<li data-role='drawer-item'><span class='k-icon k-i-eye'></span><span
class='k-item-text'>See more</span></li>
</ul>
</script>
<kendo-drawer name="drawer" template-id="template" mode="push" position="left"
min-height="330" swipe-to-open="true" on-item-click="onItemClick">
<mini enabled="true"/>
<content>
<h1 class="my-content">Swipe or drag me to the right <span class="k-icon
k-i-arrow-chevron-right"></span></h1>
</content>
</kendo-drawer>
<script type="text/javascript">
$(function () {
// The name of the Drawer is used to get its client-side instance.
var drawer = $("#drawer").data("kendoDrawer");
console.log(drawer);
});
</script>
See Also
Basic Usage of the Drawer Helper for ASP.NET Core (Demo)
Server-Side API
1136
Telerik UI for ASP.NET Core
Display Modes
The Drawer provides a set of modes for handling the way it is displayed.
Overlay Mode
The overlay mode is not associated with any content. The Drawer appears on top of the page
contents from the side which is configured in the Position()method. To show the Drawer, either
swipe or drag with mouse or call the show()method of the Kendo UI for jQuery widget. The Drawer
closes on click or tap of any of the options or on the overlay.
Push Mode
The push mode is associated with specific page content and the element from which the widget is
initialized has to wrap that content. When the drawer opens it will push that content to the side. It is
designed for wider screens (desktop or tablet). To show the Drawer, either swipe or drag with
mouse, or call the show()method of the Kendo UI for jQuery widget. The Drawer closes on click or
tap of any of the options or on the associated content.
The height of the widget is determined by the higher content of the template of the widget or of the
wrapped content with which it is associated. You can use the MinHeight()method to prevent the
content from changing its height as the user toggles the drawer options.
Mini Mode
You can use the Mini() option both with the overlay and push modes by adding a the Mini()
method. If set to true, a portion of the Drawer that is always visible occupies the default width of
50px and the main template. If the Mini() configurator is used, the Width() and
Template()/TemplateId() can also be changed.
<mini width="100" template-id="mini-template"/>
See Also
Server-Side API
1137
Telerik UI for ASP.NET Core
Interaction Modes
The Drawer has provides a set of modes and with which the user can interact and positions in which
it can be rendered.
(Default) overlay
push
The Drawer supports the following positions which determine the side on which the it will be
rendered:
(Default) left
right
The Drawer provides gesture support. It also features the mini mode which makes the it always
partly visible and allows the user to reveal its full content either with a gesture or by calling the
show() method of the widget.
See Also
Server-Side API
1138
Telerik UI for ASP.NET Core
Templates
To distinguish the items within the template when the user interacts with the Drawer, add the
data-role="drawer-item" attribute to each item HTML template.
If you wish to add a separator between the drawer items use the
data-role="drawer-separator" attribute.
You can add icons with a span with the k-icon class combined with the desired Kendo UI for jQuery
web font iconsclass. To ensure that the icons and text have a sufficient padding, wrap the item
template text in a span with class k-item-text.
<kendo-drawer
name="drawer"
template="<ul><li data-role='drawer-item'><span class='k-icon
k-i-eye'></span><span class='k-item-text'>See More</span></li></ul>"
mode="push"
position="left"
min-height="330">
<content>
<h1 class="my-content">Swipe or drag me to the right <span class="k-icon
k-i-arrow-chevron-right"></span></h1>
</content>
</kendo-drawer>
See Also
Server-Side API
1139
Telerik UI for ASP.NET Core
The Menu displays hierarchical data as a multi-level menu. It provides rich styling for unordered lists
of items, and can be used for both navigation and execution of JavaScript commands.
<kendo-menu name="menu">
</kendo-menu>
Basic Configuration
To pass the Menu items collection, either:
<kendo-menu name="menu">
<items>
<menu-item text="Home"></menu-item>
<menu-item text="Second Page"></menu-item>
</items>
</kendo-menu>
<kendo-menu name="menu">
<li>Home</li>
<li>Second Page</li>
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items => {
items.Add().Text("Home");
items.Add().Text("Second Page");
})
)
To further configure the Menu TagHelper, use its other options— <open-on-click>,
1140
Telerik UI for ASP.NET Core
<kendo-menu name="menu">
<items>
<menu-item text="Home"></menu-item>
<menu-item text="Second Page"></menu-item>
</items>
<open-on-click enabled="true" root-menu-items="true" sub-menu-items="false" />
<popup-animation>
<open duration="500" />
<close duration="300" />
</popup-animation>
<scrollable enabled="false" />
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items => {
items.Add().Text("Home");
items.Add().Text("Second Page");
})
.OpenOnClick(open => open.RootMenuItems(true).SubMenuItems(false))
.Animation(animation =>
animation.Open(open => open.Duration(500))
.Close(close => close.Duration(300))
)
.Scrollable(true)
)
See Also
Basic Usage of the Menu TagHelper for ASP.NET Core (Demo)
Server-Side API
1141
Telerik UI for ASP.NET Core
Items
The Menu items are represented by the menu-item tag helper and render <li> tags inside the Menu
root element.
The <menu-item> utilizes different inner tags and attributes to let you configure the Menu items.
The menu-item tag helper inherits the AnchorTagHelperclass which enables you to utilize the
native navigation attributes that come with it.
<kendo-menu name="menu">
<items>
<menu-item text="Home" asp-action="Index" asp-controller="Home"></menu-item>
<menu-item text="Second Page" asp-action="SecondIndex"
asp-controller="Home"></menu-item>
</items>
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items => {
items.Add().Text("Home").Action("Index", "Home");
items.Add().Text("Second Page").Action("SecondIndex", "Home");
})
)
You can also directly set up a URL that navigates to the desired location.
<kendo-menu name="menu">
<items>
<menu-item text="Home" url="/home/index"></menu-item>
</items>
</kendo-menu>
To create popup menus, configure the items by using the <sub-items> tag of the menu-item.
<kendo-menu name="menu">
<items>
<menu-item text="Navigate">
<sub-items>
<menu-item text="Home"></menu-item>
<menu-item text="About"></menu-item>
<menu-item text="Contact"></menu-item>
</sub-items>
</menu-item>
</items>
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
1142
Telerik UI for ASP.NET Core
{
items.Add().Text("Navigate").Items(subitems => {
subitems.Add().Text("Home");
subitems.Add().Text("About");
subitems.Add().Text("Contact");
});
})
)
Identical to the Kendo UI Menu helper method, you can customize the Menu items by adding images,
icons, custom CSS classes, and DOM attributes.
<kendo-menu name="menu">
<items>
<menu-item text="Home" my-attr="value" link-html-attributes='new {
link_attr="value" }'></menu-item>
<menu-item text="About" image-url="path/to/image.png"
image-html-attributes='new { img_attr="value" }'></menu-item>
<menu-item text="Contact" icon-class="k-sprite my-sprite-class"></menu-item>
<menu-item text="Login" icon="login" ></menu-item>
</items>
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
{
items.Add().Text("Home")
.LinkHtmlAttributes(new { link_attr = "value" })
.HtmlAttributes(new { my_attr="value" });
items.Add().Text("About")
.ImageUrl("path/to/image.png")
.ImageHtmlAttributes(new { img_attr = "value" });
items.Add().Text("Contact")
.SpriteCssClasses("my-sprite-class");
// The Kendo UI Menu helper method does not support icons yet.
})
)
You can also define the popup of each Menu item with HTML syntax by using the <content> tag
helper.
<kendo-menu name="menu">
<items>
<menu-item text="Locations">
<content class="locations-menu-content" content-attr="value">
<div id="template" style="padding: 10px;">
<h2>Around the Globe</h2>
<ol>
<li>United States</li>
<li>Europe</li>
<li>Canada</li>
<li>Australia</li>
</ol>
1143
Telerik UI for ASP.NET Core
<img src='@Url.Content("~/shared/web/menu/map.png")' alt="Stores Around the
Globe" />
<button class="k-button">See full list</button>
</div>
</content>
</menu-item>
</items>
</kendo-menu>
@(Html.Kendo().Menu()
.Name("menu")
.Items(items =>
{
items.Add().Text("Locations")
.ContentHtmlAttributes(new { @class= "locations-menu-content", content_attr =
"value" })
.Content(@<text>
<div id="template" style="padding: 10px;">
<h2>Around the Globe</h2>
<ol>
<li>United States</li>
<li>Europe</li>
<li>Canada</li>
<li>Australia</li>
</ol>
<img src='@Url.Content("~/shared/web/menu/map.png")' alt="Stores Around the
Globe" />
<button class="k-button">See full list</button>
</div>
</text>);
})
)
See Also
Server-Side API
1144
Telerik UI for ASP.NET Core
<kendo-panelbar name="panelbar1">
</kendo-panelbar>
Basic Configuration
The PanelBar TagHelper configuration options are passed as attributes of the tag. You can configure
items by using a nested <items> tag and bind the widget by using either the bind-to option, or the
<hierarchical-datasource> tag helper.
<kendo-panelbar name="employees" datatextfield="FullName">
<hierarchical-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Employees"
datatype="jsonp" />
</transport>
<schema type="json">
<hierarchical-model id="EmployeeId" has-children="HasEmployees">
</hierarchical-model>
</schema>
</hierarchical-datasource>
</kendo-panelbar>
<kendo-panelbar name="project">
<items>
<panelbar-item text="Storage" expanded="true">
<items>
<panelbar-item text="Wall Shelving"></panelbar-item>
<panelbar-item text="Floor Shelving"></panelbar-item>
<panelbar-item text="Kids Storag"></panelbar-item>
</items>
</panelbar-item>
<panelbar-item text="Lights">
<items>
<panelbar-item text="Ceiling"></panelbar-item>
<panelbar-item text="Table"></panelbar-item>
<panelbar-item text="Floor"></panelbar-item>
</items>
1145
Telerik UI for ASP.NET Core
</panelbar-item>
</items>
</kendo-panelbar>
@(Html.Kendo().PanelBar()
.Name("panelbar")
.ExpandMode(PanelBarExpandMode.Single)
.Items(panelbar =>
{
panelbar.Add().Text("Projects")
.Items(projects =>
{
projects.Add().Text("New Business Plan");
projects.Add().Text("Sales Forecasts")
.Items(forecasts =>
{
forecasts.Add().Text("Q1 Forecast");
forecasts.Add().Text("Q2 Forecast");
forecasts.Add().Text("Q3 Forecast");
forecasts.Add().Text("Q4 Forecast");
});
projects.Add().Text("Sales Reports");
});
panelbar.Add().Text("Programs")
.Items(programs =>
{
programs.Add().Text("Monday");
programs.Add().Text("Tuesday");
programs.Add().Text("Wednesday");
programs.Add().Text("Thursday");
programs.Add().Text("Friday");
});
panelbar.Add().Text("Communication").Enabled(false);
})
)
See Also
Basic Usage of the PanelBar TagHelper for ASP.NET Core (Demo)
Server-Side API
1146
Telerik UI for ASP.NET Core
The TabStrip displays a collection of tabs with associated content. It is composed of an unordered
list of items which represent tabs, and a collection of div elements, which contain the content for
each tab.
<kendo-tabstrip name="tabstrip">
</kendo-tabstrip>
Basic Configuration
To pass the TabStrip items collection, either:
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Tab 1">
<content><p>Content 1</p></content>
</tabstrip-item>
<tabstrip-item text="Tab 2">
<content><p>Content 2</p></content>
</tabstrip-item>
</items>
</kendo-tabstrip>
<kendo-tabstrip name="tabstrip">
<li>Tab 1</li>
<li>Tab 2</li>
<div>
<p>Content 1</p>
</div>
<div>
<p>Content 2</p>
</div>
</kendo-tabstrip>
1147
Telerik UI for ASP.NET Core
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items => {
items.Add().Text("Tab 1").Content(@<text>
<p>Content 1</p>
</text>);
items.Add().Text("Tab 2").Content(@<text>
<p>Content 2</p>
</text>);
})
)
To further configure the TabStrip TagHelper, use its other options— <popup-animation>, and
<scrollable>.
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Tab 1">
<content><p>Content 1</p></content>
</tabstrip-item>
<tabstrip-item text="Tab 2">
<content><p>Content 2</p></content>
</tabstrip-item>
</items>
<popup-animation>
<open duration="500" />
<close duration="300" />
</popup-animation>
<scrollable enabled="false" />
</kendo-tabstrip>
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items => {
items.Add().Text("Tab 1").Content(@<text>
<p>Content 1</p>
</text>);
items.Add().Text("Tab 2").Content(@<text>
<p>Content 2</p>
</text>);
})
.Animation(animation =>
animation.Open(open => open.Duration(500))
.Close(close => close.Duration(300))
)
.Scrollable(true)
)
See Also
Basic Usage of the TabStrip TagHelper for ASP.NET Core (Demo)
1148
Telerik UI for ASP.NET Core
Server-Side API
1149
Telerik UI for ASP.NET Core
Items
The TabStrip items are represented by the tabstrip-item tag helper and render <li> tags inside
the TabStrip root element.
The <tabstrip-item> utilizes various inner tags and attributes to let you configure the TabStrip
items. The tabstrip-item tag helper inherits the AnchorTagHelperclass which enables you to
utilize the native attributes that come with it and thus configure a URL to action or Razor page to
load the content from.
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Tab 1" asp-action="Content"
asp-controller="Home"></tabstrip-item>
<tabstrip-item text="Tab 2" asp-action="ContentTwo"
asp-controller="Home"></tabstrip-item>
</items>
</kendo-tabstrip>
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items => {
items.Add().Text("Tab 1").LoadContentFrom("Content", "Home");
items.Add().Text("Tab 2").LoadContentFrom("ContentTwo", "Home");
})
)
You can also directly set up a URL that loads content from the desired location.
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Tab" content-url="/home/content"></tabstrip-item>
</items>
</kendo-tabstrip>
Identical to the Kendo UI TabStrip helper method, you can customize the TabStrip items by adding
images, icons, custom CSS classes, and DOM attributes.
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Tab 1" my-attr="value" link-html-attributes='new {
link_attr="value" }'></tabstrip-item>
<tabstrip-item text="Tab 2" image-url="path/to/image.png"
image-html-attributes='new { img_attr="value" }'></tabstrip-item>
<tabstrip-item text="Tab 3" icon-class="k-sprite
my-sprite-class"></tabstrip-item>
<tabstrip-item text="Tab 4" icon="login" ></tabstrip-item>
</items>
</kendo-tabstrip>
1150
Telerik UI for ASP.NET Core
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items =>
{
items.Add().Text("Tab 1")
.LinkHtmlAttributes(new { link_attr = "value" })
.HtmlAttributes(new { my_attr="value" });
items.Add().Text("Tab 2")
.ImageUrl("path/to/image.png")
.ImageHtmlAttributes(new { img_attr = "value" });
items.Add().Text("Tab 3")
.SpriteCssClasses("my-sprite-class");
// The Kendo UI TabStrip helper method does not support icons yet.
})
)
You can also define the content of each item by using the <content> tag helper.
<kendo-tabstrip name="tabstrip">
<items>
<tabstrip-item text="Paris">
<content class="my-class" content-attr="value">
<div class="weather">
<h2>17<span>ºC</span></h2>
<p>Rainy weather in Paris.</p>
</div>
<span class="rainy"> </span>
</content>
</tabstrip-item>
</items>
</kendo-tabstrip>
@(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(items =>
{
items.Add().Text("Locations")
.ContentHtmlAttributes(new { @class= "my-class", content_attr = "value" })
.Content(@<text>
<div class="weather">
<h2>17<span>ºC</span></h2>
<p>Rainy weather in Paris.</p>
</div>
<span class="rainy"> </span>
</text>);
})
)
See Also
Server-Side API
1151
Telerik UI for ASP.NET Core
Timeline Overview
The Telerik UI Timeline TagHelper for ASP.NET Core is a server-side wrapper for the Kendo UI
Timeline widget.
The Timeline widget displays a collection of events and their data in a chronological succession for
each year.
You can scroll through the events and collapse/expand them. The events order can be vertical or
horizontal, and you can customize their templates, as well as respond to events and use API control
the widget behavior. You can also control the format of the rendered date for the event. If you
provide a list of actions, they will be rendered as links after the description and images.
<kendo-timeline name="timeline" orientation="horizontal" datadatefield="EventDate"
datatitlefield="Title" datasubtitlefield="Subtitle" datadescriptionfield="Description"
dataactionsfield="Actions" dataimagesfield="Images">
<datasource>
<transport>
<read url="/Timeline/GetTimelineData" />
</transport>
<schema>
<model>
<fields>
<field name="EventDate" type="date"></field>
</fields>
</model>
</schema>
</datasource>
</kendo-timeline>
public partial class Timeline : BaseController
{
public JsonResult GetTimelineData()
{
List<TimelineEventModel> events = new List<TimelineEventModel>();
events.Add(new TimelineEventModel() {
Title = "Barcelona \u0026 Tenerife",
Subtitle = "May 15, 2015",
Description = "First event description.",
EventDate = new System.DateTime(2015, 4, 15),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Barcelona-and-Tenerife/
Arc-de-Triomf,-Barcelona,-Spain_Liliya-Karakoleva.JPG?width=500&height=500" }
1152
Telerik UI for ASP.NET Core
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Barcelona",
url="https://en.wikipedia.org/wiki/Barcelona" }
}
});
events.Add(new TimelineEventModel()
{
Title = "United States East Coast Tour",
Subtitle = "Feb 27, 2018",
Description = "The second event description.",
EventDate = new System.DateTime(2018, 1, 27),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/United-States/Boston-Ol
d-South-Church_Ivo-Igov.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about New York City",
url="https://en.wikipedia.org/wiki/New_York_City" }
}
});
events.Add(new TimelineEventModel()
{
Title = "Malta, a Country of Кnights",
Subtitle = "My second trip this year",
Description = "Third event description.",
EventDate = new System.DateTime(2015, 5, 25),
Images = new List<TimelineEventImageModel>() {
new TimelineEventImageModel() { src =
"https://demos.telerik.com/aspnet-mvc/tripxpert/Images/Gallery/Malta/Bibliotheca-Natio
nal-Library_Marie-Lan-Nguyen.JPG?width=500&height=500" }
},
Actions = new List<TimelineEventActionModel>() {
new TimelineEventActionModel() { text = "More info about Malta",
url="https://en.wikipedia.org/wiki/Malta" }
}
});
return Json(events);
}
}
public class TimelineEventModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public DateTime EventDate { get; set; }
public List<TimelineEventImageModel> Images { get; set; }
public List<TimelineEventActionModel> Actions { get; set; }
}
public class TimelineEventImageModel
{
public string src { get; set; } // this field name must be "src"
}
1153
Telerik UI for ASP.NET Core
public class TimelineEventActionModel
{
public string text { get; set; } // this field name must be "text"
public string url { get; set; } // this field name must be "url"
}
See Also
Basic Usage of the Timeline TagHelper (Demo)
1154
Telerik UI for ASP.NET Core
The ToolBar is designed to hold different types of controls such as buttons, button groups, toggle
buttons, split buttons, and other customized elements.
<kendo-toolbar name="ToolBar">
<toolbar-items>
<item type="CommandType.Button" text="Button 1" />
<item type="CommandType.Separator" />
<item type="CommandType.Button" text="Button 2" />
</toolbar-items>
</kendo-toolbar>
Basic Configuration
The ToolBar TagHelper configuration options are passed as attributes of the tag.
The following example demonstrates the basic configuration of the ToolBar TagHelper.
<kendo-toolbar name="ToolBar">
<toolbar-items>
<item type="CommandType.Button" text="Button" />
<item type="CommandType.Button" text="Toggle Button" togglable="true" />
<item type="CommandType.SplitButton" text="Insert">
<menu-buttons>
<toolbar-button text="Insert above" icon="insert-up" />
<toolbar-button text="Insert between" icon="insert-middle" />
<toolbar-button text="Insert below" icon="insert-down" />
</menu-buttons>
</item>
<item type="CommandType.Separator" />
<item template="<label for='dropdown'>Format:</label>" />
<item template="<input id='dropdown' style='width: 150px;' />"
overflow="ShowInOverflowPopup.Never" />
<item type="CommandType.Separator" />
<item type="CommandType.ButtonGroup">
<buttons>
<toolbar-button text="Left" togglable="true" group="text-align"
icon="align-left" />
<toolbar-button text="Center" togglable="true" group="text-align"
icon="align-center" />
<toolbar-button text="Right" togglable="true" group="text-align"
1155
Telerik UI for ASP.NET Core
icon="align-right" />
</buttons>
</item>
<item type="CommandType.Button" text="Action"
overflow="ShowInOverflowPopup.Always"/>
<item type="CommandType.Button" text="Another Action"
overflow="ShowInOverflowPopup.Always"/>
<item type="CommandType.Button" text="Something else here"
overflow="ShowInOverflowPopup.Always"/>
</toolbar-items>
</kendo-toolbar>
<script>
$(document).ready(function () {
// Initialize a DropDownList in a template of the ToolBar item.
$("#dropdown").kendoDropDownList({
optionLabel: "Paragraph",
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Heading 1", value: 1 },
{ text: "Heading 2", value: 2 },
{ text: "Heading 3", value: 3 },
{ text: "Title", value: 4 },
{ text: "Subtitle", value: 5 },
]
});
// The Name() of the ToolBar is used to get its client-side instance.
var toolbar = $("#ToolBar").data("kendoToolBar");
});
</script>
@(Html.Kendo().ToolBar()
.Name("ToolBar")
.Items(items => {
items.Add().Type(CommandType.Button).Text("Button");
items.Add().Type(CommandType.Button).Text("Toggle Button").Togglable(true);
items.Add().Type(CommandType.SplitButton).Text("Insert").MenuButtons(menuButtons =>
{
menuButtons.Add().Text("Insert above").Icon("insert-up");
menuButtons.Add().Text("Insert between").Icon("insert-middle");
menuButtons.Add().Text("Insert below").Icon("insert-down");
});
items.Add().Type(CommandType.Separator);
items.Add().Template("<label for='dropdown'>Format:</label>");
items.Add().Template("<input id='dropdown' style='width: 150px;' />").Overflow
(ShowInOverflowPopup.Never);
items.Add().Type(CommandType.Separator);
items.Add().Type(CommandType.ButtonGroup).Buttons(buttons =>
{
buttons.Add().Text("Left").Togglable(true).Group("text-align").Icon("align-left");
buttons.Add().Text("Center").Togglable(true).Group("text-align").Icon("align-center");
buttons.Add().Text("Right").Togglable(true).Group("text-align").Icon("align-right");
});
items.Add().Type(CommandType.ButtonGroup).Buttons(buttons =>
{
1156
Telerik UI for ASP.NET Core
buttons.Add().Text("Bold").Togglable(true).Icon("bold");
buttons.Add().Text("Italic").Togglable(true).Icon("italic");
buttons.Add().Text("Underline").Togglable(true).Icon("underline");
});
items.Add().Type(CommandType.Button).Text("Action").Overflow(ShowInOverflowPopup.Alway
s);
items.Add().Type(CommandType.Button).Text("Another Action").Overflow
(ShowInOverflowPopup.Always);
items.Add().Type(CommandType.Button).Text("Something else here").Overflow
(ShowInOverflowPopup.Always);
})
)
<script>
$(document).ready(function () {
// Initialize a DropDownList in a template of the ToolBar item.
$("#dropdown").kendoDropDownList({
optionLabel: "Paragraph",
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Heading 1", value: 1 },
{ text: "Heading 2", value: 2 },
{ text: "Heading 3", value: 3 },
{ text: "Title", value: 4 },
{ text: "Subtitle", value: 5 },
]
});
// The Name() of the ToolBar is used to get its client-side instance.
var toolbar = $("#ToolBar").data("kendoToolBar");
});
</script>
See Also
Basic Usage of the ToolBar Tag lHelper for ASP.NET Core (Demo)
Server-Side API
1157
Telerik UI for ASP.NET Core
<kendo-treeview name="treeView1">
</kendo-treeview>
Basic Configuration
The TreeView TagHelper configuration options are passed as attributes of the tag. You can
configure the items by using a nested <items> tag and also bind the widget to
<hierarchical-datasource>.
<kendo-treeview name="treeview2" datatextfield="FullName">
<hierarchical-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/Employees"
datatype="jsonp" />
</transport>
<schema type="json">
<hierarchical-model id="EmployeeId" has-children="HasEmployees">
</hierarchical-model>
</schema>
</hierarchical-datasource>
</kendo-treeview>
<kendo-treeview name="treeView1">
<items>
<treeview-item text="Web Site" expanded="true" sprite-css-class="folder">
<items>
<treeview-item text="images" expanded="true" sprite-css-class="folder">
<items>
<treeview-item text="logo.png" sprite-css-class="image"></treeview-item>
</items>
</treeview-item>
<treeview-item text="resources" expanded="true" sprite-css-class="folder">
<items>
<treeview-item text="pdf" expanded="true" sprite-css-class="folder">
<items>
<treeview-item text="prices.pdf" sprite-css-class="pdf"></treeview-item>
</items>
1158
Telerik UI for ASP.NET Core
</treeview-item>
</items>
</treeview-item>
<treeview-item text="index.html" sprite-css-class="html"></treeview-item>
</items>
</treeview-item>
</items>
</kendo-treeview>
@(Html.Kendo().TreeView()
.Name("treeview")
.Items(treeview =>
{
treeview.Add().Text("My Web Site")
.SpriteCssClasses("folder")
.Expanded(true)
.Items(root =>
{
root.Add().Text("images")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(images =>
{
images.Add().Text("logo.png")
.SpriteCssClasses("image");
});
root.Add().Text("resources")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(resources =>
{
resources.Add().Text("pdf")
.Expanded(true)
.SpriteCssClasses("folder")
.Items(pdf =>
{
pdf.Add().Text("prices.pdf")
.SpriteCssClasses("pdf");
});
resources.Add().Text("zip")
.SpriteCssClasses("folder");
});
root.Add().Text("about.html")
.SpriteCssClasses("html");
root.Add().Text("index.html")
.SpriteCssClasses("html");
});
})
)
See Also
Basic Usage of the TreeView TagHelper for ASP.NET Core (Demo)
Server-Side API
1159
Telerik UI for ASP.NET Core
The PDFViewer displays PDF files in the browser and consists of a toolbar and a scrollable container
that wraps the page elements. Default tools collection includes pager, open and download tool. For
processing files, it supports the PDF.JS Processing and Telerik DPL Processing libraries. Among the
key features the PDFViewer provides are the selection of a PDF processing library, a built-in paging
mechanism, virtualization capabilities, a built-in default toolbar collection, and responsive
capabilities and page scaling.
The following example demonstrates a PDFViewer TagHelper which uses the PDF.JS library.
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script>
<script>
window.pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.worker.js';
</script>
<kendo-pdfviewer name="pdfviewer">
<pdfjs-processing file="@(Url.Content("~/shared/web/pdfViewer/sample.pdf"))" />
<toolbar enabled="true">
<pdfviewer-toolbar-items>
<pdfviewer-toolbar-item command="PageChangeCommand" type="pager"
name="pager"></pdfviewer-toolbar-item>
<pdfviewer-toolbar-item type="spacer" name="spacer"></pdfviewer-toolbar-item>
<pdfviewer-toolbar-item command="OpenCommand" type="button" name="open"
icon="folder-open"></pdfviewer-toolbar-item>
<pdfviewer-toolbar-item command="DownloadCommand" type="button" name="download"
icon="download"></pdfviewer-toolbar-item>
</pdfviewer-toolbar-items>
</toolbar>
</kendo-pdfviewer>
Running an Adblock extension in Chrome might treat the new browser tab for the print dialog as a
potential ad and block it.
See Also
Basic Usage of the PDFViewer TagHelper for ASP.NET Core (Demo)
Server-Side API
1160
Telerik UI for ASP.NET Core
The Calendar renders a graphical calendar that provides navigation and selection functionalities. To
define the first rendered view, use the start option. To control the navigation depth, set the depth
option. The Calendar provides the month, year, decade, and century predefined views.
<kendo-calendar name="calendar" >
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar"))
See Also
Basic Usage of the Calendar TagHelper for ASP.NET Core (Demo)
Server-Side API
1161
Telerik UI for ASP.NET Core
Date Ranges
The following example demonstrates how to create a Calendar with a selected date and a defined
minimum and maximum dates.
As a result, the Calendar does not navigate to a date that is earlier than the specified minimum date
and also restricts the navigation to the maximum date you specified.
<kendo-calendar name="calendar"
value="DateTime.Now"
min="new DateTime(1950,1,2)"
max="new DateTime(2049,12,31)">
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.Value(DateTime.Now)
.Min(new DateTime(1950, 1, 2))
.Max(new DateTime(2049, 12, 31)))
See Also
Server-Side API
1162
Telerik UI for ASP.NET Core
Day Template
The Calendar enables you to customize the rendered day for the month view.
The following example demonstrates how to create a Calendar by using a custom template.
<kendo-calendar name="calendar">
<month content="<div class='custom'><#=data.value#></div>"/>
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.MonthTemplate(x=> x.Content("<div class='custom'><#=data.value#></div>")))
The template wraps the value in a <div> HTML element. The structure of the data object that is
passed to the template function:
data = {
date: date, // A date object corresponding to the current cell.
title: kendo.toString(date, "D"),
value: date.getDate(),
dateString: "2011/0/1" // Formatted date using yyyy/MM/dd format and month is
zero-based.
};
See Also
Server-Side API
1163
Telerik UI for ASP.NET Core
Week Numbers
You can configure the Calendar to display the week number and also use the week number template
to customize the cells in the Week column.
<kendo-calendar week-number="true" name="calendar">
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.WeekNumber(true)))
You can use these properties in the template to make additional calculations.
<kendo-calendar week-number="true" name="calendar">
<month week-number="<i>#= data.weekNumber #</i>" />
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.WeekNumber()
.MonthTemplate(x=> x.WeekNumber("<i>#= data.weekNumber #</i>"))
)
See Also
Server-Side API
1164
Telerik UI for ASP.NET Core
Selection
The Calendar enables the user to make a single, multiple, range-date, and week selections.
To perform the multiple date selection, the user can also use the keyboard:
Ctrl + mouse click on specific date marks the date as selected and other previously
selected dates remain selected as well.
The selection of a date from a specific view without utilizing the Ctrl key, deselects all
previously selected dates—including the previously selected dates from other views or
months, and selects the date of the clicked cell.
The selection of a date that is already selected while holding the Ctrl key removes the date
from the selection.
<kendo-calendar selectable="multiple" name="calendar">
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.Selectable("multiple")
)
To select all dates between the most recently selected one (with Space or mouse click) and
the clicked cell, press Shift and click with the mouse.
If no previous selection was made, Shift and a mouse click select all dates from the
beginning to the clicked cell.
1165
Telerik UI for ASP.NET Core
Week Selection
When the user clicks on a specific week number, the Calendar selects the entire week. The week
selection functionality is a special case of range selection which starts from the first day of the week
and selects all dates to the end of the week.
See Also
Server-Side API
1166
Telerik UI for ASP.NET Core
Disabled Dates
The Calendar allows you to disable certain days which are not intended to be selected by the end
user such as weekends, national holidays, and others.
Setting an Array
When you set an array, list the days that need to be disabled by using the first letters from their
names in English.
<kendo-calendar disable-dates="new DateTime[] { DateTime.Now.AddDays(2),
DateTime.Now.AddDays(2) }" value="DateTime.Now" name="calendar">
</kendo-calendar>
@(Html.Kendo().Calendar()
.Name("calendar")
.Value(DateTime.Now)
.DisableDates(new[] {DayOfWeek.Monday })
)
Adding a Function
When you add a function, determine its return value as true for the date that is disabled.
<div class="demo-section k-content" style="text-align: center;">
<kendo-calendar disable-dates-handler="disabledDatesHandler"
value="DateTime.Now" name="calendar">
</kendo-calendar>
</div>
<script>
function disabledDatesHandler(date) {
var disabled = [13, 14, 20, 21];
if (date && disabled.indexOf(date.getDate()) > -1) {
return true;
} else {
return false;
}
}
</script>
See Also
Server-Side API
1167
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the Calendar works by listening to the key-down events on the wrapper
element of the widget.
The logic assumes that everything the user does is in accordance with the currently focused date
cell and not the focused element of the browser.
Depending on selection type (single or multiple), the Calendar behaves differently in terms of
selecting and navigating with the keyboard. When the user applies the multiple date selection, the
Calendar demonstrates the following keyboard navigation behavior:
The focusing or selection of a date from another month does not navigate to the
corresponding month. The user is able to continue the selection of dates from the current
view.
The pressing of Space or Enter on a specific date makes a single selection by deselecting
all other selected dates.
The pressing of Space or Enter on a specific date while the user is holding the Ctrl key
adds the date to the current selection. If the date is already selected, it is removed from the
selection.
The pressing of Shift + Enter or Space performs a range selection. It selects all dates
between the most recently selected date (with Space or Enter or a mouse click) and the
date that holds the focused cell.
The pressing of Shift + Up Arrow or Down Arrow extends the selection up or down one
row in the month view respectively.
The pressing of Shift + Right Arrow or Left Arrow adds the next or previous date to the
current selection respectively.
For a runnable example on performing date selection over the keyboard, refer to this demo.
See Also
Server-Side API
1168
Telerik UI for ASP.NET Core
The Gantt displays a set of tasks and dependencies which are used to visualize project-planning
data. It provides a TreeList section where the user can edit the tasks, and sort and reorder them in a
grid-like fashion, and a Timeline section where the tasks and dependencies are visualized under an
adjustable time ruler. The user can resize, move, edit and remove them. The Gantt also supports the
display of the Timeline section in the day, week, and month views.
<kendo-gantt name="gantt" show-work-days="false" show-work-hours="false" snap="false"
height="700">
<columns>
<gantt-column field="title" title="Title" editable="true"
sortable="true"></gantt-column>
<gantt-column field="resources" title="Assigned Resources" editable="true"
sortable="true"></gantt-column>
</columns>
<views>
<gantt-view type="GanttViewType.Day"></gantt-view>
<gantt-view type="GanttViewType.Week"></gantt-view>
<gantt-view type="GanttViewType.Month" selected="true"></gantt-view>
</views>
<gantt-datasource type="DataSourceTagHelperType.Ajax">
<transport>
<read url="@Url.Action("ReadTasks","Gantt")" />
</transport>
<schema>
<model id="TaskID">
<fields>
<field name="TaskID" type="number"></field>
<field name="parentId" from="ParentID" type="number"></field>
<field name="title" from="Title" type="string"></field>
<field name="start" from="Start" type="date"></field>
<field name="end" from="End" type="date"></field>
<field name="summary" from="Summary" type="boolean"></field>
<field name="expanded" from="Expanded" type="boolean"
default-value="true"></field>
<field name="percentComplete" from="PercentComplete" type="number"></field>
<field name="orderId" from="OrderId" type="number"></field>
</fields>
</model>
</schema>
</gantt-datasource>
</kendo-gantt>
1169
Telerik UI for ASP.NET Core
Basic Configuration
With the attributes and inner tags you can define the columns, views, DataSource, messages, range
and all other widget options available from the API of the Gantt widget.
<kendo-gantt name="gantt" show-work-days="false" show-work-hours="false" snap="false"
height="700">
<tooltip visible="false" />
<current-time-marker enabled="false" />
<messages>
<views day="MyDay" week="MyWeek" month="MyMonth" />
</messages>
<columns>
<gantt-column field="title" title="Title" editable="true"
sortable="true"></gantt-column>
<gantt-column field="resources" title="Assigned Resources" editable="true"
sortable="true"></gantt-column>
</columns>
<views>
<gantt-view type="GanttViewType.Day"></gantt-view>
<gantt-view type="GanttViewType.Week"></gantt-view>
<gantt-view type="GanttViewType.Month" selected="true"></gantt-view>
</views>
</kendo-gantt>
See Also
Basic Usage of the Gantt TagHelper for ASP.NET Core (Demo)
Server-Side API
1170
Telerik UI for ASP.NET Core
Data Binding
The Gantt TagHelper enables you to set up the DataSource instances for its data, dependencies,
resources, and assignments.
<kendo-gantt name="gantt" show-work-days="false" show-work-hours="false" snap="false"
height="700">
<columns>
<gantt-column field="title" title="Title" editable="true"
sortable="true"></gantt-column>
<gantt-column field="resources" title="Assigned Resources" editable="true"
sortable="true"></gantt-column>
</columns>
<views>
<gantt-view type="GanttViewType.Day"></gantt-view>
<gantt-view type="GanttViewType.Week"></gantt-view>
<gantt-view type="GanttViewType.Month" selected="true"></gantt-view>
</views>
<gantt-datasource type="DataSourceTagHelperType.Ajax">
<transport>
<read url="@Url.Action("ReadTasks","Gantt")" />
<destroy url="@Url.Action("DestroyTask","Gantt")" />
<update url="@Url.Action("UpdateTask","Gantt")" />
<create url="@Url.Action("CreateTask","Gantt")" />
</transport>
<schema>
<model id="TaskID">
<fields>
<field name="TaskID" type="number"></field>
<field name="parentId" from="ParentID" type="number"></field>
<field name="title" from="Title" type="string"></field>
<field name="start" from="Start" type="date"></field>
<field name="end" from="End" type="date"></field>
<field name="summary" from="Summary" type="boolean"></field>
<field name="expanded" from="Expanded" type="boolean"
default-value="true"></field>
<field name="percentComplete" from="PercentComplete" type="number"></field>
<field name="orderId" from="OrderId" type="number"></field>
</fields>
</model>
</schema>
</gantt-datasource>
<dependency-datasource name="dependencies" type="DataSourceTagHelperType.Ajax">
<transport>
<read url="@Url.Action("ReadDependencies", "Gantt")" />
<create url="@Url.Action("CreateDependency", "Gantt")" />
<destroy url="@Url.Action("DestroyDependency", "Gantt")" />
</transport>
<schema>
<model id="DependencyID">
<fields>
<field name="DependencyID" type="number"></field>
<field name="predecessorId" from="PredecessorID" type="number"></field>
<field name="successorId" from="SuccessorID" type="number"></field>
<field name="type" from="Type" type="number"></field>
</fields>
</model>
</schema>
</dependency-datasource>
1171
Telerik UI for ASP.NET Core
<resources field="resources" datacolorfield="Color" datatextfield="Name">
<datasource type="DataSourceTagHelperType.Custom">
<schema data="Data">
<model id="ID"></model>
</schema>
<transport>
<read url="@Url.Action("ReadResources", "Gantt")" />
</transport>
</datasource>
</resources>
<assignments datataskidfield="TaskID" dataresourceidfield="ResourceID"
datavaluefield="Units">
<datasource type="DataSourceTagHelperType.Ajax">
<schema>
<model id="ID">
<fields>
<field name="ID" type="number"></field>
<field name="TaskID" type="number"></field>
<field name="ResourceID" type="number"></field>
<field name="Units" type="number"></field>
</fields>
</model>
</schema>
<transport>
<read url="@Url.Action("ReadAssignments", "Gantt")" />
<create url="@Url.Action("CreateAssignment", "Gantt")" />
<destroy url="@Url.Action("DestroyAssignment", "Gantt")" />
<update url="@Url.Action("UpdateAssignment", "Gantt")" />
</transport>
</datasource>
</assignments>
</kendo-gantt>
You can also use external DataSource tag helpers to implement the same and assign their names to
the corresponding fields.
<kendo-ganttdatasource name="ganttdatasource" type="DataSourceTagHelperType.Ajax">
<transport>
<read url="@Url.Action("ReadTasks","Gantt")" />
<destroy url="@Url.Action("DestroyTask","Gantt")" />
<update url="@Url.Action("UpdateTask","Gantt")" />
<create url="@Url.Action("CreateTask","Gantt")" />
</transport>
<schema>
<model id="TaskID">
<fields>
<field name="TaskID" type="number"></field>
<field name="parentId" from="ParentID" type="number"></field>
<field name="title" from="Title" type="string"></field>
<field name="start" from="Start" type="date"></field>
<field name="end" from="End" type="date"></field>
<field name="summary" from="Summary" type="boolean"></field>
<field name="expanded" from="Expanded" type="boolean"
default-value="true"></field>
<field name="percentComplete" from="PercentComplete" type="number"></field>
<field name="orderId" from="OrderId" type="number"></field>
</fields>
</model>
</schema>
</kendo-ganttdatasource>
1172
Telerik UI for ASP.NET Core
<kendo-ganttdependencydatasource name="ganttdependencydatasource"
type="DataSourceTagHelperType.Ajax">
<transport>
<read url="@Url.Action("ReadDependencies", "Gantt")" />
<create url="@Url.Action("CreateDependency", "Gantt")" />
<destroy url="@Url.Action("DestroyDependency", "Gantt")" />
</transport>
<schema>
<model id="DependencyID">
<fields>
<field name="DependencyID" type="number"></field>
<field name="predecessorId" from="PredecessorID" type="number"></field>
<field name="successorId" from="SuccessorID" type="number"></field>
<field name="type" from="Type" type="number"></field>
</fields>
</model>
</schema>
</kendo-ganttdependencydatasource>
<kendo-datasource name="resourcesdatasource" type="DataSourceTagHelperType.Custom">
<schema data="Data">
<model id="ID"></model>
</schema>
<transport>
<read url="@Url.Action("ReadResources", "Gantt")" />
</transport>
</kendo-datasource>
<kendo-datasource name="assignmentsdatasource" type="DataSourceTagHelperType.Ajax">
<schema>
<model id="ID">
<fields>
<field name="ID" type="number"></field>
<field name="TaskID" type="number"></field>
<field name="ResourceID" type="number"></field>
<field name="Units" type="number"></field>
</fields>
</model>
</schema>
<transport>
<read url="@Url.Action("ReadAssignments", "Gantt")" />
<create url="@Url.Action("CreateAssignment", "Gantt")" />
<destroy url="@Url.Action("DestroyAssignment", "Gantt")" />
<update url="@Url.Action("UpdateAssignment", "Gantt")" />
</transport>
</kendo-datasource>
<kendo-gantt name="gantt" show-work-days="false" show-work-hours="false" snap="false"
height="700" datasource-id="ganttdatasource"
dependancy-datasource-id="ganttdependencydatasource">
<columns>
<gantt-column field="title" title="Title" editable="true"
sortable="true"></gantt-column>
<gantt-column field="resources" title="Assigned Resources" editable="true"
sortable="true"></gantt-column>
</columns>
<views>
<gantt-view type="GanttViewType.Day"></gantt-view>
<gantt-view type="GanttViewType.Week"></gantt-view>
<gantt-view type="GanttViewType.Month" selected="true"></gantt-view>
</views>
<resources field="resources" datacolorfield="Color" datatextfield="Name"
datasource-id="resourcesdatasource">
1173
Telerik UI for ASP.NET Core
</resources>
<assignments datataskidfield="TaskID" dataresourceidfield="ResourceID"
datavaluefield="Units" datasource-id="assignmentsdatasource">
</assignments>
</kendo-gantt>
See Also
Server-Side API
1174
Telerik UI for ASP.NET Core
The MultiViewCalendar renders a graphical Gregorian calendar with multiple horizontal views.
public ActionResult Index()
{
return View();
}
3. Add a MultiViewCalendar.
<kendo-multiviewcalendar name="multiviewcalendar"
min="new DateTime(2010, 1, 1, 10, 0, 0)"
max="new DateTime(2010, 1, 1, 20, 0, 0)"
value="DateTime.Now">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar") // The name of the MultiViewCalendar is
mandatory. It specifies the "id" attribute of the widget.
.Min(new DateTime(2010, 1, 1, 10, 0, 0)) // Set the min time of the
MultiViewCalendar.
.Max(new DateTime(2010, 1, 1, 20, 0, 0)) // Set the min date of the
MultiViewCalendar.
.Value(DateTime.Now) // Set the value of the MultiViewCalendar.
)
1175
Telerik UI for ASP.NET Core
Disable dates
Week column
Keyboard navigation
Events
You can subscribe to all MultiViewCalendar events.
<kendo-multiviewcalendar name="multiviewcalendar" on-change="calendar_change"
on-navigate="calendar_navigate">
</kendo-multiviewcalendar>
<script>
function calendar_navigate() {
// Handle the navigate event.
}
function calendar_change() {
// Handle the change event.
}
</script>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Events(e => e
.Change("calendar_change")
.Navigate("calendar_navigate")
)
)
<script>
function calendar_navigate() {
// Handle the navigate event.
}
function calendar_change() {
// Handle the change event.
}
</script>
See Also
Basic Usage of the MultiViewCalendar TagHelper for ASP.NET Core (Demo)
Server-Side API
1176
Telerik UI for ASP.NET Core
Active View
To define the first view which the MultiViewCalendar initially renders, use the Start option.
<kendo-multiviewcalendar name="multiviewcalendar" start="CalendarView.Year"
depth="CalendarView.Year">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Start(CalendarView.Year)
.Depth(CalendarView.Year)
)
See Also
Server-Side API
1177
Telerik UI for ASP.NET Core
Multiple Views
The Telerik UI MultiViewCalendar allows you to define the number of views and months that are
displayed at a time.
In some scenarios it might be necessary to display more than two months. This is especially helpful
when performing range selection between months.
<kendo-numerictextbox name="numberOfViews" restrict-decimals="true" decimals="0"
min="2" max="10" format="n0"/>
<kendo-button name="numberOfViewsBtn" on-click="click">
Apply Changes
</kendo-button>
<kendo-multiviewcalendar name="multiviewcalendar">
</kendo-multiviewcalendar>
<script>
function click() {
var numberOfViews = $("#numberOfViews").data().kendoNumericTextBox.value();
if (numberOfViews > 0) {
$("#multiViewCalendar").data().kendoMultiViewCalendar.setOptions({
numberOfVies: numberOfViews });
}
}
</script>
@(Html.Kendo().NumericTextBox()
.Name("numberOfViews")
.RestrictDecimals(true)
.Decimals(0)
.Min(2)
.Max(10)
.Value(2)
.Format("{0:n0}")
)
@(Html.Kendo().Button()
.Name("numberOfViewsBtn")
.Content("Apply Changes")
.Events(ev => ev.Click("click"))
)
@(Html.Kendo().MultiViewCalendar()
.Name("multiViewCalendar")
)
<script>
function click() {
var numberOfViews = $("#numberOfViews").data().kendoNumericTextBox.value();
if (numberOfViews > 0) {
$("#multiViewCalendar").data().kendoMultiViewCalendar.setOptions({
numberOfVies: numberOfViews });
}
}
</script>
1178
Telerik UI for ASP.NET Core
See Also
Server-Side API
1179
Telerik UI for ASP.NET Core
Selection
The Kendo UI MultiViewCalendar allows the user to select multiple dates by using the multiple-view
MultiViewCalendar selection mode.
<kendo-multiviewcalendar name="multiviewcalendar" selectable="range">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Selectable("range")
)
See Also
Server-Side API
1180
Telerik UI for ASP.NET Core
Day Template
The MultiViewCalendar enables you to customize the rendered day for the month view.
<kendo-multiviewcalendar name="multiviewcalendar">
<month content="<div class='custom'><#=data.value#></div>"/>
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.MonthTemplate("<div class='custom'><#=data.value#></div>")
)
The template wraps the value in a <div> HTML element. The structure of the data object that is
passed to the template function:
data = {
date: date, // Date object corresponding to the current cell
title: kendo.toString(date, "D"),
value: date.getDate(),
dateString: "2011/0/1" // formatted date using yyyy/MM/dd format and month is
zero-based
};
See Also
Server-Side API
1181
Telerik UI for ASP.NET Core
Disabled Dates
The MultiViewCalendar allows you to disable certain days which are not intended to be selected by
the end user such as weekends, national holidays, and others.
To disable a date set an array of the dates that have to be disabled and list the days that need to be
disabled by using the first letters from their names in English.
<kendo-multiviewcalendar name="multiviewcalendar" disable-dates="new DateTime[] {
DateTime.Now }">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.DisableDates(new[] {"we", "th" })
)
See Also
Server-Side API
1182
Telerik UI for ASP.NET Core
<kendo-multiviewcalendar name="multiviewcalendar" week-number="true">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.WeekNumber(true)
)
See Also
Server-Side API
1183
Telerik UI for ASP.NET Core
Keyboard Navigation
The keyboard navigation of the MultiViewCalendar is always available.
Shortcut Description
Up Arrow Highlights the same day from the previous
week.
Down Arrow Highlights the same day from the next week.
Left Arrow Highlights the previous day.
Right Arrow Highlights the next day.
Enter Selects the focused date.
Home Focuses the first date in the month.
End Focuses the last date in the month.
Ctrl+Up Arrow Navigates to the previous view.
Ctrl+Down Arrow Navigates to the next view.
Ctrl+Down Left Navigates to the previous month.
Ctrl+Down Right Navigates to the next month.
<kendo-multiviewcalendar name="multiviewcalendar" selectable="multiple">
</kendo-multiviewcalendar>
@(Html.Kendo().MultiViewCalendar()
.Name("MultiViewCalendar")
.Selectable("multiple")
)
See Also
Server-Side API
1184
Telerik UI for ASP.NET Core
The Scheduler displays a set of events, appointments, or tasks. It supports the display of scheduled
events in different views—single days, whole weeks, or months, or as a list of tasks which need to be
accomplished.
As of the Kendo UI for jQuery R1 2017 release, exceptions are no longer automatically removed
when the user edits a series. Changes that are made to specific occurrences are persisted during
series editing. If a series contains an exception, the Scheduler renders a Reset Series button within
the Edit dialog of the series which allows the user to reset the series by removing existing
exceptions.
<kendo-scheduler name="scheduler"></kendo-scheduler>
Basic Configuration
The Scheduler TagHelper configuration options are passed as attributes of the tag. For more details
on the Scheduler configurations, refer to the overview of the MVC Scheduler HtmlHelperand the Kendo
Scheduler for jQuery.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WorkWeekView(workWeekView =>
{
workWeekView.Selected(true);
});
views.WeekView();
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.Resources(resource =>
1185
Telerik UI for ASP.NET Core
{
resource.Add(m => m.OwnerID)
.Title("Owner")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Alex", Value = 1, Color = "#f8a398" } ,
new { Text = "Bob", Value = 2, Color = "#51a0ed" } ,
new { Text = "Charlie", Value = 3, Color = "#56ca85" }
});
})
.DataSource(d => d
.Events(e => e.Error("onError"))
.Model(m =>
{
m.Id(f => f.TaskID);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.OwnerID).DefaultValue(1);
m.RecurrenceId(f => f.RecurrenceID);
})
.Read("Read", "Scheduler")
.Create("Create", "Scheduler")
.Destroy("Destroy", "Scheduler")
.Update("Update", "Scheduler")
.Filter(filters =>
{
filters.Add(model => model.OwnerID).IsEqualTo(1).Or().IsEqualTo(2);
})
)
)
@{
var resources = new[]
{
new { Text = "Alex", Value = 1, Color = "#f8a398" },
new { Text = "Bob", Value = 2, Color = "#51a0ed" },
new { Text = "Charlie", Value = 3, Color = "#56ca85" },
};
}
<kendo-scheduler name="scheduler" height="600" date="new DateTime(2013, 6, 13)"
start-time="new DateTime(2013, 6, 13, 7, 0, 0, 0)" timezone="Etc/UTC">
<views>
<view type="day"></view>
<view type="workWeek" selected="true"></view>
<view type="week"></view>
<view type="month"></view>
<view type="agenda"></view>
<view type="timeline"></view>
</views>
<resources>
<resource name="Owner" datacolorfield="Color" datatextfield="Text"
datavaluefield="Value" field="OwnerID" bind-to="@resources">
</resource>
</resources>
<scheduler-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/tasks" type="jsonp" />
<update url="https://demos.telerik.com/kendo-ui/service/tasks/update"
type="jsonp" />
</transport>
1186
Telerik UI for ASP.NET Core
<schema data="Data" total="Total" errors="Errors">
<scheduler-model id="TaskID">
<fields>
<field name="TaskID" type="number"></field>
<field name="title" from="Title" type="string"></field>
<field name="start" from="Start" type="date"></field>
<field name="end" from="End" type="date"></field>
<field name="description" from="Description" type="number"></field>
<field name="recurrenceId" type="number" from="RecurrenceID"></field>
<field name="recurrenceRule" type="string" from="RecurrenceRule"></field>
<field name="recurrenceException" type="string"
from="RecurrenceException"></field>
<field name="OwnerID" type="number"></field>
<field name="startTimezone" from="StartTimeZone" type="string"></field>
<field name="endTimezone" from="EndTimeZone" type="string"></field>
<field name="isAllDay" from="IsAllDay" type="boolean"></field>
</fields>
</scheduler-model>
</schema>
</scheduler-datasource>
</kendo-scheduler>
See Also
Basic Usage of the Scheduler TagHelper for ASP.NET Core (Demo)
Server-Side API
1187
Telerik UI for ASP.NET Core
Selection
The Scheduler supports enables the user to select events.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
.Name("scheduler")
.Height(600)
.Selectable(true)
)
<kendo-scheduler name="scheduler" height="600" selectable="true">
</kendo-scheduler>
See Also
Server-Side API
1188
Telerik UI for ASP.NET Core
Grouping
The Scheduler provides options for grouping its resources.
@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Group(group => { group.Resources("Owner"); })
.Views(views =>
{
views.DayView();
views.WorkWeekView(workWeekView =>
{
workWeekView.Selected(true);
});
views.WeekView();
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.Resources(resource =>
{
resource.Add(m => m.OwnerID)
.Title("Owner")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(new[] {
new { Text = "Alex", Value = 1, Color = "#f8a398" } ,
new { Text = "Bob", Value = 2, Color = "#51a0ed" } ,
new { Text = "Charlie", Value = 3, Color = "#56ca85" }
});
})
.DataSource(d => d
.Events(e => e.Error("onError"))
.Model(m =>
{
m.Id(f => f.TaskID);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.OwnerID).DefaultValue(1);
m.RecurrenceId(f => f.RecurrenceID);
})
.Read("Read", "Scheduler")
.Create("Create", "Scheduler")
.Destroy("Destroy", "Scheduler")
.Update("Update", "Scheduler")
.Filter(filters =>
{
filters.Add(model => model.OwnerID).IsEqualTo(1).Or().IsEqualTo(2);
})
)
)
1189
Telerik UI for ASP.NET Core
@{
var resources = new[]
{
new { Text = "Alex", Value = 1, Color = "#f8a398" },
new { Text = "Bob", Value = 2, Color = "#51a0ed" },
new { Text = "Charlie", Value = 3, Color = "#56ca85" },
};
}
<kendo-scheduler name="scheduler" height="600" date="new DateTime(2013, 6, 13)"
selectable="true" start-time="new DateTime(2013, 6, 13, 7, 0, 0, 0)"
timezone="Etc/UTC">
<views>
<view type="day"></view>
<view type="workWeek" selected="true"></view>
<view type="week"></view>
<view type="month"></view>
<view type="agenda"></view>
<view type="timeline"></view>
</views>
<group>
<resources>
<group-resource name="Owner" />
</resources>
</group>
<resources>
<resource name="Owner" datacolorfield="Color" datatextfield="Text"
datavaluefield="Value" field="OwnerID" bind-to="@resources">
</resource>
</resources>
<scheduler-datasource>
<transport>
<read url="https://demos.telerik.com/kendo-ui/service/tasks" type="jsonp" />
<update url="https://demos.telerik.com/kendo-ui/service/tasks/update"
type="jsonp" />
</transport>
<schema data="Data" total="Total" errors="Errors">
<scheduler-model id="TaskID">
<fields>
<field name="TaskID" type="number"></field>
<field name="title" from="Title" type="string"></field>
<field name="start" from="Start" type="date"></field>
<field name="end" from="End" type="date"></field>
<field name="description" from="Description" type="number"></field>
<field name="recurrenceId" type="number" from="RecurrenceID"></field>
<field name="recurrenceRule" type="string" from="RecurrenceRule"></field>
<field name="recurrenceException" type="string"
from="RecurrenceException"></field>
<field name="OwnerID" type="number"></field>
<field name="startTimezone" from="StartTimeZone" type="string"></field>
<field name="endTimezone" from="EndTimeZone" type="string"></field>
<field name="isAllDay" from="IsAllDay" type="boolean"></field>
</fields>
</scheduler-model>
</schema>
</scheduler-datasource>
</kendo-scheduler>
See Also
Server-Side API
1190
Telerik UI for ASP.NET Core
Cards
The Telerik UI Cards for ASP.NET Core is a set of classes that define flexible content containers.
A card can consist of a header, a body, and actions and can also accommodate images, lists,
groups, separators, and more.
Getting Started
To build a card, utilize the .k-card class which enables you to use a wide variety of content.
<div class="k-card">
...
</div>
Building Blocks
The Card can accommodate the following elements:
Header
Body
Actions
Images
Separators
Header
The header of the Card is an optional element. To render a Card header, use the .k-card-header
class which can include a title and a subtitle.
<div class="k-card" style="width: 300px;">
<div class="k-card-header">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
</div>
<div class="k-card-body">
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
</div>
You can also use titles and subtitles outside the header.
1191
Telerik UI for ASP.NET Core
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
Body
The main content of a card is the body which can be defined through the .k-card-body class.
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<p>
Some quick example text to build on the card title and make up the bulk of the
card content.
</p>
</div>
</div>
Actions
You can add a list of actions to a Card by using the .k-card-actions class.
<div class="k-card" style="width: 300px;">
<div class="k-card-header">
Card Header
</div>
<div class="k-card-body">
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-card-action">
1192
Telerik UI for ASP.NET Core
<span class="k-button k-flat k-primary">Action 1</span>
</span>
<span class="k-card-action">
<span class="k-button k-flat k-primary">Action 2</span>
</span>
</div>
</div>
The actions can be stretched to take the entire container by adding the
.k-card-actions-stretched.
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions k-card-actions-stretched">
<span class="k-card-action">
<span class="k-button k-flat k-primary">Action 1</span>
</span>
<span class="k-card-action">
<span class="k-button k-flat k-primary">Action 2</span>
</span>
</div>
</div>
The actions can also be forced to display vertically through the .k-card-actions-vertical class.
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions k-card-actions-vertical">
<span class="k-card-action"><span class="k-button k-flat k-primary">Action
1</span></span>
<span class="k-card-action"><span class="k-button k-flat k-primary">Action
2</span></span>
</div>
</div>
Images
Cards support images through the .k-card-image class.
<div class="k-card" style="width: 300px;">
<div class="k-card-header">
Card Header
</div>
<img class="k-card-image" />
<div class="k-card-body">
1193
Telerik UI for ASP.NET Core
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
</div>
Separators
To include Card separators, use the .k-hr class.
<div class="k-card" style="width: 300px;">
<div class="k-columnset k-flex-auto">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<hr class="k-hr" />
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
</div>
</div>
Layout
Cards expose additional classes that are used for laying out series of cards.
<div class="k-card-list">
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
1194
Telerik UI for ASP.NET Core
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
</div>
<div class="k-card-group">
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
1195
Telerik UI for ASP.NET Core
</div>
<div class="k-card-deck">
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
</div>
Styles
Cards provide predefined state classes that you can use to change the Card appearance.
<div class="k-card k-state-primary" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title Primary</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
1196
Telerik UI for ASP.NET Core
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card k-state-info" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title Info</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card k-state-success" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title Success</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card k-state-warning" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title Warning</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
<div class="k-card k-state-error" style="width: 300px;">
<div class="k-card-body">
<h5 class="k-card-title">Card Title Error</h5>
<h6 class="k-card-subtitle">Card Subtitle</h6>
<p>Some quick example text to build on the card title and make up the bulk of
the card content.</p>
</div>
<div class="k-card-actions">
<span class="k-button k-flat k-primary">Action 1</span>
<span class="k-button k-flat k-primary">Action 2</span>
</div>
</div>
1197
Telerik UI for ASP.NET Core
The tool renders the same look and feel as the look and feel of all other components in the suite. It
also delivers full control over the skin elements of each component and automatically updates its
composite units. After you create the skin and achieve the desired look of the theme, the Sass
Theme Builder enables you to download and integrate it in your project.
1. On the initial Sass Theme Builder pane, select the Start Theming option.
2. Choose one of the existing skins to use as a base. The currently available built-in skins are
Default and Bootsrap.
1198
Telerik UI for ASP.NET Core
Modifying Themes
The Sass Theme Builder supports the following options for customization:
To customize an existing theme, use the following Sass Theme Builder features:
1. Color swatches—Contains predefined color palettes that you can apply to all components in
your application.
2. Default—Provides the applicable color customization options.
3. Preview components—Keeps the main view of the components. It reflects the customization
changes you make each time you add or remove theme elements.
4. Download—Downloads the archive that holds the generated style files after the
customization completes. When you click the button, a dialog appears and prompts you to
name your theme.
1199
Telerik UI for ASP.NET Core
1200
Telerik UI for ASP.NET Core
When you complete the modifications and the theme is ready to be used:
Reference only the all.css file because the exported CSS file contains all styles you need.
See Also
Cards
1201
Telerik UI for ASP.NET Core
To see the example, refer to the GitHub repo on how to change the theme on the client.
See Also
Including Client-Side Resources
Sass ThemeBuilder
Cards
1202
Telerik UI for ASP.NET Core
Globalization Overview
Globalization is the process of designing and developing an application that works in multiple
cultures and languages.
Applying Cultures
To use a culture that is different from the default en-US one in Telerik UI for ASP.NET Core:
1. Copy the required culture JavaScript file from the \js\culture\ folder of your Telerik UI for
ASP.NET Core installation to the wwwroot/lib/kendo-ui/js/cultures/ folder of your
application. This example uses the Spanish es-ES culture.
2. Include the corresponding culture JavaScript file after the other JavaScript product files.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/kendo-ui/js/kendo.all.min.js"></script>
<script src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"></script>
<script
src="~/lib/kendo-ui/js/cultures/kendo.culture.es-ES.min.js"></script>
3. Set the current culture by calling the kendo.culturemethod. You have to add the script
block after the culture JavaScript file. As a result, all Telerik UI for ASP.NET Core helpers will
use the es-ES culture for parsing and formatting dates and numbers.
<script>
kendo.culture("es-ES");
</script>
Matching Cultures
The cultures that are set on the client and on the server have to match. This ensures that dates and
numbers are displayed and parsed correctly.
var supportedCultures = new[] { new CultureInfo("es-ES") };
1203
Telerik UI for ASP.NET Core
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("es-ES"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
1. Copy the required culture JavaScript files from the \js\culture\ folder of your Telerik UI
for ASP.NET Core installation to the wwwroot/lib/kendo-ui/js/cultures/ folder of your
application.
2. Get the current culture.
@{
var culture = System.Globalization.CultureInfo.CurrentCulture.ToString();
}
<script src="@Url.Content("~/lib/kendo/js/cultures/kendo.culture." + culture +
".min.js")"></script>
4. Set the current culture by calling the kendo.culturemethod. You have to add the script
block after the culture JavaScript file.
Set the client-side culture before initializing any helpers that rely on it.
<script>
kendo.culture("@culture");
</script>
See Also
Overview of Localization by Telerik UI for ASP.NET Core
1204
Telerik UI for ASP.NET Core
Localization
Localizationis the process of adapting software to meet the requirements of local markets and
different languages.
You can change the messages that are displayed in the Telerik UI for ASP.NET Core helpers by
including an additional script file in the document.
Include the localization script before the helpers are initialized. The best place to include it is right
after the Kendo UI JavaScript files.
The following example demonstrates how to register the localization script in the _Layout.cshtml
file.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/kendo-ui/js/kendo.all.min.js"></script>
<script src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"></script>
<script src="~/lib/kendo-ui/js/cultures/kendo.messages.es-ES.min.js"></script>
The following example demonstrates how to register the localization script in the _Layout.cshtml
file by using CDN.
<script src="https://kendo.cdn.telerik.com/<version>/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/<version>/js/kendo.all.min.js"></script>
<script
src="https://kendo.cdn.telerik.com/<version>/js/kendo.aspnetmvc.min.js"></script>
<script
src="https://kendo.cdn.telerik.com/<version>/js/messages/kendo.messages.es-ES.min.js">
</script>
Currently, translations are not available for every language and some of the localization files may be
incomplete. For more information on the full list of available translations, refer to the section on
contributing.
1205
Telerik UI for ASP.NET Core
network website.
The following example demonstrates how to create a new localization file. The
kendo.messages.en-US.js contains all messages and may be used as a reference when you
create the new localization file—copy the file, rename it, and translate the messages.
/* <Helper-name> messages */
if (kendo.ui.<Helper-name>) {
kendo.ui.<Helper-name>.prototype.options.messages =
$.extend(true, kendo.ui.<Helper-name>.prototype.options.messages,{
"<message-name>": "<translation",
//...
});
}
Contribution
Currently, translations are not available for every language and some of the localization files may be
incomplete. The full list of currently available translations is available in the Kendo UI Core repository.
If you notice any missing messages in the localization files or would like to add localization files for
your language, do not hesitate to:
See Also
Overview of Globalization by Telerik UI for ASP.NET Core
1206
Telerik UI for ASP.NET Core
Accessibility Overview
Websites and applications are accessible when they provide full control over their features by
enabling users with disabilities to access their content by using assistive technologies or keyboard
navigation.
For the full list of components which support accessibility and keyboard navigation, refer to the
article on accessibility support by Telerik UI for ASP.NET Core.
Section 508
W3C Web Content Accessibility Guidelines (WCAG) 2.0
WAI-ARIA
Keyboard navigation requirements
Section 508
Section 508 of the Rehabilitation Act is a set of accessibility standards set by the U.S. General
Services Administration (GSA). They apply to electronic and information technology and contain
technical criteria specific to various types of technologies and performance-based requirements
which focus on the functional capabilities of the listed products.
WCAG 2.1
The W3C Web Content Accessibility Guidelines set the standards for applications regarding the
provision of accessible content. Depending on the number of guidelines that are followed when
building an application, W3C defines three levels of accessibility conformance—A, AA, and AAA
levels.
WAI-ARIA
WAI-ARIA is a World Wide Web Consortium accessibility specification. It specifies steps for
developing web components that make them more accessible to assistive technologies such as
screen readers. The WAI-ARIA framework is designed to be a framework for web developers to apply
while creating web applications that use Ajax, scripting, and other rich application techniques.
Keyboard Navigation
By default, users can only navigate to links, buttons, and form controls with a keyboard. The
navigation order in which interactive items receive keyboard focus has to be logical and intuitive.
Generally, it needs to follow the visual horizontal and vertical flow of the page. For example, left to
right and top to bottom, header first followed by the main and then page navigation.
1207
Telerik UI for ASP.NET Core
Suggested Links
Accessibility Support by Telerik UI for ASP.NET Core
GSA Government-Wide Section 508 Accessibility Program
WAI-ARIA Authoring Practices
1208
Telerik UI for ASP.NET Core
Accessibility Compliance
The following table lists the Telerik UI for ASP.NET Core components which support accessibility
and keyboard navigation options.
1209
Telerik UI for ASP.NET Core
Suggested Links
Overview of Accessibility
1210
Telerik UI for ASP.NET Core
Breaking Changes
Telerik UI for ASP.NET Coreis a set of server-side wrappers that allows you to use the Kendo UI
widgetsfrom the server code. That is why, all important changes in the Kendo UI suite also apply to
the client-side code and behavior of the Telerik UI for ASP.NET Core wrappers. For the list of all
breaking changes, refer to the articles on the Kendo UI breaking changes.
See Also
Kendo UI 2019 Breaking Changes
Kendo UI 2018 Breaking Changes
1211
Telerik UI for ASP.NET Core
2018 Releases
Kendo UI R2 2018
As of the Kendo UI R2 2018 release, the sample application, which represents an offline version of
the Telerik UI for ASP.NET Core Demos, is only available for Visual Studio 2017. The Visual Studio
2015 version which contains the deprecated project.json base version is no longer distributed.
Dialog—Previously, it was possible to nest content directly in the <kendo-dialog> tag. Now
the content must be nested within a <content> tag.
Window—Previously, it was possible to nest content directly in the <kendo-window> tag.
Now the content must be nested within a <content> tag.
Upload:
The <kendo-upload-async-settings> tag name is now changed to <async>.
The <kendo-upload-files> tag name is now changed to <files>.
The <kendo-upload-file> tag name is now changed to <file>.
The <kendo-upload-localization-settings> tag name is now changed to
<localization>.
The <kendo-upload-validation-settings> tag name is now changed to
<validation>.
Splitter—Previously, the tag name of the pane was <kendo-splitter-pane>. The tag name
is now changed to <pane>.
1212
Telerik UI for ASP.NET Core
Licensing
Progress® Telerik UI for ASP.NET Core is available under a developer (commercial) or a trial license.
Regardless of the license version you hold, to use Telerik UI for ASP.NET Core, you have to agree to
the End User License Agreement for Progress Kendo UI, Progress Telerik UI for ASP.NET MVC, Progress
Telerik UI for ASP.NET Core, Progress Telerik UI for JSP, and Progress Telerik UI for PHP .
You can find the license agreement in your Telerik controls installation folder under
\LicenseAgreements\EULA.rtf. For example, the default location for the R2 2018 release is
C:\Program Files (x86)\Progress\Telerik UI for ASP.NET Core R2
2018\LicenseAgreements\EULA.rtf.
Developer Licenses
Developer licenses come with modified DLLs which work without displaying copyright messages. If
you have a Developer license for one or more of the Telerik components, only make sure that you are
using the developer build when downloading the controls. These builds have the Dev abbreviation in
their file names.
If your application is displaying a copyright message intermittently, this means that you are using a
trial version of the product. Log in into your Telerik accountand download the developer build through
the Products & Subscriptions menu and its Purchased Products section. To update your project,
refer to the Upgrading the Trial License to a Production License section for the step-by-step
instructions.
For more information on the commercial terms, refer to the pricing list of the available developer
licenses which include Telerik UI for ASP.NET Core .
Trial Licenses
The free trial licenses of all Telerik products are fully functional and will work for an unlimited time
but with copyright message (see below) displayed randomly on the page.
Trial licenses provide free and fully functional access to all Telerik UI for ASP.NET Core products.
While the trial version is unlimited in time, the pages will randomly display the following copyright
message: "Thank you for using the Trial Version of Progress® Telerik UI for ASP.NET Core to build
1213
Telerik UI for ASP.NET Core
more powerful applications faster. Purchase the Commercial Version now to get access to all
product updates and the Telerik expert support".
Licensing Mechanism
As of the Q1 2015 release, Telerik® UI for ASP.NET Core uses the standard .NET licensing
mechanism—if you use Telerik® UI for ASP.NET Core items in design-time, Visual Studio adds a
license.licx file to the solution. This file is used only in design-mode and is not needed for
deployment explicitly. The .NET framework (lc.exe) will embed it in the assembly when your
application is built for deployment.
The license.licx license file is maintained by Visual Studio and contains information about all
licensed components in the application, including non-Telerik products. Having this license file is not
expected to bring any performance or compilation issues and you can ignore it.
If your project build fails with errors which point to the license file, you can delete it and rebuild.
Alternatively, you can clear its contents and mark it as Read Only.
If you are working under source control, once the file is created, it will be detected as a change by
your source control system. Telerik suggests that you check in this file initially. When the file is
checked out again during your work, it is up to you to decide whether to check it in, or discard the
changes.
See Also
First Steps on Visual Studio for Windows (Online Guide)
First Steps on Visual Studio for Mac (Online Guide)
First Steps with CLI (Online Guide)
1214
Telerik UI for ASP.NET Core
Upgrade
You can upgrade the version of the Telerik UI for ASP.NET Core helpers and also switch from a trial
to a developer license.
1. In Visual Studio, open the NuGet Package Manager on the Installed tab and click Update for
the Telerik.UI.for.AspNet.Core package.
2. In Visual Studio, open the Bower Package Manager on the Installed tab and click Update for
the kendo-ui package.
3. In the application, manually replace any references which point to the old Kendo UI resource
files such as scripts and styles.
To properly load the Telerik and Kendo UI packages, both NuGetand Bowerrequire authentication.
Upgrading Manually
1. Downloadthe desired version from the Download section of your account.
2. Replace all scripts, styles, and images that are related to Telerik UI for ASP.NET Core with
the desired version of the framework.
3. Change the reference to the new Kendo.MVC dll and verify that the dll refers to the correct
ASP.NET Core version.
4. In the application, manually replace any references which point to the old Kendo UI resource
files such as scripts and styles.
See Also
First steps on Visual Studio for Windows (online guide)
1215
Telerik UI for ASP.NET Core
1216
Telerik UI for ASP.NET Core
Virtual Classroom
The Progress® Virtual Classroom contains product-focused training courses and represent a free
on-demand technical training program exclusive to active license holders.
Each session provides practical knowledge combined with helpful approaches to application
development which are suitable for both junior and senior developers.
1217
Telerik UI for ASP.NET Core
Additionally, this information may be used by Marketing and/or Sales to ensure you receive relevant
content updates, product news, and materials. Please see our Privacy Policyfor more details.
This information is for our own purposes and we do not sell or otherwise provide this information to
any third-parties for a commercial purpose.
1218
Telerik UI for ASP.NET Core
Copyright
© 2020 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights
reserved.
These materials and all Progress® software products are copyrighted and all rights are reserved by
Progress Software Corporation. The information in these materials is subject to change without
notice, and Progress Software Corporation assumes no responsibility for any errors that may appear
therein. The references in these materials to specific platforms supported are subject to change.
Business Making Progress, Corticon, DataDirect (and design), DataDirect Cloud, DataDirect Connect,
DataDirect Connect64, DataDirect XML Converters, DataDirect XQuery, Deliver More Than Expected,
Icenium, Kendo UI, Making Software Work Together, NativeScript, OpenEdge, Powered by Progress,
Progress, Progress Software Business Making Progress, Progress Software Developers Network,
Rollbase, RulesCloud, RulesWorld, SequeLink, Sitefinity (and Design), SpeedScript, Stylus Studio,
TeamPulse, Telerik, Telerik (and Design), Test Studio, and WebSpeed are registered trademarks of
Progress Software Corporation or one of its affiliates or subsidiaries in the U.S. and/or other
countries. AccelEvent, AppsAlive, AppServer, BravePoint, BusinessEdge, DataDirect Spy, DataDirect
SupportLink, Future Proof, High Performance Integration, OpenAccess, ProDataSet, Progress Arcade,
Progress Profiles, Progress Results, Progress RFID, Progress Software, ProVision, PSE Pro,
SectorAlliance, Sitefinity, SmartBrowser, SmartComponent, SmartDataBrowser, SmartDataObjects,
SmartDataView, SmartDialog, SmartFolder, SmartFrame, SmartObjects, SmartPanel, SmartQuery,
SmartViewer, SmartWindow, WebClient, and Who Makes Progress are trademarks or service marks
of Progress Software Corporation and/or its subsidiaries or affiliates in the U.S. and other countries.
Java is a registered trademark of Oracle and/or its affiliates. Any other marks contained herein may
be trademarks of their respective owners.
Please refer to the Release Notes applicable to the particular Progress product release for any
third-party acknowledgements required to be provided in the documentation associated with the
Progress product.
1219