Ej2 Aspnetmvc Docs
Ej2 Aspnetmvc Docs
Introduction 1.1
Installation 1.2
System Requirements 1.3
Getting Started 1.4
NuGet Packages 1.5
State Persistence 1.6
Accessibility 1.7
Browser Compatibility 1.8
Theming 1.9
Avatar 2.1
Getting Started(ASP.NET MVC) 2.1.1
Types 2.1.2
How-To 2.1.3
Badge 3.1
Getting Started(ASP.NET MVC) 3.1.1
Types 3.1.2
How-To 3.1.3
Release Notes 4.1
v16.2.41 4.1.1
v16.1.37 4.1.2
v16.1.34 4.1.3
v16.1.32 4.1.4
v16.1.25 4.1.5
v16.1.24 4.1.6
Migration from 16.1 to 16.2 4.1.7
Button Group 5.1
Getting Started 5.1.1
Types and Styles 5.1.2
Selection and Nesting 5.1.3
Accessibility 5.1.4
How To 5.1.5
1
Base 6.1
Localization 6.1.1
Internationalization 6.1.2
Right-To-Left 6.1.3
Button 7.1
Getting Started 7.1.1
Types and Styles 7.1.2
How To 7.1.3
Calendar 8.1
Getting Started 8.1.1
Date Range 8.1.2
Globalization 8.1.3
Customization 8.1.4
Calendar Views 8.1.5
Accessibility 8.1.6
How To 8.1.7
Card 9.1
Getting Started 9.1.1
Header and Content 9.1.2
Image and Divider 9.1.3
Action Buttons 9.1.4
Horizontal Card 9.1.5
How to 9.1.6
Chart 10.1
Getting Started 10.1.1
Working with Data 10.1.2
Chart Dimensions 10.1.3
Category Axis 10.1.4
Numeric Axis 10.1.5
DateTime Axis 10.1.6
Logarithmic Axis 10.1.7
Axis Labels 10.1.8
Axis Customization 10.1.9
Stripline 10.1.10
2
Multiple Panes 10.1.11
Basic Chart 10.1.12
Polar & Radar 10.1.13
Financial Charts 10.1.14
Other Types 10.1.15
Multiple Series 10.1.16
Technical Indicators 10.1.17
Trendlines 10.1.18
Markers 10.1.19
Data Labels 10.1.20
Annotations 10.1.21
Legend 10.1.22
Tooltip 10.1.23
Zooming 10.1.24
Crosshair and Trackball 10.1.25
Selection 10.1.26
Print and Export 10.1.27
Appearance 10.1.28
Accessibility 10.1.29
Internationalization 10.1.30
Localization 10.1.31
Check Box 11.1
Getting Started 11.1.1
Label and Size 11.1.2
Accessibility 11.1.3
How To 11.1.4
Color Picker 12.1
Getting Started(ASP.NET MVC) 12.1.1
Mode And Value 12.1.2
Accessibility 12.1.3
How To 12.1.4
Context Menu 13.1
Getting Started 13.1.1
Icons and Navigation 13.1.2
3
Template and Multilevel nesting 13.1.3
Accessibility 13.1.4
How To 13.1.5
Datepicker 14.1
Getting Started 14.1.1
Date Range 14.1.2
Date Format 14.1.3
Globalization 14.1.4
Strict Mode 14.1.5
Customization 14.1.6
Start and Depth View 14.1.7
Accessibility 14.1.8
How To 14.1.9
Daterangepicker 15.1
Getting Started 15.1.1
Range Restriction 15.1.2
Globalization 15.1.3
Customization 15.1.4
Accessibility 15.1.5
How To 15.1.6
Dialog 16.1
Getting Started 16.1.1
Templates 16.1.2
Animation 16.1.3
Localization 16.1.4
Accessibility 16.1.5
How To 16.1.6
Document Editor 17.1
Getting Started(ASP.NET MVC) 17.1.1
Drop Down Button 18.1
Getting Started 18.1.1
Icons 18.1.2
Popup Items 18.1.3
Accessibility 18.1.4
4
How To 18.1.5
Grid 19.1
Getting Started(ASP.NET MVC) 19.1.1
Data Binding 19.1.2
Columns 19.1.3
Row 19.1.4
Cell 19.1.5
Editing 19.1.6
Sorting 19.1.7
Grouping 19.1.8
Filtering 19.1.9
Searching 19.1.10
Paging 19.1.11
Scrolling 19.1.12
Virtualization 19.1.13
Selection 19.1.14
Aggregates 19.1.15
Print 19.1.16
State Persistence 19.1.17
Toolbar 19.1.18
Pdf Export 19.1.19
Excel Export 19.1.20
Globalization 19.1.21
Accessibility 19.1.22
Clipboard 19.1.23
Context Menu 19.1.24
How To 19.1.25
Heatmap 20.1
Getting Started 20.1.1
Working With Data 20.1.2
Rendering Modes 20.1.3
Axis 20.1.4
Palette 20.1.5
Legend 20.1.6
5
Appearance 20.1.7
Dimensions 20.1.8
Tooltip 20.1.9
List View 21.1
Getting Started(ASP.NET MVC) 21.1.1
Data Binding 21.1.2
Grouping 21.1.3
Checklist 21.1.4
Nested List 21.1.5
Customizing Templates 21.1.6
Virtualization 21.1.7
Accessibility 21.1.8
Maskedtextbox 22.1
Getting Started 22.1.1
Mask Configuration 22.1.2
Accessibility 22.1.3
How To 22.1.4
Radio Button 23.1
Getting Started 23.1.1
Label and Size 23.1.2
How To 23.1.3
Range Navigator 24.1
Getting Started 24.1.1
Range 24.1.2
Lightweight 24.1.3
Series Type 24.1.4
Type of Data 24.1.5
Period Selector 24.1.6
Labels 24.1.7
Grid Lines and Tick Lines 24.1.8
Customization 24.1.9
Tooltip 24.1.10
RTL 24.1.11
Export and Print 24.1.12
6
Schedule 25.1
Getting Started 25.1.1
Appointments 25.1.2
Data binding 25.1.3
Editor customization 25.1.4
Timezone 25.1.5
Views 25.1.6
Resources 25.1.7
Readonly 25.1.8
Timescale 25.1.9
Header bar customization 25.1.10
Working days and hours 25.1.11
Globalization 25.1.12
Schedule dimensions 25.1.13
Customizations 25.1.14
Recurrence editor 25.1.15
Accessibility 25.1.16
How To 25.1.17
Sidebar 26.1
Getting Started 26.1.1
Target 26.1.2
Types 26.1.3
Auto Close 26.1.4
Dock 26.1.5
How To 26.1.6
Slider 27.1
Getting Started(ASP.NET MVC) 27.1.1
Ticks 27.1.2
Formatting 27.1.3
Limits 27.1.4
Accessibility 27.1.5
How-To 27.1.6
Split Button 28.1
Getting Started 28.1.1
7
Icons 28.1.2
Popup Items 28.1.3
Accessibility 28.1.4
How To 28.1.5
Switch 29.1
Getting Started 29.1.1
Accessibility 29.1.2
How To 29.1.3
Textbox 30.1
Getting Started 30.1.1
Groups 30.1.2
Sizing 30.1.3
Validation 30.1.4
How To 30.1.5
Timepicker 31.1
Getting Started 31.1.1
Time Range 31.1.2
Globalization 31.1.3
Strict Mode 31.1.4
Accessibility 31.1.5
How To 31.1.6
Toast 32.1
Getting Started(ASP.NET MVC) 32.1.1
Configuring options 32.1.2
Positioning 32.1.3
Action Buttons 32.1.4
TimeOut 32.1.5
Template 32.1.6
Animation 32.1.7
Accessibility 32.1.8
How to 32.1.9
Tooltip 33.1
Getting Started(ASP.NET MVC) 33.1.1
Setting Dimension 33.1.2
8
Content 33.1.3
Position 33.1.4
Open Mode 33.1.5
Animation 33.1.6
Customization 33.1.7
Uploader 34.1
Getting Started(ASP.NET MVC) 34.1.1
Asynchronous Upload 34.1.2
Chunk Upload 34.1.3
Drag and drop 34.1.4
Validation 34.1.5
Form Support 34.1.6
Template 34.1.7
Localization 34.1.8
Accessibility 34.1.9
How To 34.1.10
9
Essential JS 2 for ASP.NET MVC
Essential JS 2 for ASP.NET is a modern enterprise UI toolkit that has been the built from the
ground up to be lightweight, responsive, modular and touch friendly. It also available in other
frameworks such as JavaScript and Angular, React. This documentation is a common
documentation site for ASP.NET MVC wrappers for Essential JS 2.
Now that you are familiar with the basics of using the component, the next step would be to
start integrating the component into your application. A good starting point would be to refer
to the code snippets in the online sample browser which contains hundreds of code samples,
it is very likely that you will find a code sample that resembles your intended usage scenario.
Another valuable resource is the API reference which provides detailed information on the
object hierarchy as well as the settings available on every object.
Getting Help
If you are still not able to find the information that you are looking for in the self-help
resources mentioned above then please contact us by creating a support ticket in our
support site or ask your query. with tag syncfusion-ej2 .
10
Installation
The following specified location is the place where all the assemblies, scripts, CSS files, and
samples are available.
For example, If you have installed the Essential Studio package within C:\Program Files(x86),
then navigate to the following location, C:\Program Files (x86)\Syncfusion\Essential
Studio\16.1.0.24\
The ASP.NET MVC samples can be accessed from the following location.
For example, If you have installed the Essential Studio package within C:\Program Files(x86),
then navigate to the following location. C:\Program Files (x86)\Syncfusion\Essential
Studio\16.1.0.24\Samples
The Dashboard can be opened by running the Dashboard.exe file present within the following
location.
For example, If you have installed the Essential Studio package within C:\Program Files(x86),
navigate to the following location. C:\Program Files (x86)\Syncfusion\Essential
Studio\16.1.0.24\Infrastructure\Dashboard\4.0
To run the local samples from dashboard and other online samples, refer to the link here.
11
System Requirements
12
Getting Started
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
Prerequisites
To get start with ASP.NET MVC application, need to ensure the following software to be installed
on the machine.
13
Step 2: After creating an application. We need to add Syncfusion EJ2 package into your
application by using NuGet Package Manager.
14
Install the Syncfusion.EJ2.MVC4 package to the application
15
After Installation complete this will included in the project. You can refer it from the Project
Assembly Reference.
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>
<system.web>
<compilation>
<assemblies>
<add assembly="Syncfusion.EJ2, Culture=neutral" />
</assemblies>
</compilation>
</system.web>
Step 4: Add client side resource through CDN or local package in the layout page
Views/Shared/_Layout.cshtml .
<head>
@* Syncfusion Essential JS 2 Styles *@
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css" />
16
You can also install the NuGet package Syncfusion.EJ2.JavaScript which have the client-side
dependencies (Scripts and Styles) of the Essential JS 2 components.
Step 5: Add the Script Manager reference in the layout page Views/Shared/_Layout.cshtml . The
Script Manager need to be added after body rendered.
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Html.EJS().ScriptManager()
</body>
Step 6: Adding Syncfusion Essential JS 2 for ASP.Net MVC component in any page you want.
<div>
<h2> Essential JS 2 for ASP.NET MVC Calendar </h2>
@Html.EJS().Calendar("calendar").Render()
</div>
17
NuGet Packages for ASP.NET MVC
You can use the Syncfusion ASP.NET MVC NuGet packages without installing the
Essential Studio or ASP.NET MVC platform installation to implement the Syncfusion
ASP.NET MVC controls.
You should get the private Syncfusion ASP.NET MVC NuGet feed URL to install or upgrade the
Syncfusion ASP.NET MVC NuGet packages. To get the URL from Syncfusion website use the
following steps:
2. Navigate to WEB(Essential JS 2), click the Copy URL label under ASP.NET MVC platform
to copy the Syncfusion ASP.NET MVC platform NuGet feed to clipboard or directly use the
following URL:
http://nuget.syncfusion.com/nuget_aspnetmvc-js2/nuget/getsyncfusionpackages/aspnetmvc-
js2
3. Now, use this NuGet feed URL to access the Syncfusion NuGet Packages in Visual Studio.
Windows
1. Open your Visual Studio application.
4. Click the Add button (green plus), and enter the ‘Package Name’ and ‘Package Source URL’
of the Syncfusion ASP.NET MVC NuGet packages.
18
Source: Syncfusion ASP.NET MVC NuGet Feed URL
http://nuget.syncfusion.com/nuget_aspnetmvc-js2/nuget/getsyncfusionpackages/aspnetmvc-
js2.
5. Click the Update button to add the name and source details to package sources.
macOS
1. Open your Visual Studio application.
2. Right-click on the Packages folder in the project, and then select Add Packages…
3. Choose the Configure Sources… from the dropdown that appears in the left corner of the
Add Packages dialog.
4. At the bottom right corner of the dialog, click the Add button to enter the feed name and the
URL.
Name: Enter the name (For e.g., Syncfusion ASP.NET MVC Packages).
1. On the Tools, menu, NuGet Package Manager | Manage NuGet Packages for Solution...
Alternatively, right-click on the project/solution in Solution Explorer tab, and choose Manage
NuGet Packages…
2. By default, the NuGet.org package is selected in the Package source drop-down. Select
your appropriate feed name that you configured.
19
3. The Syncfusion ASP.NET MVC NuGet Packages are listed and available in the package
source feed URL. Search and install the required packages in your application, by clicking
Install button.
1. On the Tools menu, select NuGet Package Manager and then Package Manager
Console.
For example:
1. Right-click on the folder in the project, and then select Add Packages…
20
2. By default, the NuGet.org package is selected in the Package source drop-down. Select
the appropriate feed name.
3. The Syncfusion ASP.NET MVC NuGet Packages available in the package source location
will be listed. Search and install the required packages in your application, by clicking Add
Package button.
To update the existing nuget.exe to latest version use the following command:
2. Open the downloaded executable location in the command window, and run the following
commands to configure the Syncfusion ASP.NET MVC NuGet packages:
For example:
NuGet installation
21
Download and install the required NuGet packages to a project specified in the package.config .
#install specified package in default project from specified package source for Windows
Platform
nuget.exe install <Package name | ConfigFilePath > <Options>
#install specified package in default project from specified package source for MAC/Lin
ux Platform
mono nuget.exe install <Package name | ConfigFilePath > <Options>
configPath is optional. This identifies the package.config or solutions file that lists the
packages utilized in the project.
For example:
#install specific Syncfusion NuGet package with Syncfusion ASP.NET MVC NuGet feed for W
indows
nuget.exe install “Syncfusion.EJ2.MVC5” –Source “http://nuget.syncfusion.com/nuget_aspn
etmvc-js2/nuget/getsyncfusionpackages/aspnetmvc-js2”
#install all package which mention in package.config path for Mac and Linux
mono nuget.exe install “C:\Users\SyncfusionApplication\package.config”
#install specific Syncfusion NuGet package with Syncfusion ASP.NET MVC NuGet feed for M
ac and Linux
mono nuget.exe install “Syncfusion.EJ2.MVC5” –Source “http://nuget.syncfusion.com/nuget
_aspnetmvc-js2/nuget/getsyncfusionpackages/aspnetmvc-js2”
22
1. On the Tools menu, NuGet Package Manager | Manage NuGet Packages for Solution...
Alternatively, right-click on project/solution in the Solution Explorer tab, and choose Manage
NuGet Packages…
2. Select the Updates tab to see the packages available for update from the desired package
sources. Select the required packages and the specific version from the dropdown, and click
the Update button.
2. This will update the NuGet package to the latest version. You can double-click Add
packages and choose the specific version.
To update all the projects from solution, use update option in the solution level.
1. On the Tools menu, select NuGet Package Manager, and then Package Manager
Console.
For example:
23
Update-Package Syncfusion.EJ2.MVC5
To update the existing nuget.exe to latest version use the following command:
2. Open the downloaded executable location in the command window. Run the following
“update commands” to update the Syncfusion ASP.NET MVC NuGet packages.
configPath is optional. This identifies the package.config or solutions file lists the
packages utilized in the project.
For example:
Update command is not working as expected in Mono (Mac and Linux) and projects
using PackageReference format.
24
State Persistence
Essential JS 2 has support for persisting component’s state across page refreshes or navigation.
To enable this feature, set EnablePersistence property as true to the required component. This
will store the component’s state in browser’s localStorage object on page unload event. For
example, we have enabled persistence to grid component in the following code.
razor
@Html.EJS().Grid("check").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").
CrossDomain(true).Adaptor("ODataV4Adaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syn
cfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAl
ign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign
(Syncfusion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
})
.EnablePersistence()
.AllowPaging()
.PageSettings(page=>page.PageCount(5))
.Render()
25
Accessibility
All the Syncfusion Essential JS 2 components follows WAI-ARIA accessibility standard by
default. This enables you to build accessible web application which are fully navigable by user
with disabilities.
Keyboard Navigation
Keyboard navigation support enables users to interact with components using Keyboard
shortcuts. Each component has its own set of shortcuts, please refer the following documents to
get details for each component.
AutoComplete
Calendar
Combobox
DatePicker
Dialog
DropDownList
Grid
ListView
TimePicker
26
Browser Support
Syncfusion Essential JS 2 Component support modern browsers. This include the below
versions.
Windows
Chrome Firefox Opera Edge IE Safari IOS Android
Mobile
11
Latest Latest Latest 13 + 9+ 9+ 4.4 + IE 11 +
+
Required Polyfills
The below polyfills are required to run Essential JS 2 components in each browser.
Browser Polyfills
IE 11 ES6 Promise
27
Theming
THe Essential JS 2 has provided the below list of in-built themes those are,
1. Google’s Material
2. Microsoft Office’s Fabric
3. Bootstrap
4. High Contrast
Themes are shipped as individual and combined CSS files. Combined CSS file can be referred
from the npm package @syncfusion/ej2 and individual CSS files are available within same
component repository’s style folder. In ej2 npm packages, we have shipped both CSS and
SCSS files for all components.
@import "./node_modules/@syncfusion/ej2/<theme_name>.css";
@import "ej2/<theme_name>.scss";
@import "ej2-buttons/button/<theme_name>.scss";
@import "ej2/button/<theme_name>.scss";
28
Overview
Avatars are icons or figures representing a particular person, used in popular media formats like
images, SVG, font icons, and letters.
Key features
Types - Provided 2 types of Avatar.
Sizes - Supports different sizes to adapt the various application scenario.
29
Getting Started
This section briefly explains about how to render Avatar component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x , if you reference Syncfusion assemblies from trial setup or from
the NuGet feed, you also have to include a license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP .NET MVC application to
use our components.
<span class="e-avatar">GR</span>
After successful compilation of your application, simply press F5 to run the application.
razor
HomeController.cs
<div id='element'>
<span class="e-avatar e-avatar-xlarge"></span>
<span class="e-avatar e-avatar-large"></span>
<span class="e-avatar"></span>
<span class="e-avatar e-avatar-small"></span>
<span class="e-avatar e-avatar-xsmall"></span>
</div>
<style>
#element {
display: block;
width: 300px;
margin: 130px auto;
border-radius: 3px;
justify-content: center;
}
.e-avatar {
30
background-image: url(./pic01.png);
margin: 2px;
}
</style>
31
Types and Styles
This section explains different types of avatar.
Avatar size
The Essential JS 2 Avatar has the following predefined sizes that can be used with the .e-
avatar class to change the appearance of the avatar.
razor
HomeController.cs
<div id='element'>
<span class="e-avatar e-avatar-xlarge"></span>
<span class="e-avatar e-avatar-large"></span>
<span class="e-avatar"></span>
<span class="e-avatar e-avatar-small"></span>
<span class="e-avatar e-avatar-xsmall"></span>
</div>
<style>
#element {
display: block;
width: 300px;
margin: 100px auto;
border-radius: 3px;
}
.e-avatar {
background-image: url(./pic01.png);
}
</style>
32
Avatar types
The types of Essential JS 2 avatar are:
Default
Circle
Default
The default style of the avatar is rectangular shape with rounded corners, which can be applied
from adding the modifier class .e-avatar to the target element.
razor
HomeController.cs
<div id='element'>
<span class="e-avatar e-avatar-xlarge">RT</span>
<span class="e-avatar e-avatar-large">RT</span>
<span class="e-avatar">RT</span>
<span class="e-avatar e-avatar-small">RT</span>
<span class="e-avatar e-avatar-xsmall">RT</span>
</div>
<style>
#element {
display: block;
width: 260px;
margin: 100px auto;
border-radius: 3px;
}
</style>
Circle
The circle avatar style can be applied by adding the modifier class .e-avatar-circle to the
target element.
razor
HomeController.cs
<div id='element'>
<span class="e-avatar e-avatar-xlarge e-avatar-circle">SJ</span>
<span class="e-avatar e-avatar-large e-avatar-circle">SJ</span>
33
<span class="e-avatar e-avatar-circle">SJ</span>
<span class="e-avatar e-avatar-small e-avatar-circle">SJ</span>
<span class="e-avatar e-avatar-xsmall e-avatar-circle">SJ</span>
</div>
<style>
#element {
display: block;
width: 300px;
margin: 100px auto;
border-radius: 3px;
}
</style>
34
How To
As the avatar is a completely customizable and integral component, this section shows some of
the customization and integration of avatar with other components.
Customize avatars
Colour customization
The avatar comes with default background colour (grey). This can be easily customized to
desired colour by adding custom class or directly selecting the avatar class from the CSS.
razor
HomeController.cs
<div id='element'>
<span class="e-avatar e-avatar-xlarge e-avatar-circle green">AJ</span>
<span class="e-avatar e-avatar-xlarge e-avatar-circle violet">JK</span>
<span class="e-avatar e-avatar-xlarge e-avatar-circle rose">EL</span>
<span class="e-avatar e-avatar-xlarge e-avatar-circle blue">SR</span>
<span class="e-avatar e-avatar-xlarge e-avatar-circle red">PD</span>
</div>
<style>
#element {
display: flex;
width: 400px;
margin: 100px auto;
border-radius: 3px;
justify-content: center;
}
.e-avatar {
margin: 2px;
}
.e-avatar.green {
background-color: #87eb87;
}
.e-avatar.violet {
background-color: #ee82ee;
}
.e-avatar.blue {
35
background-color: #7171e4;
}
.e-avatar.red {
background-color: #d86e6e;
}
.e-avatar.rose {
background-color: #bc8f8f;
}
</style>
razor
HomeController.cs
<div id='element'>
<span class="e-avatar">26px</span>
<span class="e-avatar">24px</span>
<span class="e-avatar">22px</span>
<span class="e-avatar">20px</span>
<span class="e-avatar">18px</span>
</div>
<style>
#element {
display: block;
width: 400px;
margin: 100px auto;
border-radius: 3px;
}
#element :nth-child(5) {
font-size: 18px;
}
#element :nth-child(4) {
font-size: 20px;
36
}
#element :nth-child(3) {
font-size: 22px;
}
#element :nth-child(2) {
font-size: 24px;
}
#element :nth-child(1) {
font-size: 26px;
}
</style>
razor
HomeController.cs
<div class="avatar-block">
<!-- Card Component -->
<div class="e-card e-avatar-showcase">
<div class="e-card-content">
<!-- XLarge Circle Avatar Component -->
<div class="e-avatar e-avatar-xlarge e-avatar-circle">
<div class="svg_icons chrome"></div>
37
</div>
</div>
<div class="e-card-content">
<div>SVG</div>
</div>
</div>
</div>
<div class="avatar-block">
<!-- Card Component -->
<div class="e-card e-avatar-showcase">
<div class="e-card-content">
<!-- XLarge Circle Avatar Component -->
<div class="e-avatar e-avatar-xlarge e-avatar-circle">GR</div>
</div>
<div class="e-card-content">
<div>Initial</div>
</div>
</div>
</div>
<div class="avatar-block">
<!-- Card Component -->
<div class="e-card e-avatar-showcase">
<div class="e-card-content">
<!-- XLarge Circle Avatar Component -->
<div class="e-avatar e-avatar-xlarge e-avatar-circle">
<div class="e-people icons"></div>
</div>
</div>
<div class="e-card-content">
<div>FontIcon</div>
</div>
</div>
</div>
<div class="avatar-block">
<!-- Card Component -->
<div class="e-card e-avatar-showcase">
<div class="e-card-content">
<!-- XLarge Circle Avatar Component -->
<div class="e-avatar e-avatar-xlarge e-avatar-circle">User</div>
</div>
<div class="e-card-content">
<div>Word</div>
</div>
</div>
</div>
38
<div class="avatar-block">
<!-- Card Component -->
<div class="e-card e-avatar-showcase">
<div class="e-card-content">
<!-- XLarge Circle Avatar Component -->
<div class="e-avatar e-avatar-xlarge e-avatar-circle custom">
<div class="e-people icons"></div>
</div>
</div>
<div class="e-card-content">
<div>Custom</div>
</div>
</div>
</div>
</div>
<style>
/* Media Quries for various devices */
.sample_container.avatar-types .avatar-block {
display: inline-block;
vertical-align: top;
}
.e-avatar.image {
39
background-image: url(./pic01.png);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
/* SVG Icons */
.chrome {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/200
0/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%23ffffff' d='M16.033 11.049a5.155 5.155 0 1
1 0 10.312 5.156 5.156 0 0 1 0-10.312zM16.124 0c1.281-.003 9.659.318 14.268 9.043h-.01
6l.01.018c.33.578 3.745 6.94-.485 14.969 0 0-4.215 8.107-14.565 7.968l-.452-.012-.004.0
07-.004.007.02-.037c.564-.98 5.112-8.884 6.357-11.067l.016-.028.007-.008.04-.069.11-.12
7a7.085 7.085 0 0 0 1.457-2.967l.01-.046.035-.151c.088-.424.148-.944.128-1.549l-.006-.1
17v-.004l-.007-.143-.006-.07-.005-.079-.012-.116v-.01l-.001-.008-.016-.158a7.2 7.2 0 0
0-.096-.572l-.018-.081-.013-.064a9.801 9.801 0 0 0-.692-2.016c-.165-.243-.332-.489-.512
-.733l-.142-.187 8.728-2.554s-10.538-.01-13.018-.001l.021.005H16.642l-.14-.013a7.034 7.
034 0 0 0-1.132-.003l-.167.016h-.047l-.034-.001c-.193.002-1.213.045-2.492.764l-.005.003
-.033.016a7.158 7.158 0 0 0-3.25 3.533l-.059.148-6.485-6.404s4.74 8.311 6.165 10.779l.0
65.113.023.088a7.14 7.14 0 0 0 7.777 5.118l.144-.02L14.854 32h-.027c-.667-.005-7.894-.2
34-12.744-7.906 0 0-4.925-7.698.37-16.573l.252-.411.001-.002C2.822 6.904 6.58.374 15.95
8.003c0 0 .057-.003.166-.003z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.svg_icons {
width: 32px;
height: 32px;
display: inline-block;
}
/* Card Customization */
.e-avatar-showcase.e-card {
height: 113px;
padding: 5px;
margin: 5px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
border-radius: 8px;
}
40
color: rgba(0, 0, 0, 0.75);
white-space: pre-line;
font-size: 14px;
text-shadow: #eaeaea 1px 1px 2px;
}
.e-avatar-showcase.e-card .e-card-content {
align-self: center;
padding: 10px 0 10px 0;
overflow: visible;
}
/* Font Icons */
@font-face {
font-family: 'Contacts';
src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMj0gS
RgAAAEoAAAAVmNtYXDnEOdaAAABjAAAADhnbHlmiAnWagAAAcwAAADwaGVhZBD04psAAADQAAAANmhoZWEHiwNu
AAAArAAAACRobXR4C9AAAAAAAYAAAAAMbG9jYQAwAHgAAAHEAAAACG1heHABDwA1AAABCAAAACBuYW1lby+ImAA
AArwAAAIxcG9zdGUbI4AAAATwAAAAOwABAAADUv9qAFoEAAAAAAAD3QABAAAAAAAAAAAAAAAAAAAAAwABAAAAAQ
AAWW9ja18PPPUACwPoAAAAANb8zuYAAAAA1vzO5gAAAAAD3QPqAAAACAACAAAAAAAAAAEAAAADACkAAgAAAAAAA
gAAAAoACgAAAP8AAAAAAAAAAQPwAZAABQAAAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAUGZFZABA5wDnAQNS/2oAWgPqAJYAAAABAAAAAAAABAAAAAPoAAAD6AAAAAAAAgAAAAMAAAAUAAM
AAQAAABQABAAkAAAABAAEAAEAAOcB//8AAOcA//8AAAABAAQAAAABAAIAAAAAADAAeAACAAAAAAO+A+oADQAZAA
A3FBYXIT4BNS4BJyEOARMeARc+ATcuAScOAS4YFwMzFxgDq4H+zYGr4QOCY2KCAwOCYmGCnCtOISFOK3qiAwOiA
e1igwICg2JjggICggAAAAACAAAAAAPdA+oAFAAoAAABDgEHIicjDgEHLgEnLgEnPgE3HgEFFBYfARYfATcXFhc2
JDcmJCcGBAOkBfK3KioXEFcpBBEMRUsBBfK3tvL8cVRLDggBBsQKLDDPARMFBf7tz87+7QI+ndEEBwI/Izh2DS+
RVZ3RBATRnWCmN3BIETecAgcBBPK1tfIEBPIAAAAAABIA3gABAAAAAAAAAAEAAAABAAAAAAABAAgAAQABAAAAAA
ACAAcACQABAAAAAAADAAgAEAABAAAAAAAEAAgAGAABAAAAAAAFAAsAIAABAAAAAAAGAAgAKwABAAAAAAAKACwAM
wABAAAAAAALABIAXwADAAEECQAAAAIAcQADAAEECQABABAAcwADAAEECQACAA4AgwADAAEECQADABAAkQADAAEE
CQAEABAAoQADAAEECQAFABYAsQADAAEECQAGABAAxwADAAEECQAKAFgA1wADAAEECQALACQBLyBDb250YWN0c1J
lZ3VsYXJDb250YWN0c0NvbnRhY3RzVmVyc2lvbiAxLjBDb250YWN0c0ZvbnQgZ2VuZXJhdGVkIHVzaW5nIFN5bm
NmdXNpb24gTWV0cm8gU3R1ZGlvd3d3LnN5bmNmdXNpb24uY29tACAAQwBvAG4AdABhAGMAdABzAFIAZQBnAHUAb
ABhAHIAQwBvAG4AdABhAGMAdABzAEMAbwBuAHQAYQBjAHQAcwBWAGUAcgBzAGkAbwBuACAAMQAuADAAQwBvAG4A
dABhAGMAdABzAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAHUAcwBpAG4AZwAgAFMAeQBuAGMAZgB1AHM
AaQBvAG4AIABNAGUAdAByAG8AIABTAHQAdQBkAGkAbwB3AHcAdwAuAHMAeQBuAGMAZgB1AHMAaQBvAG4ALgBjAG
8AbQAAAAACAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBAgEDAQQABHVzZXIKY2hhdC0wMS13ZgAAA
A==) format('truetype');
font-weight: normal;
font-style: normal;
}
41
.people,
.e-people {
font-family: 'Contacts';
}
.e-people:before {
content: '\e700';
}
.e-avatar .e-people.icons {
font-size: 24px;
}
.e-avatar.custom {
background-color: blueviolet;
}
</style>
Integrate avatars
Avatar can be integrated into various components to make a wide variety of applications. Some
of the integrations are shown in the following section.
Listview
Avatar is integrated into the listview to create contacts applications. The xsmall size avatar is
used to match the size of the list item. Letters and images are also used as avatar content.
razor
HomeController.cs
@section ControlsSection{
<div class="col-lg-12 control-section">
<div class="sample_container">
<!-- Listview element -->
@{ var template = "<div class='listWrapper'>" +
"${if(avatar!=='')}" +
"<span class='e-avatar e-avatar-small e-avatar-circle'>${avatar}</span>"
+
42
"${else}" +
"<span class='${pic} e-avatar e-avatar-small e-avatar-circle'> </span>"
+
"${/if}" +
"<span class='text'>" +
"${text} </span> </div>";}
@Html.EJS().ListView("letterAvatarList").Enable(true).DataSource((IEnumerab
le<object>)ViewBag.dataSource).HeaderTitle("Contacts").ShowHeader(true).Template(templa
te).SortOrder(Syncfusion.EJ2.ListView.SortOrder.Ascending).Render()
</div>
</div>
}
<style>
.control-section {
overflow: auto;
}
/* Listview Customization */
#letterAvatarList {
max-width: 350px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
#letterAvatarList .listWrapper {
width: inherit;
height: inherit;
position: relative;
}
#letterAvatarList .e-list-header {
height: 54px;
}
43
.highcontrast #letterAvatarList .e-list-header .e-text {
line-height: 20px;
}
#letterAvatarList .e-list-item {
cursor: pointer;
height: 50px;
line-height: 44px;
border: 0;
}
/* Badge Positioning */
#letterAvatarList .e-badge {
margin-top: 12px;
}
/* Avatar Positioning */
44
.pic01 {
background-image: url('../../Content/avatar/images/pic01.png');
}
.pic02 {
background-image: url('../../Content/avatar/images/pic02.png');
}
.pic03 {
background-image: url('../../Content/avatar/images/pic03.png');
}
.pic04 {
background-image: url('../../Content/avatar/images/pic04.png');
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EJ2MVCSampleBrowser.Controllers.Avatar
{
public partial class AvatarController : Controller
{
public ActionResult Listview()
{
List<object> data = new List<object>();
data.Add(new { text = "Robert", id = "s_01", avatar= "", pic= "pic04" });
data.Add(new { text = "Nancy", id = "s_02", avatar= "N", pic= "" });
data.Add(new { text = "John", id = "s_03", pic= "pic01", avatar= "" });
data.Add(new { text = "Andrew", id = "s_04", avatar= "A", pic= "" });
data.Add(new { text = "Michael", id = "s_05", pic= "pic02", avatar= "" });
data.Add(new { text = "Steven", id = "s_06", pic= "pic03", avatar= "" });
data.Add(new { text = "Margaret", id = "s_07", avatar= "M", pic= "" });
ViewBag.dataSource = data;
return View();
}
}
45
Overview
Badges can be used to alert users about new or unread messages, notifications, and additional
information to the content. This can be used in conjunction with lists to represent each list’s
timeline such as ‘new’, ‘old’, and ‘preview’.
Key features
Types - Provided 8 different types of Badges.
46
Getting Started
This section briefly explains about how to render Badge component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x , if you reference Syncfusion assemblies from trial setup or from
the NuGet feed, you also have to include a license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP .NET MVC application to
use our components.
After successful compilation of your application, simply press F5 to run the application.
razor
HomeController.cs
<div id='element'>
<h1>Badge Component <span class="e-badge e-badge-primary">New</span></h1>
</div>
<style>
#element {
display: flex;
width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
}
</style>
47
}
48
Types and Styles
This section explains different styles and types of the badges.
Badge styles
The Essential JS 2 Badge has the following predefined styles that can be used with .e-badge
class to change the appearance of a badge.
razor
HomeController.cs
<div id='element'>
<div class="sample_container">
<div class="block" style="display:inline-block">
<div class="e-card e-badge-showcase">
<div class="e-card-content">
<div>
<span class="e-badge e-badge-primary">Primary</span>
</div>
</div>
<div class="e-card-content">
<div>
<code>.e-badge-primary</code>
</div>
</div>
</div>
</div>
49
<div class="e-card-content">
<span class="e-badge e-badge-secondary">Secondary</span>
</div>
<div class="e-card-content">
<code>.e-badge-secondary</code>
</div>
</div>
</div>
50
</div>
</div>
</div>
<Style>
#element {
width: 100%;
margin: auto;
}
.sample_container {
width: 800px;
margin: auto;
}
.block {
margin: 10px 10px 10px 10px;
vertical-align: top;
}
.e-badge-showcase.e-card {
width: 150px;
height: 90px;
padding: 5px;
margin: 5px;
51
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
border-radius: 8px;
}
.e-badge-showcase.e-card .e-card-content {
align-self: center;
padding: 0 0 10px 0;
}
</Style>
Badge types
The types of Essential JS 2 badges are as follows:
Circle
Pill
Link
Notification
52
Overlap
Dot
Position
Circle
The circle badge style can be applied by adding the modifier class .e-badge-circle to the
target element.
razor
HomeController.cs
<div id='element'>
<div style="position:relative;display:inline-block;margin:20px 20px 10px 20px;">
<div class="skype svg_icons"></div>
<span class="e-badge e-badge-success e-badge-overlap e-badge-notification e-bad
ge-circle">18</span>
</div>
53
}
.facebook {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%233c5a99;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M22.53,8.7h2.58V4.64H21.24a5.25,5.25,0,0,0-4,2s-1.06,
1-1.08,3.92h0v3H12.36v4.31h3.82V29h4.41V17.86h3.8l.53-4.31H20.59v-3h0A1.78,1.78,0,0,1,2
2.53,8.7Z'/%3e%3c/svg%3e");
}
.skype {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%2331c4ed;%7d.cls-2%7bfill:%23fff;fill-rule:evenodd;%7d%3c/style%3e%3c/
defs%3e%3ctitle%3eIcon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='
28' rx='5.75' ry='5.75'/%3e%3cpath class='cls-2' d='M19.5,19.14a4,4,0,0,1-1.75,1.31,7.2
2,7.22,0,0,1-2.68.46A6.6,6.6,0,0,1,12,20.27,4,4,0,0,1,10.58,19,2.71,2.71,0,0,1,10,17.51
a1.05,1.05,0,0,1,.36-.8,1.28,1.28,0,0,1,.9-.33,1.14,1.14,0,0,1,.75.26,1.89,1.89,0,0,1,.
51.73,4.54,4.54,0,0,0,.49.86,2,2,0,0,0,.72.55A3.08,3.08,0,0,0,15,19a3,3,0,0,0,1.73-.45,
1.23,1.23,0,0,0,.63-1.06,1,1,0,0,0-.33-.8,2.3,2.3,0,0,0-.92-.49c-.39-.12-.92-.26-1.57-.
39a12.2,12.2,0,0,1-2.25-.67,3.64,3.64,0,0,1-1.48-1.06,2.47,2.47,0,0,1-.29-.47,2.84,2.84
,0,0,1-.26-1.22,2.71,2.71,0,0,1,.58-1.72,3.71,3.71,0,0,1,1.67-1.14A7.37,7.37,0,0,1,15,9
.14a7,7,0,0,1,2,.26,4.38,4.38,0,0,1,1.42.7,3.1,3.1,0,0,1,.84.92,2.11,2.11,0,0,1,.26,1,1
.13,1.13,0,0,1-.35.82,1.18,1.18,0,0,1-.88.36,1.09,1.09,0,0,1-.74-.23,2.68,2.68,0,0,1-.5
1-.67,3,3,0,0,0-.77-.94A2.42,2.42,0,0,0,14.87,11a2.76,2.76,0,0,0-1.49.36,1,1,0,0,0-.53.
81.78.78,0,0,0,.17.5,1.63,1.63,0,0,0,.52.38,4.48,4.48,0,0,0,.69.27l.15,0,1,.24c.69.15,1
.33.32,1.89.49a6.29,6.29,0,0,1,1.47.67,2.81,2.81,0,0,1,1,1,3,3,0,0,1,.35,1.49,3.15,3.15
,0,0,1-.6,1.89Zm4-2.23a7.73,7.73,0,0,0,.2-1.81c0-.22,0-.43,0-.64a8.53,8.53,0,0,0-8.56-7
.83,8.72,8.72,0,0,0-1.46.12A5.08,5.08,0,0,0,11,6a5,5,0,0,0-5,4.91,4.83,4.83,0,0,0,.68,2
.48,7.33,7.33,0,0,0-.13.94,6.51,6.51,0,0,0,0,.77,8.52,8.52,0,0,0,8.58,8.46,8.9,8.9,0,0,
0,1.57-.14A5.09,5.09,0,0,0,19,24a4.94,4.94,0,0,0,5-4.91,4.86,4.86,0,0,0-.52-2.18Z'/%3e%
3c/svg%3e");
}
.twitter {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
54
.firefox {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.svg_icons {
width: 32px;
height: 32px;
display: inline-block;
}
</style>
Pill
The pill badge style can be applied by adding the modifier class .e-badge-pill to the target
element.
razor
HomeController.cs
<div id='element'>
<h1>Badge Component <span class="e-badge e-badge-primary e-badge-pill">New</span></
h1>
</div>
55
Link
When badge modifier classes are applied to the anchor tag, the badge’s appearance will change
from normal state to hover state on mouseover.
razor
HomeController.cs
<div id='element'>
<div style="display: inline-block; margin-top: 15px;">
<a href="#" class="e-badge e-badge-primary">Link Badge</a>
</div>
</div>
<style>
#element {
display: flex;
width: 400px;
height: 50px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
</style>
Notification
The notification badge style can be applied by adding the modifier class .e-badge-notification
to the target element. Notification badges are used when a content or a context needs special
attention. While using the notification badge, set the parent element to position: relative .
razor
HomeController.cs
<div id='element'>
<div style="position:relative;display:inline-block;margin:20px 20px 10px 20px;">
56
<div class="skype svg_icons"></div>
<span class="e-badge e-badge-success e-badge-overlap e-badge-notification">99+<
/span>
</div>
<Style>
#element {
display: flex;
width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
.facebook {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%233c5a99;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M22.53,8.7h2.58V4.64H21.24a5.25,5.25,0,0,0-4,2s-1.06,
1-1.08,3.92h0v3H12.36v4.31h3.82V29h4.41V17.86h3.8l.53-4.31H20.59v-3h0A1.78,1.78,0,0,1,2
2.53,8.7Z'/%3e%3c/svg%3e");
}
.skype {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
57
3e.cls-1%7bfill:%2331c4ed;%7d.cls-2%7bfill:%23fff;fill-rule:evenodd;%7d%3c/style%3e%3c/
defs%3e%3ctitle%3eIcon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='
28' rx='5.75' ry='5.75'/%3e%3cpath class='cls-2' d='M19.5,19.14a4,4,0,0,1-1.75,1.31,7.2
2,7.22,0,0,1-2.68.46A6.6,6.6,0,0,1,12,20.27,4,4,0,0,1,10.58,19,2.71,2.71,0,0,1,10,17.51
a1.05,1.05,0,0,1,.36-.8,1.28,1.28,0,0,1,.9-.33,1.14,1.14,0,0,1,.75.26,1.89,1.89,0,0,1,.
51.73,4.54,4.54,0,0,0,.49.86,2,2,0,0,0,.72.55A3.08,3.08,0,0,0,15,19a3,3,0,0,0,1.73-.45,
1.23,1.23,0,0,0,.63-1.06,1,1,0,0,0-.33-.8,2.3,2.3,0,0,0-.92-.49c-.39-.12-.92-.26-1.57-.
39a12.2,12.2,0,0,1-2.25-.67,3.64,3.64,0,0,1-1.48-1.06,2.47,2.47,0,0,1-.29-.47,2.84,2.84
,0,0,1-.26-1.22,2.71,2.71,0,0,1,.58-1.72,3.71,3.71,0,0,1,1.67-1.14A7.37,7.37,0,0,1,15,9
.14a7,7,0,0,1,2,.26,4.38,4.38,0,0,1,1.42.7,3.1,3.1,0,0,1,.84.92,2.11,2.11,0,0,1,.26,1,1
.13,1.13,0,0,1-.35.82,1.18,1.18,0,0,1-.88.36,1.09,1.09,0,0,1-.74-.23,2.68,2.68,0,0,1-.5
1-.67,3,3,0,0,0-.77-.94A2.42,2.42,0,0,0,14.87,11a2.76,2.76,0,0,0-1.49.36,1,1,0,0,0-.53.
81.78.78,0,0,0,.17.5,1.63,1.63,0,0,0,.52.38,4.48,4.48,0,0,0,.69.27l.15,0,1,.24c.69.15,1
.33.32,1.89.49a6.29,6.29,0,0,1,1.47.67,2.81,2.81,0,0,1,1,1,3,3,0,0,1,.35,1.49,3.15,3.15
,0,0,1-.6,1.89Zm4-2.23a7.73,7.73,0,0,0,.2-1.81c0-.22,0-.43,0-.64a8.53,8.53,0,0,0-8.56-7
.83,8.72,8.72,0,0,0-1.46.12A5.08,5.08,0,0,0,11,6a5,5,0,0,0-5,4.91,4.83,4.83,0,0,0,.68,2
.48,7.33,7.33,0,0,0-.13.94,6.51,6.51,0,0,0,0,.77,8.52,8.52,0,0,0,8.58,8.46,8.9,8.9,0,0,
0,1.57-.14A5.09,5.09,0,0,0,19,24a4.94,4.94,0,0,0,5-4.91,4.86,4.86,0,0,0-.52-2.18Z'/%3e%
3c/svg%3e");
}
.twitter {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.firefox {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.svg_icons {
width: 32px;
58
height: 32px;
display: inline-block;
}
</Style>
Dot
Dot can be applied by adding the modifier class .e-badge-dot to the target element. Dot badges
are similar to notification badges, but in a minimalistic way. While using the dot badge, set the
parent element to position: relative .
razor
HomeController.cs
<div id='element'>
<div style="position:relative;display:inline-block;margin:20px 20px 10px 20px;">
<div class="skype svg_icons"></div>
<span class="e-badge e-badge-success e-badge-overlap e-badge-dot"></span>
</div>
<style>
#element {
display: flex;
width: 400px;
59
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
.facebook {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%233c5a99;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M22.53,8.7h2.58V4.64H21.24a5.25,5.25,0,0,0-4,2s-1.06,
1-1.08,3.92h0v3H12.36v4.31h3.82V29h4.41V17.86h3.8l.53-4.31H20.59v-3h0A1.78,1.78,0,0,1,2
2.53,8.7Z'/%3e%3c/svg%3e");
}
.skype {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%2331c4ed;%7d.cls-2%7bfill:%23fff;fill-rule:evenodd;%7d%3c/style%3e%3c/
defs%3e%3ctitle%3eIcon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='
28' rx='5.75' ry='5.75'/%3e%3cpath class='cls-2' d='M19.5,19.14a4,4,0,0,1-1.75,1.31,7.2
2,7.22,0,0,1-2.68.46A6.6,6.6,0,0,1,12,20.27,4,4,0,0,1,10.58,19,2.71,2.71,0,0,1,10,17.51
a1.05,1.05,0,0,1,.36-.8,1.28,1.28,0,0,1,.9-.33,1.14,1.14,0,0,1,.75.26,1.89,1.89,0,0,1,.
51.73,4.54,4.54,0,0,0,.49.86,2,2,0,0,0,.72.55A3.08,3.08,0,0,0,15,19a3,3,0,0,0,1.73-.45,
1.23,1.23,0,0,0,.63-1.06,1,1,0,0,0-.33-.8,2.3,2.3,0,0,0-.92-.49c-.39-.12-.92-.26-1.57-.
39a12.2,12.2,0,0,1-2.25-.67,3.64,3.64,0,0,1-1.48-1.06,2.47,2.47,0,0,1-.29-.47,2.84,2.84
,0,0,1-.26-1.22,2.71,2.71,0,0,1,.58-1.72,3.71,3.71,0,0,1,1.67-1.14A7.37,7.37,0,0,1,15,9
.14a7,7,0,0,1,2,.26,4.38,4.38,0,0,1,1.42.7,3.1,3.1,0,0,1,.84.92,2.11,2.11,0,0,1,.26,1,1
.13,1.13,0,0,1-.35.82,1.18,1.18,0,0,1-.88.36,1.09,1.09,0,0,1-.74-.23,2.68,2.68,0,0,1-.5
1-.67,3,3,0,0,0-.77-.94A2.42,2.42,0,0,0,14.87,11a2.76,2.76,0,0,0-1.49.36,1,1,0,0,0-.53.
81.78.78,0,0,0,.17.5,1.63,1.63,0,0,0,.52.38,4.48,4.48,0,0,0,.69.27l.15,0,1,.24c.69.15,1
.33.32,1.89.49a6.29,6.29,0,0,1,1.47.67,2.81,2.81,0,0,1,1,1,3,3,0,0,1,.35,1.49,3.15,3.15
,0,0,1-.6,1.89Zm4-2.23a7.73,7.73,0,0,0,.2-1.81c0-.22,0-.43,0-.64a8.53,8.53,0,0,0-8.56-7
.83,8.72,8.72,0,0,0-1.46.12A5.08,5.08,0,0,0,11,6a5,5,0,0,0-5,4.91,4.83,4.83,0,0,0,.68,2
.48,7.33,7.33,0,0,0-.13.94,6.51,6.51,0,0,0,0,.77,8.52,8.52,0,0,0,8.58,8.46,8.9,8.9,0,0,
0,1.57-.14A5.09,5.09,0,0,0,19,24a4.94,4.94,0,0,0,5-4.91,4.86,4.86,0,0,0-.52-2.18Z'/%3e%
3c/svg%3e");
}
.twitter {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
60
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.firefox {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.svg_icons {
width: 32px;
height: 32px;
display: inline-block;
}
.svg_icons + .e-badge.e-badge-overlap {
transform: translateX(-100%);
}
</style>
Overlap
The overlap badge can be used with notification or dot badge, which overlaps with the
target element by adding the modifier class .e-badge-overlap . While using the overlap badge,
set the parent element to position: relative .
razor
HomeController.cs
<div id='element'>
61
<div style="position:relative;display:inline-block;margin:20px 20px 10px 20px;">
<div class="skype svg_icons"></div>
<span class="e-badge e-badge-success e-badge-overlap e-badge-notification">99+<
/span>
</div>
<Style>
#element {
display: flex;
width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
.facebook {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%233c5a99;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M22.53,8.7h2.58V4.64H21.24a5.25,5.25,0,0,0-4,2s-1.06,
1-1.08,3.92h0v3H12.36v4.31h3.82V29h4.41V17.86h3.8l.53-4.31H20.59v-3h0A1.78,1.78,0,0,1,2
2.53,8.7Z'/%3e%3c/svg%3e");
}
.skype {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
62
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%2331c4ed;%7d.cls-2%7bfill:%23fff;fill-rule:evenodd;%7d%3c/style%3e%3c/
defs%3e%3ctitle%3eIcon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='
28' rx='5.75' ry='5.75'/%3e%3cpath class='cls-2' d='M19.5,19.14a4,4,0,0,1-1.75,1.31,7.2
2,7.22,0,0,1-2.68.46A6.6,6.6,0,0,1,12,20.27,4,4,0,0,1,10.58,19,2.71,2.71,0,0,1,10,17.51
a1.05,1.05,0,0,1,.36-.8,1.28,1.28,0,0,1,.9-.33,1.14,1.14,0,0,1,.75.26,1.89,1.89,0,0,1,.
51.73,4.54,4.54,0,0,0,.49.86,2,2,0,0,0,.72.55A3.08,3.08,0,0,0,15,19a3,3,0,0,0,1.73-.45,
1.23,1.23,0,0,0,.63-1.06,1,1,0,0,0-.33-.8,2.3,2.3,0,0,0-.92-.49c-.39-.12-.92-.26-1.57-.
39a12.2,12.2,0,0,1-2.25-.67,3.64,3.64,0,0,1-1.48-1.06,2.47,2.47,0,0,1-.29-.47,2.84,2.84
,0,0,1-.26-1.22,2.71,2.71,0,0,1,.58-1.72,3.71,3.71,0,0,1,1.67-1.14A7.37,7.37,0,0,1,15,9
.14a7,7,0,0,1,2,.26,4.38,4.38,0,0,1,1.42.7,3.1,3.1,0,0,1,.84.92,2.11,2.11,0,0,1,.26,1,1
.13,1.13,0,0,1-.35.82,1.18,1.18,0,0,1-.88.36,1.09,1.09,0,0,1-.74-.23,2.68,2.68,0,0,1-.5
1-.67,3,3,0,0,0-.77-.94A2.42,2.42,0,0,0,14.87,11a2.76,2.76,0,0,0-1.49.36,1,1,0,0,0-.53.
81.78.78,0,0,0,.17.5,1.63,1.63,0,0,0,.52.38,4.48,4.48,0,0,0,.69.27l.15,0,1,.24c.69.15,1
.33.32,1.89.49a6.29,6.29,0,0,1,1.47.67,2.81,2.81,0,0,1,1,1,3,3,0,0,1,.35,1.49,3.15,3.15
,0,0,1-.6,1.89Zm4-2.23a7.73,7.73,0,0,0,.2-1.81c0-.22,0-.43,0-.64a8.53,8.53,0,0,0-8.56-7
.83,8.72,8.72,0,0,0-1.46.12A5.08,5.08,0,0,0,11,6a5,5,0,0,0-5,4.91,4.83,4.83,0,0,0,.68,2
.48,7.33,7.33,0,0,0-.13.94,6.51,6.51,0,0,0,0,.77,8.52,8.52,0,0,0,8.58,8.46,8.9,8.9,0,0,
0,1.57-.14A5.09,5.09,0,0,0,19,24a4.94,4.94,0,0,0,5-4.91,4.86,4.86,0,0,0-.52-2.18Z'/%3e%
3c/svg%3e");
}
.twitter {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.firefox {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.svg_icons {
63
width: 32px;
height: 32px;
display: inline-block;
}
</Style>
Position
The default position of the notification or dot badge is top. But, the position can be changed
to bottom using the modifier class .e-badge-bottom . For example, the bottom class modifier is
used with dot badge to display the status in the avatar as shown in the following sample.
razor
HomeController.cs
<div id='element'>
<div class="badge-block">
<div class="contact svg_icons"></div>
<!-- Success Colored Bottom Dot Badge -->
<span class="e-badge e-badge-success e-badge-overlap e-badge-dot e-badge-bottom"
></span>
</div>
<div class="badge-block">
<div class="skype svg_icons"></div>
<!-- Info Colored Bottom Dot Badge -->
<span class="e-badge e-badge-info e-badge-overlap e-badge-dot e-badge-bottom"><
/span>
</div>
<div class="badge-block">
<div class="facebook svg_icons"></div>
<!-- Info Colored Dot Badge -->
<span class="e-badge e-badge-info e-badge-overlap e-badge-dot"></span>
</div>
<div class="badge-block">
<div class="pinterest svg_icons"></div>
<!-- Danger Colored Dot Badge -->
<span class="e-badge e-badge-danger e-badge-overlap e-badge-dot"></span>
64
</div>
</div>
<style>
#element {
display: flex;
width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
.badge-block {
position: relative;
display: inline-block;
margin: 10px 13px 10px 10px;
}
/* SVG Icons */
.facebook {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%233c5a99;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M22.53,8.7h2.58V4.64H21.24a5.25,5.25,0,0,0-4,2s-1.06,
1-1.08,3.92h0v3H12.36v4.31h3.82V29h4.41V17.86h3.8l.53-4.31H20.59v-3h0A1.78,1.78,0,0,1,2
2.53,8.7Z'/%3e%3c/svg%3e");
}
.skype {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%2331c4ed;%7d.cls-2%7bfill:%23fff;fill-rule:evenodd;%7d%3c/style%3e%3c/
defs%3e%3ctitle%3eIcon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='
28' rx='5.75' ry='5.75'/%3e%3cpath class='cls-2' d='M19.5,19.14a4,4,0,0,1-1.75,1.31,7.2
2,7.22,0,0,1-2.68.46A6.6,6.6,0,0,1,12,20.27,4,4,0,0,1,10.58,19,2.71,2.71,0,0,1,10,17.51
a1.05,1.05,0,0,1,.36-.8,1.28,1.28,0,0,1,.9-.33,1.14,1.14,0,0,1,.75.26,1.89,1.89,0,0,1,.
51.73,4.54,4.54,0,0,0,.49.86,2,2,0,0,0,.72.55A3.08,3.08,0,0,0,15,19a3,3,0,0,0,1.73-.45,
1.23,1.23,0,0,0,.63-1.06,1,1,0,0,0-.33-.8,2.3,2.3,0,0,0-.92-.49c-.39-.12-.92-.26-1.57-.
39a12.2,12.2,0,0,1-2.25-.67,3.64,3.64,0,0,1-1.48-1.06,2.47,2.47,0,0,1-.29-.47,2.84,2.84
,0,0,1-.26-1.22,2.71,2.71,0,0,1,.58-1.72,3.71,3.71,0,0,1,1.67-1.14A7.37,7.37,0,0,1,15,9
.14a7,7,0,0,1,2,.26,4.38,4.38,0,0,1,1.42.7,3.1,3.1,0,0,1,.84.92,2.11,2.11,0,0,1,.26,1,1
.13,1.13,0,0,1-.35.82,1.18,1.18,0,0,1-.88.36,1.09,1.09,0,0,1-.74-.23,2.68,2.68,0,0,1-.5
1-.67,3,3,0,0,0-.77-.94A2.42,2.42,0,0,0,14.87,11a2.76,2.76,0,0,0-1.49.36,1,1,0,0,0-.53.
81.78.78,0,0,0,.17.5,1.63,1.63,0,0,0,.52.38,4.48,4.48,0,0,0,.69.27l.15,0,1,.24c.69.15,1
65
.33.32,1.89.49a6.29,6.29,0,0,1,1.47.67,2.81,2.81,0,0,1,1,1,3,3,0,0,1,.35,1.49,3.15,3.15
,0,0,1-.6,1.89Zm4-2.23a7.73,7.73,0,0,0,.2-1.81c0-.22,0-.43,0-.64a8.53,8.53,0,0,0-8.56-7
.83,8.72,8.72,0,0,0-1.46.12A5.08,5.08,0,0,0,11,6a5,5,0,0,0-5,4.91,4.83,4.83,0,0,0,.68,2
.48,7.33,7.33,0,0,0-.13.94,6.51,6.51,0,0,0,0,.77,8.52,8.52,0,0,0,8.58,8.46,8.9,8.9,0,0,
0,1.57-.14A5.09,5.09,0,0,0,19,24a4.94,4.94,0,0,0,5-4.91,4.86,4.86,0,0,0-.52-2.18Z'/%3e%
3c/svg%3e");
}
.twitter {
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.whatsapp {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#25D366' d='M11.863 8.305c-.444-.011-.813.335-
1.18.677-.12.11-.235.228-.344.35-.489.552-.798 1.186-.703 1.935.103.807.187 1.63.423 2.
402.65 2.13 1.962 3.843 3.605 5.309 1.51 1.346 3.162 2.47 5.151 2.977a9.847 9.847 0 0 0
1.966.268c.984.044 2.378-.942 2.728-1.86a.37.37 0 0 0 .022-.158c-.028-.435-.052-.87-.0
97-1.303-.009-.088-.083-.212-.158-.242a276.61 276.61 0 0 0-3.316-1.281c-.277-.105-.526-
.057-.749.159-.337.325-.707.617-1.029.956-.207.217-.384.257-.617.078-.619-.48-1.26-.933
-1.853-1.443-.93-.8-1.7-1.744-2.38-2.763-.19-.284-.199-.483.077-.724.294-.256.517-.592.
804-.856.366-.336.37-.69.192-1.12a85.3 85.3 0 0 1-.964-2.46c-.3-.792-.294-.795-1.258-.8
33a.894.894 0 0 0-.32-.068zm4.016-5.566c5.806-.062 10.95 3.973 12.154 9.89 1.123 5.523-
1.825 11.269-6.975 13.536-3.56 1.568-7.1 1.477-10.606-.216-.13-.063-.337-.05-.479.004-1
.39.532-2.777 1.08-4.164 1.625-.069.027-.14.049-.266.093.412-1.455.8-2.847 1.205-4.235.
064-.216.03-.357-.112-.526-2.056-2.454-3.018-5.292-2.889-8.483.226-5.636 4.415-10.442 9
.968-11.475.727-.136 1.45-.205 2.164-.213zm.203-2.086a14.416 14.416 0 0 0-4.595.74c-5.6
36 1.87-9.435 6.872-9.764 12.803-.189 3.43.773 6.54 2.82 9.307.133.182.178.333.12.563-.
576 2.266-1.137 4.535-1.718 6.866.178-.065.31-.111.438-.162 2.147-.838 4.297-1.67 6.44-
2.521.324-.128.598-.141.925-.005 1.091.452 2.228.737 3.4.883 3.548.44 6.831-.306 9.797-
2.291 5.426-3.631 7.685-10.342 5.562-16.54A14.243 14.243 0 0 0 16.082.654zM16.032 0c.49
4.004.992.03 1.492.078 6.504.613 12.026 5.686 13.158 12.108.805 4.565-.231 8.687-3.16 1
2.275-2.333 2.857-5.366 4.599-9.012 5.227a14.618 14.618 0 0 1-7.895-.793.818.818 0 0 0-
.649 0c-2.55 1.005-5.105 1.999-7.659 2.996-.08.031-.162.058-.305.108l.783-3.13c.393-1.5
73.791-3.144 1.172-4.72a.617.617 0 0 0-.089-.442c-1.92-2.71-2.94-5.725-2.8-9.04.26-6.17
1 3.233-10.635 8.781-13.33C11.81.386 13.89-.017 16.032 0z'/%3E%3C/svg%3E") no-repeat 10
0% 100%;
}
.firefox {
66
background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name
='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3e%3cdefs%3e%3cstyle%
3e.cls-1%7bfill:%231da1f2;%7d.cls-2%7bfill:%23fff;%7d%3c/style%3e%3c/defs%3e%3ctitle%3e
Icon%3c/title%3e%3crect class='cls-1' x='1' y='1' width='28' height='28' rx='5.75' ry='
5.75'/%3e%3cpath class='cls-2' d='M11.67,23.11A11.3,11.3,0,0,0,23.05,11.73c0-.17,0-.35,
0-.52a8,8,0,0,0,2-2.07,8,8,0,0,1-2.29.63,4,4,0,0,0,1.75-2.21,8,8,0,0,1-2.54,1,4,4,0,0,0
-6.81,3.65A11.36,11.36,0,0,1,6.89,8a4,4,0,0,0-.54,2,4,4,0,0,0,1.78,3.33,4,4,0,0,1-1.81-
.5v.05a4,4,0,0,0,3.2,3.92,4,4,0,0,1-1,.14,3.67,3.67,0,0,1-.75-.07,4,4,0,0,0,3.74,2.78,8
.06,8.06,0,0,1-5,1.71,7.61,7.61,0,0,1-1-.06,11.31,11.31,0,0,0,6.14,1.8'/%3e%3c/svg%3e")
;
}
.contact {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cellipse cx='16' cy='16' fill='#4285f4' rx='16' ry='16'/%3
E%3Cpath fill='#FFF' d='M13.55 16.95h4.9c2.7 0 4.85 2.05 4.85 4.6 0 .9-.25 1.75-.75 2.4
5H9.45c-.5-.7-.75-1.55-.75-2.45 0-2.55 2.15-4.6 4.85-4.6zM16.05 8c2.05 0 3.7 1.65 3.7 3
.7 0 2.05-1.65 3.7-3.7 3.7-2.05 0-3.7-1.65-3.7-3.7.05-2.05 1.7-3.7 3.7-3.7z'/%3E%3C/svg
%3E") no-repeat 100% 100%;
}
.chrome {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#ffffff' d='M16.033 11.049a5.155 5.155 0 1 1 0
10.312 5.156 5.156 0 0 1 0-10.312zM16.124 0c1.281-.003 9.659.318 14.268 9.043h-.016l.0
1.018c.33.578 3.745 6.94-.485 14.969 0 0-4.215 8.107-14.565 7.968l-.452-.012-.004.007-.
004.007.02-.037c.564-.98 5.112-8.884 6.357-11.067l.016-.028.007-.008.04-.069.11-.127a7.
085 7.085 0 0 0 1.457-2.967l.01-.046.035-.151c.088-.424.148-.944.128-1.549l-.006-.117v-
.004l-.007-.143-.006-.07-.005-.079-.012-.116v-.01l-.001-.008-.016-.158a7.2 7.2 0 0 0-.0
96-.572l-.018-.081-.013-.064a9.801 9.801 0 0 0-.692-2.016c-.165-.243-.332-.489-.512-.73
3l-.142-.187 8.728-2.554s-10.538-.01-13.018-.001l.021.005H16.642l-.14-.013a7.034 7.034
0 0 0-1.132-.003l-.167.016h-.047l-.034-.001c-.193.002-1.213.045-2.492.764l-.005.003-.03
3.016a7.158 7.158 0 0 0-3.25 3.533l-.059.148-6.485-6.404s4.74 8.311 6.165 10.779l.065.1
13.023.088a7.14 7.14 0 0 0 7.777 5.118l.144-.02L14.854 32h-.027c-.667-.005-7.894-.234-1
2.744-7.906 0 0-4.925-7.698.37-16.573l.252-.411.001-.002C2.822 6.904 6.58.374 15.958.00
3c0 0 .057-.003.166-.003z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.pinterest {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cellipse cx='16' cy='16' fill='#bd081c' rx='16' ry='16'/%3
E%3Cpath fill='#FFF' d='M16.22 6.458c4.807-.009 9.028 1.888 9.663 5.307.787 4.256-2.438
8.866-8.213 8.535-1.565-.09-2.222-.666-3.448-1.22-.675 2.628-1.5 5.147-3.942 6.463-.75
4-3.972 1.107-6.954 1.971-10.12-1.474-1.842.177-5.547 3.284-4.634 3.824 1.123-3.31 6.84
5 1.48 7.56 5 .746 7.04-6.441 3.94-8.779-4.48-3.376-13.042-.077-11.989 4.755.256 1.181
1.9 1.54.657 3.17-2.868-.471-3.724-2.15-3.614-4.39.178-3.664 4.435-6.229 8.705-6.583.50
6-.043 1.01-.064 1.507-.064z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
67
.svg_icons {
width: 32px;
height: 32px;
display: inline-block;
}
.svg_icons + .e-badge.e-badge-overlap {
transform: translateX(-100%);
}
</style>
68
How To
The badge is a completely customizable and integral component, and this section shows how to
customize and integrate badges with other components.
Customize badges
Colour customization
Even though badges come with 8 predefined colors , you can also customize the colour of the
badge as desired.
razor
HomeController.cs
<div id='element'>
<h1>Color Customization <span class="e-badge e-badge-primary e-badge-pill green">Ne
w</span></h1>
<h1>Color Customization <span class="e-badge e-badge-primary e-badge-pill bue">New<
/span></h1>
<h1>Color Customization <span class="e-badge e-badge-primary e-badge-pill purple">N
ew</span></h1>
<h1>Color Customization <span class="e-badge e-badge-primary e-badge-pill gradient"
>New</span></h1>
</div>
<style>
#element {
display: table;
width: 560px;
margin: auto;
height: 200px;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 55px;
}
h1 {
text-align: center;
}
#element .e-badge.green {
background: #329378;
color: #fff;
69
}
#element .e-badge.blue {
background: #5f65b8;
color: #fff;
}
#element .e-badge.gradient {
background: #4776E6;
/* fallback for old browsers */
background: -webkit-linear-gradient(to top, #8E54E9, #4776E6);
/* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to top, #8E54E9, #4776E6);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
color: #fff;
}
#element .e-badge.purple {
background: #9a428f;
color: #fff;
}
</style>
razor
HomeController.cs
<div id='element'>
<h1>Badge Component <span class="e-badge e-badge-primary size_1">New</span></h1>
<h1>Badge Component <span class="e-badge e-badge-primary size_2">New</span></h1>
<h1>Badge Component <span class="e-badge e-badge-primary size_3">New</span></h1>
</div>
<Style>
#element {
display: block;
width: 400px;
70
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
}
h1 {
text-align: center;
}
.e-badge.size_1 {
font-size: 12px;
}
.e-badge.size_2 {
font-size: 16px;
}
.e-badge.size_3 {
font-size: 18px;
}
</Style>
Custom position
Even though the badges support the conventional top and bottom positions, the position of
the badges can be changed as desired. This can be done by adding a custom class to the badge
element to override the default position applied from the source.
razor
HomeController.cs
<div id='element'>
<div style="width: 200px;margin: 10px auto;">
<div class="badge-block">
<div class="whatsapp svg_icons"></div>
<!-- Warning Colored Notification Badge -->
<span class="e-badge e-badge-warning e-badge-notification e-badge-overlap l
eftTop">99+</span>
</div>
71
<div class="badge-block">
<div class="facebook svg_icons"></div>
<!-- Danger Colored Notification Badge -->
<span class="e-badge e-badge-danger e-badge-notification e-badge-overlap le
ftTop">99+</span>
</div>
<div class="badge-block">
<div class="skype svg_icons"></div>
<!-- Secondary Colored Notification Badge -->
<span class="e-badge e-badge-secondary e-badge-notification e-badge-overlap
leftTop">18</span>
</div>
</div>
<div style="width: 200px;margin: 10px auto;">
<div class="badge-block">
<div class="whatsapp svg_icons"></div>
<!-- Warning Colored Notification Badge -->
<span class="e-badge e-badge-warning e-badge-notification e-badge-overlap l
eftBottom">99+</span>
</div>
<div class="badge-block">
<div class="facebook svg_icons"></div>
<!-- Danger Colored Notification Badge -->
<span class="e-badge e-badge-danger e-badge-notification e-badge-overlap le
ftBottom">99+</span>
</div>
<div class="badge-block">
<div class="skype svg_icons"></div>
<!-- Secondary Colored Notification Badge -->
<span class="e-badge e-badge-secondary e-badge-notification e-badge-overlap
leftBottom">18</span>
</div>
</div>
</div>
<style>
#element {
display: flex;
width: 500px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
justify-content: center;
position: relative;
top: 130px;
}
72
.badge-block {
position: relative;
display: inline-block;
margin: 10px 13px 10px 10px;
}
.badge-block .e-badge.leftBottom {
transform: translateX(-150%) translateY(200%);
}
.badge-block .e-badge.leftTop {
transform: translateX(-150%);
}
/* SVG Icons */
.facebook {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#3b5998' d='M1.82 0h28.36c.908 0 1.645.819 1.6
45 1.829v28.342c0 1.011-.737 1.829-1.645 1.829h-8.188V18.852h3.934v-4.271h-3.934V13.15c
0-1.04.828-1.883 1.853-1.883h2.081V6.998h-4.505c-2.737 0-4.955 2.251-4.955 5.029v2.554h
-3.55v4.271h3.55V32H1.82c-.908 0-1.645-.818-1.645-1.829V1.829C.175.819.912 0 1.82 0z'/%
3E%3C/svg%3E") no-repeat 100% 100%;
}
.skype {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#00aff0' d='M16.067 5.579c-1.68 0-3.166.234-4.
416.696-1.265.468-2.247 1.15-2.92 2.028a4.893 4.893 0 0 0-1.022 3.046c0 1.192.328 2.207
.974 3.016.636.796 1.505 1.433 2.585 1.891 1.056.449 2.383.847 3.944 1.181 1.148.24 2.0
77.471 2.76.684.657.204 1.198.502 1.606.885.392.367.582.833.582 1.428 0 .752-.364 1.366
-1.114 1.878-.767.523-1.787.789-3.031.789-.905 0-1.64-.131-2.187-.389-.541-.257-.965-.5
85-1.261-.976-.308-.406-.599-.922-.864-1.533-.24-.56-.537-.995-.883-1.288-.363-.307-.80
9-.462-1.326-.462-.63 0-1.157.196-1.57.584a1.89 1.89 0 0 0-.628 1.421c0 .882.325 1.797.
964 2.719a7.062 7.062 0 0 0 2.478 2.199c1.413.75 3.226 1.131 5.388 1.131 1.8 0 3.383-.2
78 4.702-.827 1.333-.554 2.362-1.335 3.058-2.32a5.711 5.711 0 0 0 1.053-3.358c0-1.037-.
206-1.928-.612-2.65a5.125 5.125 0 0 0-1.697-1.792c-.706-.46-1.572-.856-2.574-1.176-.99-
.317-2.11-.61-3.327-.871a55.674 55.674 0 0 1-2.082-.51 6.642 6.642 0 0 1-1.211-.47c-.38
2-.191-.683-.42-.897-.681a1.328 1.328 0 0 1-.301-.876c0-.559.306-1.031.933-1.443.652-.4
27 1.529-.643 2.608-.643 1.16 0 2.006.195 2.512.579.52.397.976.959 1.35 1.672.325.558.6
17.946.898 1.195.302.268.74.404 1.297.404.613 0 1.133-.217 1.545-.646.41-.425.617-.914.
617-1.452 0-.559-.158-1.136-.47-1.717-.31-.574-.801-1.127-1.463-1.644-.657-.514-1.493-.
931-2.485-1.24-.987-.306-2.168-.462-3.513-.462zM8.95 0c1.708 0 3.298.492 4.643 1.339.83
6-.144 1.696-.22 2.575-.22 8.31 0 15.049 6.738 15.049 15.049 0 1.109-.121 2.189-.35 3.2
29a8.728 8.728 0 0 1-11.945 11.567c-.892.166-1.814.253-2.754.253-8.311 0-15.05-6.738-15
.05-15.049 0-1.037.105-2.049.304-3.026A8.727 8.727 0 0 1 8.95 0z'/%3E%3C/svg%3E") no-re
peat 100% 100%;
}
73
.twitter {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#1da1f2' d='M22.155 5.26c1.888 0 3.594.658 4.7
92 1.712a14.9 14.9 0 0 0 4.169-1.316c-.49 1.267-1.531 2.33-2.887 3A15.3 15.3 0 0 0 32 7
.802a12.298 12.298 0 0 1-3.276 2.807c.013.233.019.467.019.703 0 7.164-6.604 15.427-18.6
79 15.427-3.708 0-7.158-.897-10.064-2.436.514.05 1.037.076 1.566.076 3.076 0 5.907-.867
8.153-2.322-2.872-.043-5.297-1.612-6.132-3.766a7.864 7.864 0 0 0 2.964-.093c-3.003-.49
8-5.266-2.688-5.266-5.316l.001-.067a7.637 7.637 0 0 0 2.974.678c-1.762-.974-2.921-2.633
-2.921-4.514 0-.994.324-1.925.889-2.726 3.238 3.28 8.075 5.438 13.532 5.666a4.542 4.542
0 0 1-.17-1.237c0-2.994 2.939-5.421 6.565-5.421z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.whatsapp {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#25D366' d='M11.863 8.305c-.444-.011-.813.335-
1.18.677-.12.11-.235.228-.344.35-.489.552-.798 1.186-.703 1.935.103.807.187 1.63.423 2.
402.65 2.13 1.962 3.843 3.605 5.309 1.51 1.346 3.162 2.47 5.151 2.977a9.847 9.847 0 0 0
1.966.268c.984.044 2.378-.942 2.728-1.86a.37.37 0 0 0 .022-.158c-.028-.435-.052-.87-.0
97-1.303-.009-.088-.083-.212-.158-.242a276.61 276.61 0 0 0-3.316-1.281c-.277-.105-.526-
.057-.749.159-.337.325-.707.617-1.029.956-.207.217-.384.257-.617.078-.619-.48-1.26-.933
-1.853-1.443-.93-.8-1.7-1.744-2.38-2.763-.19-.284-.199-.483.077-.724.294-.256.517-.592.
804-.856.366-.336.37-.69.192-1.12a85.3 85.3 0 0 1-.964-2.46c-.3-.792-.294-.795-1.258-.8
33a.894.894 0 0 0-.32-.068zm4.016-5.566c5.806-.062 10.95 3.973 12.154 9.89 1.123 5.523-
1.825 11.269-6.975 13.536-3.56 1.568-7.1 1.477-10.606-.216-.13-.063-.337-.05-.479.004-1
.39.532-2.777 1.08-4.164 1.625-.069.027-.14.049-.266.093.412-1.455.8-2.847 1.205-4.235.
064-.216.03-.357-.112-.526-2.056-2.454-3.018-5.292-2.889-8.483.226-5.636 4.415-10.442 9
.968-11.475.727-.136 1.45-.205 2.164-.213zm.203-2.086a14.416 14.416 0 0 0-4.595.74c-5.6
36 1.87-9.435 6.872-9.764 12.803-.189 3.43.773 6.54 2.82 9.307.133.182.178.333.12.563-.
576 2.266-1.137 4.535-1.718 6.866.178-.065.31-.111.438-.162 2.147-.838 4.297-1.67 6.44-
2.521.324-.128.598-.141.925-.005 1.091.452 2.228.737 3.4.883 3.548.44 6.831-.306 9.797-
2.291 5.426-3.631 7.685-10.342 5.562-16.54A14.243 14.243 0 0 0 16.082.654zM16.032 0c.49
4.004.992.03 1.492.078 6.504.613 12.026 5.686 13.158 12.108.805 4.565-.231 8.687-3.16 1
2.275-2.333 2.857-5.366 4.599-9.012 5.227a14.618 14.618 0 0 1-7.895-.793.818.818 0 0 0-
.649 0c-2.55 1.005-5.105 1.999-7.659 2.996-.08.031-.162.058-.305.108l.783-3.13c.393-1.5
73.791-3.144 1.172-4.72a.617.617 0 0 0-.089-.442c-1.92-2.71-2.94-5.725-2.8-9.04.26-6.17
1 3.233-10.635 8.781-13.33C11.81.386 13.89-.017 16.032 0z'/%3E%3C/svg%3E") no-repeat 10
0% 100%;
}
.firefox {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#e66000' d='M27.579 8.902l.048.09a.54.54 0 0 1
-.045-.082zm-7.06-4.054c-.351.003-.712.024-1.081.067 1.2.192 2.284.501 2.729 1.457-.625
-.005-1.3-.054-1.58.291 2.275 1.189 5.035 1.886 5.315 5.096-.36-.17-.48-.58-1.005-.582.
23 1.595.78 3.799.145 5.388-.35-.422-.365-1.185-.865-1.457.105 2.68-.025 5.119-1.29 6.4
07-.035-.572.405-1.424 0-1.892-1.15 3.86-8.29 5.12-10.2 1.746 3.016.292 3.73-1.751 6.17
6-2.038-.125-.937-.915-1.676-2.01-1.748-1.19-.076-2.215 1.096-3.305 1.02-.56-.04-1.18-.
554-1.725-1.02-1.77-1.514-.894-2.931 1.58-1.892.325-.797-.145-1.698-.43-2.33.64-.954 2.
74
245-.928 2.3-2.475-1.76-.012-2.745-.81-3.45-1.894.33-1.317 1.165-2.124 2.015-2.912-1.65
.172-2.605 1.05-3.734 1.748-1.075-.346-2.275.005-3.16.29-1-.539-1.15-1.941-1.58-3.057-1
.1 1.167-1.445 3.102-1.44 5.388-.765 1.018-1.57 1.998-1.575 3.786.42.168.53-.698.715-.2
92-2.335 8.76 5.49 16.323 13.644 16.018 8.354-.313 13.649-8.231 13.219-17.182-.65-.12.0
3 1.098-.575 1.019.025-2.797-.825-5.474-2.155-6.407.31.28.204.983.35 1.428l.032.083-.08
3-.157c-1.265-2.286-3.702-3.923-6.977-3.897zM16.103 0c2.763-.007 5.09.615 6.784 1.421 4
.995 2.381 9.719 7.97 9.049 16.162-.73 8.88-8.514 14.467-16.088 14.417C6.794 31.937-.64
5 24.6.045 14.816.32 10.992 1.724 8.529 2.634 7.1 4.599 3.998 8.959.67 14.123.111a18.88
7 18.887 0 0 1 1.98-.11z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.contact {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cellipse cx='16' cy='16' fill='#4285f4' rx='16' ry='16'/%3
E%3Cpath fill='#FFF' d='M13.55 16.95h4.9c2.7 0 4.85 2.05 4.85 4.6 0 .9-.25 1.75-.75 2.4
5H9.45c-.5-.7-.75-1.55-.75-2.45 0-2.55 2.15-4.6 4.85-4.6zM16.05 8c2.05 0 3.7 1.65 3.7 3
.7 0 2.05-1.65 3.7-3.7 3.7-2.05 0-3.7-1.65-3.7-3.7.05-2.05 1.7-3.7 3.7-3.7z'/%3E%3C/svg
%3E") no-repeat 100% 100%;
}
.chrome {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cpath fill='#ffffff' d='M16.033 11.049a5.155 5.155 0 1 1 0
10.312 5.156 5.156 0 0 1 0-10.312zM16.124 0c1.281-.003 9.659.318 14.268 9.043h-.016l.0
1.018c.33.578 3.745 6.94-.485 14.969 0 0-4.215 8.107-14.565 7.968l-.452-.012-.004.007-.
004.007.02-.037c.564-.98 5.112-8.884 6.357-11.067l.016-.028.007-.008.04-.069.11-.127a7.
085 7.085 0 0 0 1.457-2.967l.01-.046.035-.151c.088-.424.148-.944.128-1.549l-.006-.117v-
.004l-.007-.143-.006-.07-.005-.079-.012-.116v-.01l-.001-.008-.016-.158a7.2 7.2 0 0 0-.0
96-.572l-.018-.081-.013-.064a9.801 9.801 0 0 0-.692-2.016c-.165-.243-.332-.489-.512-.73
3l-.142-.187 8.728-2.554s-10.538-.01-13.018-.001l.021.005H16.642l-.14-.013a7.034 7.034
0 0 0-1.132-.003l-.167.016h-.047l-.034-.001c-.193.002-1.213.045-2.492.764l-.005.003-.03
3.016a7.158 7.158 0 0 0-3.25 3.533l-.059.148-6.485-6.404s4.74 8.311 6.165 10.779l.065.1
13.023.088a7.14 7.14 0 0 0 7.777 5.118l.144-.02L14.854 32h-.027c-.667-.005-7.894-.234-1
2.744-7.906 0 0-4.925-7.698.37-16.573l.252-.411.001-.002C2.822 6.904 6.58.374 15.958.00
3c0 0 .057-.003.166-.003z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.pinterest {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/
svg' viewBox='0 0 32 32'%3E%3Cellipse cx='16' cy='16' fill='#bd081c' rx='16' ry='16'/%3
E%3Cpath fill='#FFF' d='M16.22 6.458c4.807-.009 9.028 1.888 9.663 5.307.787 4.256-2.438
8.866-8.213 8.535-1.565-.09-2.222-.666-3.448-1.22-.675 2.628-1.5 5.147-3.942 6.463-.75
4-3.972 1.107-6.954 1.971-10.12-1.474-1.842.177-5.547 3.284-4.634 3.824 1.123-3.31 6.84
5 1.48 7.56 5 .746 7.04-6.441 3.94-8.779-4.48-3.376-13.042-.077-11.989 4.755.256 1.181
1.9 1.54.657 3.17-2.868-.471-3.724-2.15-3.614-4.39.178-3.664 4.435-6.229 8.705-6.583.50
6-.043 1.01-.064 1.507-.064z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.svg_icons {
75
width: 32px;
height: 32px;
display: inline-block;
}
</style>
Integration
Listview
The badges can be integrated with the listview component to indicate new notification with
colour based on priority.
In the following sample, default badges are used and there is no need to customize the badge
size. The component will automatically adjust the size based on the container element.
razor
HomeController.cs
@section ControlsSection{
<div class="col-lg-12 control-section">
@section PreScripts {
<script id="template" type="text/x-template">
<div class="listWrapper" style="width: inherit; height: inherit;">
<span class="${icons} list_svg"> </span>
<span class="list_text">'${text}'</span>
${if(messages !== '')}
<span class='${badge}' style="float: right; margin-top: 16px; font-size
: 12px;">${messages}</span>
76
${/if}
</div>
</script>
}
<script>
function actionComplete() {
let list = document.getElementById('lists').getElementsByClassName('e-list-grou
p-item')[0];
list.style.display = 'none';
}
</script>
<style>
.control-section {
overflow: auto;
}
.sample_container.badge-list {
max-width: 350px;
margin: auto;
}
#lists {
margin: auto;
border: 1px solid rgba(0, 0, 0, 0.12)
}
#lists .e-list-item {
cursor: pointer;
height: 50px;
line-height: 48px;
border: 0;
}
.list_svg {
width: 24px;
height: 24px;
display: inline-block;
margin-top: 11px;
margin-right: 16px;
}
.list_text {
width: 60%;
display: inline-block;
vertical-align: top;
77
}
.updates {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M17.024 13.812l.022.162v.8
93c0 .487-.007.942-.022 1.366-.012.423-.027.833-.042 1.23v2.435c0 .415.022.799.064 1.15
.042.35.11.559.202.622.091.063.232.095.422.095h.328l.105.324c-.041.073-.125.136-.253.18
9-.127.055-.226.063-.296.028H14.126a.556.556 0 0 1-.34-.109v-.27c.086-.108.22-.162.403-
.162h.38c.185-.109.294-.219.328-.328.036-.108.054-.3.054-.573a7.32 7.32 0 0 0 .042-.819
c0-.29.007-.527.021-.709V17.233c0-.636-.018-1.041-.053-1.213-.034-.173-.082-.386-.138-.
64a20.09 20.09 0 0 1-.455.19c-.176.072-.291.108-.348.108l-.105-.162c0-.162.09-.307.274-
.434l.38-.27a6.472 6.472 0 0 1 .847-.406c.227-.144.469-.265.73-.365.26-.1.554-.176.878-
.229zm-.952-5.736a.9.9 0 0 1 .613.243c.184.162.343.361.477.595.135.235.2.451.2.65 0 .45
1-.129.802-.39 1.054-.261.254-.453.397-.572.434a1.424 1.424 0 0 1-.412.054.934.934 0 0
1-.455-.122c-.15-.082-.293-.23-.433-.447a1.834 1.834 0 0 1-.277-.676c-.027-.307.044-.63
.213-.974.17-.342.373-.577.613-.703.17-.072.31-.108.423-.108zM16 3.465C9.088 3.465 3.46
4 9.088 3.464 16c0 6.913 5.624 12.536 12.536 12.536S28.536 22.913 28.536 16c0-6.912-5.6
24-12.535-12.536-12.535zM16 1.6c7.94 0 14.4 6.46 14.4 14.4S23.94 30.4 16 30.4 1.6 23.94
1.6 16 8.06 1.6 16 1.6z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.promotion {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M6 4c.4 0 .7.2 1 .4.5.6.5
1.5-.1 2-.5.5-1.4.5-1.9-.1s-.5-1.4.1-1.9c.2-.3.6-.4.9-.4zm0-1c-.6 0-1.2.2-1.6.6-1 .9-1.
1 2.4-.2 3.4.9 1 2.4 1 3.4.2 1-.9 1-2.4.1-3.4C7.3 3.2 6.6 3 6 3zm.3-3l7.1 1 18 19.6L18.
9 32 .9 12.4.6 5.3z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.social {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M15.254 19.089c.996 0 3.58
7 1.992 3.786 8.27l-19.03.199s-.498-7.97 5.579-8.37c2.392-.398 4.783 1.993 6.178 1.793
1.295-.198 2.59-1.892 3.487-1.892zm3.886-2.69c.797 0 1.793 1.495 2.989 1.694 1.096.198
3.188-1.993 5.18-1.595 5.082.3 4.684 7.573 4.684 7.573l-11.558-.1c-.697-3.687-2.391-5.1
81-3.288-5.38.598-1.594 1.495-2.192 1.993-2.192zm-8.17-9.963c2.79 0 4.98 2.49 4.98 5.67
9 0 3.089-2.19 5.679-4.98 5.679-2.79 0-4.982-2.491-4.982-5.68 0-3.088 2.192-5.678 4.982
-5.678zm11.657-1.994c2.49 0 4.583 2.293 4.583 5.082 0 2.79-2.092 5.082-4.583 5.082s-4.5
83-2.293-4.583-5.082c0-2.79 2.092-5.082 4.583-5.082z'/%3E%3C/svg%3E") no-repeat 100% 10
0%;
}
.primary {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M1 7.5h10v2H2v18h28v-18h-9
v-2h10a1 1 0 0 1 1 1v20a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1v-20a1 1 0 0 1 1-1zm14-5h2v13.172l
2.536-2.536 1.414 1.414L17 18.5l-1 1-1-1-3.95-3.95 1.414-1.414L15 15.672z'/%3E%3C/svg%3
E") no-repeat 100% 100%;
}
78
.draft {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M10.262 23.448l2.295 2.298
-3.443 1.149zm6.886-6.895l2.296 2.298-5.739 5.746-2.295-2.298zm3.443-3.448l2.295 2.299-
2.295 2.298-2.295-2.298zM21 3.414V7h3.785zM6 2v28h20V9h-4.833C20.062 9 19 8.137 19 7.03
2V2zm.167-2h14.414L28 7.586V30c0 1.103-.73 2-1.833 2h-20C5.064 32 4 31.103 4 30V2C4 .89
7 5.064 0 6.167 0z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.outbox {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M2 9.63V26h28.001V9.67L15.
998 20.08zM2 6v1.134l14.001 10.452 14-10.408L30 6zm0-2h28c1.103 0 2 .897 2 2v20c0 1.103
-.897 2-2 2H2c-1.103 0-2-.897-2-2V6c0-1.103.897-2 2-2z'/%3E%3C/svg%3E") no-repeat 100%
100%;
}
.sent {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M6.756 7.527l6.997 8.487-7
.02 8.516 20.126-8.457zM0 2.48l32 13.603L.024 29.52l11.135-13.506z'/%3E%3C/svg%3E") no-
repeat 100% 100%;
}
.important {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M1.3 2.7c.7 0 1.3.6 1.3 1.
3v25.2c0 .7-.6 1.3-1.3 1.3-.7 0-1.3-.6-1.3-1.3V4c0-.7.6-1.3 1.3-1.3zm10.3-1.2C18.2 1.5
23.7 5 32 2v17.5c-11.1 4-17.1-3.7-27.7 1V3.1c2.7-1.2 5-1.6 7.3-1.6z'/%3E%3C/svg%3E") no
-repeat 100% 100%;
}
.starred {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M16 1.6l4.45 9.48 9.95 1.5
2-7.2 7.38 1.7 10.42-8.9-4.92-8.9 4.92 1.7-10.42-7.2-7.38 9.951-1.52z'/%3E%3C/svg%3E")
no-repeat 100% 100%;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
79
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class BadgeController : Controller
{
public IActionResult Listview()
{
List<object> data = new List<object>();
data.Add(new { id = "p_01", text = "Primary", messages = "3 New", badge = "
e-badge e-badge-primary", icons = "primary", type = "Primary" });
data.Add(new { id = "p_02", text = "Social", messages = "27 New", badge = "
e-badge e-badge-secondary", icons = "social", type = "Primary" });
data.Add(new { id = "p_03", text = "Promotions", messages = "7 New", badge
= "e-badge e-badge-success", icons = "promotion", type = "Primary" });
data.Add(new { id = "p_04", text = "Updates", messages = "13 New", badge =
"e-badge e-badge-info", icons = "updates", type = "Primary" });
data.Add(new { id = "p_05", text = "Starred", messages = "", badge = "", ic
ons = "starred", type = "All Labels" });
data.Add(new { id = "p_06", text = "Important", messages = "2 New", badge =
"e-badge e-badge-danger", icons = "important", type = "All Labels" });
data.Add(new { id = "p_07", text = "Sent", messages = "", badge = "", icons
= "sent", type = "All Labels" });
data.Add(new { id = "p_08", text = "Outbox", messages = "", badge = "", ico
ns = "outbox", type = "All Labels" });
data.Add(new { id = "p_09", text = "Drafts", messages = "7 New", badge = "e
-badge e-badge-warning", icons = "draft", type = "All Labels" });
ViewBag.dataSource = data;
return View();
}
}
}
Dynamic Content
Badges in real-time needs to be updated dynamically based on the requirements. The following
sample demonstrates how to update the badges content dynamically. Click the increment button
to change the badge value.
razor
HomeController.cs
@section ControlsSection{
<div class="col-lg-12 control-section">
<div class="sample_container badge-list">
<!-- Listview element -->
80
@Html.EJS().ListView("lists").Enable(true).DataSource((IEnumerable<object>)
ViewBag.dataSource).HeaderTitle("Inbox").ShowHeader(true).Template("#template").ActionC
omplete("actionComplete").Fields(new ListViewFieldSettings { GroupBy = "type" }).Render
()
<p class='crossline'></p>
<span class='incr_button'>
<button class='e-btn e-primary' id='button'>Increment Badge Count</butt
on>
</span>
</div>
</div>
}
@section PreScripts {
<script id="template" type="text/x-template">
<div class="listWrapper" style="width: inherit; height: inherit;">
<span class="${icons} list_svg"> </span>
<span class="list_text">'${text}'</span>
${if(messages !== '')}
<span class='${badge}' style="float: right; margin-top: 16px; font-size
: 12px;">${messages}</span>
${/if}
</div>
</script>
}
<style>
.control-section {
overflow: auto;
}
.sample_container.badge-list {
max-width: 650px;
margin: auto;
height: 540px;
}
#lists {
width: 370px;
display: inline-block;
border: 1px solid rgba(0, 0, 0, 0.12)
}
#lists ul li:first-child {
display: none;
}
.incr_button {
vertical-align: top;
position: relative;
top: 250px;
81
display: inline-block;
}
.crossline {
display: inline-block;
height: 100%;
margin: 0 20px;
width: 1px;
background: #8080805c;
}
#lists .e-list-item {
cursor: pointer;
height: 50px;
line-height: 48px;
border: 0;
}
.list_svg {
width: 24px;
height: 24px;
display: inline-block;
margin-top: 11px;
margin-right: 16px;
}
.list_text {
width: 60%;
display: inline-block;
vertical-align: top;
}
.updates {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M17.024 13.812l.022.162v.8
93c0 .487-.007.942-.022 1.366-.012.423-.027.833-.042 1.23v2.435c0 .415.022.799.064 1.15
.042.35.11.559.202.622.091.063.232.095.422.095h.328l.105.324c-.041.073-.125.136-.253.18
9-.127.055-.226.063-.296.028H14.126a.556.556 0 0 1-.34-.109v-.27c.086-.108.22-.162.403-
.162h.38c.185-.109.294-.219.328-.328.036-.108.054-.3.054-.573a7.32 7.32 0 0 0 .042-.819
c0-.29.007-.527.021-.709V17.233c0-.636-.018-1.041-.053-1.213-.034-.173-.082-.386-.138-.
64a20.09 20.09 0 0 1-.455.19c-.176.072-.291.108-.348.108l-.105-.162c0-.162.09-.307.274-
.434l.38-.27a6.472 6.472 0 0 1 .847-.406c.227-.144.469-.265.73-.365.26-.1.554-.176.878-
.229zm-.952-5.736a.9.9 0 0 1 .613.243c.184.162.343.361.477.595.135.235.2.451.2.65 0 .45
1-.129.802-.39 1.054-.261.254-.453.397-.572.434a1.424 1.424 0 0 1-.412.054.934.934 0 0
1-.455-.122c-.15-.082-.293-.23-.433-.447a1.834 1.834 0 0 1-.277-.676c-.027-.307.044-.63
.213-.974.17-.342.373-.577.613-.703.17-.072.31-.108.423-.108zM16 3.465C9.088 3.465 3.46
4 9.088 3.464 16c0 6.913 5.624 12.536 12.536 12.536S28.536 22.913 28.536 16c0-6.912-5.6
82
24-12.535-12.536-12.535zM16 1.6c7.94 0 14.4 6.46 14.4 14.4S23.94 30.4 16 30.4 1.6 23.94
1.6 16 8.06 1.6 16 1.6z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.promotion {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M6 4c.4 0 .7.2 1 .4.5.6.5
1.5-.1 2-.5.5-1.4.5-1.9-.1s-.5-1.4.1-1.9c.2-.3.6-.4.9-.4zm0-1c-.6 0-1.2.2-1.6.6-1 .9-1.
1 2.4-.2 3.4.9 1 2.4 1 3.4.2 1-.9 1-2.4.1-3.4C7.3 3.2 6.6 3 6 3zm.3-3l7.1 1 18 19.6L18.
9 32 .9 12.4.6 5.3z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.social {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M15.254 19.089c.996 0 3.58
7 1.992 3.786 8.27l-19.03.199s-.498-7.97 5.579-8.37c2.392-.398 4.783 1.993 6.178 1.793
1.295-.198 2.59-1.892 3.487-1.892zm3.886-2.69c.797 0 1.793 1.495 2.989 1.694 1.096.198
3.188-1.993 5.18-1.595 5.082.3 4.684 7.573 4.684 7.573l-11.558-.1c-.697-3.687-2.391-5.1
81-3.288-5.38.598-1.594 1.495-2.192 1.993-2.192zm-8.17-9.963c2.79 0 4.98 2.49 4.98 5.67
9 0 3.089-2.19 5.679-4.98 5.679-2.79 0-4.982-2.491-4.982-5.68 0-3.088 2.192-5.678 4.982
-5.678zm11.657-1.994c2.49 0 4.583 2.293 4.583 5.082 0 2.79-2.092 5.082-4.583 5.082s-4.5
83-2.293-4.583-5.082c0-2.79 2.092-5.082 4.583-5.082z'/%3E%3C/svg%3E") no-repeat 100% 10
0%;
}
.primary {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M1 7.5h10v2H2v18h28v-18h-9
v-2h10a1 1 0 0 1 1 1v20a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1v-20a1 1 0 0 1 1-1zm14-5h2v13.172l
2.536-2.536 1.414 1.414L17 18.5l-1 1-1-1-3.95-3.95 1.414-1.414L15 15.672z'/%3E%3C/svg%3
E") no-repeat 100% 100%;
}
.draft {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M10.262 23.448l2.295 2.298
-3.443 1.149zm6.886-6.895l2.296 2.298-5.739 5.746-2.295-2.298zm3.443-3.448l2.295 2.299-
2.295 2.298-2.295-2.298zM21 3.414V7h3.785zM6 2v28h20V9h-4.833C20.062 9 19 8.137 19 7.03
2V2zm.167-2h14.414L28 7.586V30c0 1.103-.73 2-1.833 2h-20C5.064 32 4 31.103 4 30V2C4 .89
7 5.064 0 6.167 0z'/%3E%3C/svg%3E") no-repeat 100% 100%;
}
.outbox {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M2 9.63V26h28.001V9.67L15.
998 20.08zM2 6v1.134l14.001 10.452 14-10.408L30 6zm0-2h28c1.103 0 2 .897 2 2v20c0 1.103
-.897 2-2 2H2c-1.103 0-2-.897-2-2V6c0-1.103.897-2 2-2z'/%3E%3C/svg%3E") no-repeat 100%
100%;
}
83
.sent {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M6.756 7.527l6.997 8.487-7
.02 8.516 20.126-8.457zM0 2.48l32 13.603L.024 29.52l11.135-13.506z'/%3E%3C/svg%3E") no-
repeat 100% 100%;
}
.important {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M1.3 2.7c.7 0 1.3.6 1.3 1.
3v25.2c0 .7-.6 1.3-1.3 1.3-.7 0-1.3-.6-1.3-1.3V4c0-.7.6-1.3 1.3-1.3zm10.3-1.2C18.2 1.5
23.7 5 32 2v17.5c-11.1 4-17.1-3.7-27.7 1V3.1c2.7-1.2 5-1.6 7.3-1.6z'/%3E%3C/svg%3E") no
-repeat 100% 100%;
}
.starred {
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org
/2000/svg' viewBox='0 0 32 32'%3E%3Cpath fill='%239E9E9E' d='M16 1.6l4.45 9.48 9.95 1.5
2-7.2 7.38 1.7 10.42-8.9-4.92-8.9 4.92 1.7-10.42-7.2-7.38 9.951-1.52z'/%3E%3C/svg%3E")
no-repeat 100% 100%;
}
</style>
<script type="text/javascript">
var badgeElements;
function onActionComplete() {
badgeElements = Array.prototype.slice.call(document.getElementById('lists').get
ElementsByClassName('e-badge'));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
84
{
public partial class BadgeController : Controller
{
public IActionResult Listview()
{
List<object> data = new List<object>();
data.Add(new { id = "p_01", text = "Primary", messages = "3 New", badge = "
e-badge e-badge-primary", icons = "primary", type = "Primary" });
data.Add(new { id = "p_02", text = "Social", messages = "27 New", badge = "
e-badge e-badge-secondary", icons = "social", type = "Primary" });
data.Add(new { id = "p_03", text = "Promotions", messages = "7 New", badge
= "e-badge e-badge-success", icons = "promotion", type = "Primary" });
data.Add(new { id = "p_04", text = "Updates", messages = "13 New", badge =
"e-badge e-badge-info", icons = "updates", type = "Primary" });
data.Add(new { id = "p_05", text = "Starred", messages = "", badge = "", ic
ons = "starred", type = "All Labels" });
data.Add(new { id = "p_06", text = "Important", messages = "2 New", badge =
"e-badge e-badge-danger", icons = "important", type = "All Labels" });
data.Add(new { id = "p_07", text = "Sent", messages = "", badge = "", icons
= "sent", type = "All Labels" });
data.Add(new { id = "p_08", text = "Outbox", messages = "", badge = "", ico
ns = "outbox", type = "All Labels" });
data.Add(new { id = "p_09", text = "Drafts", messages = "7 New", badge = "e
-badge e-badge-warning", icons = "draft", type = "All Labels" });
ViewBag.dataSource = data;
return View();
}
}
}
85
Common
Breaking Changes
The API types are corrected from static Object to its corresponding type references in
16.2.41 version of Essential JS 2. Please refer this Migration from 16.1 to 16.2 link for
further details.
Starting with version 16.2 (2018 Vol 2), you need to include a valid license key (either paid or trial
key) within your applications. Please refer to this help topic for more information.
Accumulation Chart
New Features
Support has been provided to group the pie slice based on count.
AutoComplete
Breaking Changes
Provided enum support for floatLabelType property.
Button
Breaking Changes
Default color changed for the flat button
ButtonGroup
ButtonGroup is a graphical user interface that groups series of buttons horizontally or vertically.
Types, Sizes, and Styles - Provided with different types, sizes and predefined styles of
button.
Selection - Supports single and multiple selection behaviors.
Orientation - Supports horizontal and vertical orientations.
Nesting - Supports nesting with drop-down and split button components.
Accessibility - Built-in accessibility features to access all the button group using the
keyboard, screen readers, or other assistive technology devices.
86
Calendars
New Features
Event arguments for all Calendar components has been streamlined.
Chart
Bug Fixes
Now, tooltip is working properly when the container for chart is initialized without ID.
The performance issue with loading 800 series in chart has been fixed.
Mean value for Box and Whisker is now rendering properly with multiple series.
New Features
Histogram series type has been added to chart.
Scrollbar feature has been added to zoom and pan the chart.
CircularGauge
Bug Fixes
Provided one way binding support for Axes properties in Angular platform.
ColorPicker
Color picker is a user interface that is used to select and adjust color values.
Color specification: Supports Red Green Blue , Hue Saturation Value and Hex codes.
Mode: Supports Picker and Palette mode.
Inline: Supports inline type rendering of color picker.
Custom palettes: Allows you to customize palettes and supports multiple palette groups
rendering.
Opacity: Allows to set and change the opacity of the selected color.
Accessibility: Built-in accessibility features to access color picker using the keyboard,
screen readers, or other assistive technology devices.
ComboBox
Breaking Changes
87
Provided enum support for floatLabelType property.
DatePicker
Breaking Changes
Now, you can access the floatLabelType Enum type directly instead of mentioning along with
the namespace as Syncfusion.EJ2.Inputs.FloatLabelType .
DateRangePicker
Breaking Changes
Now, you can access the floatLabelType Enum type directly instead of mentioning along with
the namespace as Syncfusion.EJ2.Inputs.FloatLabelType .
New Features
DrillDown support has been provided for DateRangePicker component that allows to quick
navigate back and forth from month, year, and decade views to select a range easier.
Value property support has been provided for DateRangePicker component to set a date
range.
DateTimePicker
Breaking Changes
Now, you can access the floatLabelType Enum type directly instead of mentioning along with
the namespace as Syncfusion.EJ2.Inputs.FloatLabelType .
Diagram
The diagram component visually represents information. It is also used to create diagrams like
flow charts, organizational charts, mind maps, and BPMN either through code or a visual
interface.
Nodes - Nodes are used to host graphical objects (path or controls) that can be arranged
and manipulated on a diagram page. Many predefined standard shapes are included.
Custom shapes can also be created and added easily.
Connectors - The relationship between two nodes is represented using a connector.
Labels - Labels are used to annotate nodes and connectors.
88
Interactive Features - Interactive features are used to improve the run time editing
experience of a diagram.
Data Binding - Generates diagram with nodes and connectors based on the information
provided from an external data source.
Commands - Supports a set of predefined commands that helps edit the diagram using
keyboard. It is also possible to configure new commands and key combinations.
Automatic Layout - Automatic layouts are used to arrange nodes automatically based on a
predefined layout logic. There is built-in support for organizational chart layout, hierarchical
tree layout, symmetric layout, radial tree layout, and mind map layout.
Overview Panel - The overview panel is used to improve navigation experience when
exploring large diagrams.
SymbolPalettes - The symbol palette is a gallery of reusable symbols and nodes that can
be dragged and dropped on the surface of a diagram.
Rulers - The ruler provides horizontal and vertical guides for measuring diagram objects in
diagram control.
Serialization - When saved in JSON format a diagram’s state persists, and then it can be
loaded back using serialization.
Exporting and Printing - Diagrams can be exported as .png, .jpeg, .bmp, and .svg image
files, and can also be printed as documents.
Gridlines - Gridlines are the pattern of lines drawn behind diagram elements. It provides a
visual guidance while dragging or arranging the objects on a diagram surface.
Page Layout - The drawing surface can be configured to page-like appearance using page
size, orientation, and margins.
Context Menu - Frequently used commands can easily be mapped to the context menu.
Document Editor
The Document Editor component is used to create, edit, view, and print Word documents in web
applications. All the user interactions and editing operations that run purely in the client-side
provides much faster editing experience to the users.
Opens the native Syncfusion Document Text (*.sfdt) format documents in the client-side.
Saves the documents in the client-side as Syncfusion Document Text (*.sfdt) and Word
document (*.docx) .
Supports document elements like text, inline image, table, fields, bookmark, section, header,
and footer.
Supports the commonly used fields like hyperlink, page number, page count, and table of
contents.
Supports formats like text, paragraph, bullets and numbering, table, page settings, etc.
Provides support to create, edit, and apply paragraph and character styles.
Provides support to find and replace text within the document.
Supports all the common editing and formatting operations along with undo and redo.
89
Provides support to cut, copy, and paste rich text contents within the component. Also allows
pasting simple text to and from other applications.
Allows user interactions like zoom, scroll, select contents through touch, mouse, and
keyboard.
Provides intuitive UI options like context menu, dialogs, and navigation pane.
Creates a lightweight Word viewer using module injection to view and prints Word
documents.
DropDownList
Breaking Changes
Provided enum support for floatLabelType property.
HeatMap
The HeatMap control is used to visualize a two-dimensional data in which the values are
represented in gradient or fixed colors.
Axis Types - Supports three different types of axes to populate the data, namely Numerical,
Categorical,and Datetime.
Axis Feature - Supports inverted axis, opposed position and axis intervals.
Legend - Supports legend which provides value information for the colors which represents
each values in HeatMap.
Data Binding - Supports binding data in JSON and two-dimensional array formats.
Rendering Modes - Supports automatic switching between SVG and Canvas rendering
modes based on the data source length.
Input
New Features
The clear button can be enabled/disabled dynamically through setClearButton method.
ListView
Breaking Changes
The following API namings are renamed.
90
unCheckAllItem uncheckAllItems
unCheckItem uncheckItem
New Features
UI-Virtualization implemented to render only viewable list items in a view port on loading
large number of data.
Maps
New Features
Support has been added for animating the shapes on zooming.
Support has been added to trim the maps title, when it exceeds the available width.
Support had been provided for printing and exporting the maps.
Support has been provided for printing.
MaskedTextBox
New Features
Provided option to show/hide clear button to reset the value in MaskedTextBox
MultiSelect
Breaking Changes
Provided enum support for floatLabelType property.
NumericTextBox
New Features
Provided option to show/hide clear button to reset the value in NumericTextBox.
Prevented to type unwanted text and symbols in NumericTextBox.
Pivot Grid
91
The pivot grid is a multidimensional data visualization component built on top of relational data
sources. The pivot report can be managed dynamically at runtime along with other capabilities
like aggregation, filtering, and sorting based on fields and values.
RadioButton
Bug Fixes
Wrapped text of a RadioButton label overlaps with next RadioButton label issue fixed.
RangeNavigator
The range navigator provides an intuitive interface for selecting a smaller range from a larger
collection. It is commonly used in financial dashboards to filter a date range for which the data
needs to be visualized. This control easily combines with other controls such as Chart, Data Grid,
etc., to create rich and powerful dashboards.
Data Binding - Binds the data with local and remote data source.
Chart - To represent the data in RangeNavigator and its supports line, step line and area
type series.
Slider - To handle the selected data in RangeNavigator.
Data Types - Supports three different types of data, namely Numerical, Datetime, and
Logarithmic.
Animation - Chart series and slider will be animated when rendering and changing the
selected data.
Period Selector - Supports period selector to select data based on predefined periods.
Light Weight - Supports light weight RN to navigate through the data based on range.
Tooltip - Supports tooltip for the selected data.
92
Export - Supports to print the range navigator directly from the browser and exports the
range navigator in both JPEG and PNG format.
RichTextEditor
The rich text editor component is WYSIWYG ("what you see is what you get") editor used to
create and edit the content and return valid HTML markup or markdown (MD) of the content. The
editor provides a standard toolbar to format content using its commands. Modular library features
to load the necessary functionality on demand. The toolbar contains commands to align the text,
insert link, insert image, insert list, undo/redo operation, HTML view, and more.
Schedule
New Features
Distinct time interval option with customizable major and minor slots has been introduced to
view the appointments clearly and accurately.
An enhancement has been made to extend the default view range with customized intervals,
to display 'n' number of days, weeks and months.
Validation support on recurrence appointment(s) has been added.
Multiple resources support has been added with the following options.
Group By Child - To group the same child resource(s) under different parent resource(s).
Group By Date - To group the resource(s) on day basis.
Group Editing - To edit all resource events simultaneously.
Custom Work Days - To display the custom work days for each resource.
Provided public methods to add or remove the resources dynamically.
Breaking Changes
Appearance enhancement has been done on quick popup that opens, when single clicked
on cells and events. Also, the same popup opens on single tap of events on mobile mode.
93
Sidebar
Breaking Changes
Target property supports both the id and class selectors to locate the target element.
New Features
Support for setting the open/close state of the Sidebar has been provided with isOpen
property.
Slider
Breaking Changes
The following API namings are renamed.
readOnly readonly
New Features
Limits implemented to limit movement interval of min and max values to certain range.
Drag interval implemented to interact with the range slider by dragging the range.
Provided to support custom value arrays.
Bootstrap theme tooltip appearance improved by enabling tooltip pointer.
Smith Chart
Smith chart is one of the most useful data visualization tools for high frequency circuit
applications. It contains two sets of circles to plot the parameters of transmission lines.
Sparkline
94
Sparklines are easy to interpret and also it conveys much more information to the user by
visualizing the data in a small amount of space.
Types - Sparklines had five type of series. Line, Area, Column and WinLoss and Pie.
Marker - Sparklines support the marker feature.
DataLabel - Sparklines support the datalabel feature. It uses to identify the x and y value for
the current point.
Range Band - Sparklines support the rangeband feature. It used to denote the certain range
sparkline points.
Tooltip - Sparklines support the tooltip feature. It used to interact with points to get more
about current point.
SplitButton
Breaking Changes
UI changes based on design guidelines
Switch
Switch is a graphical user interface element that allows you to toggle between checked and
unchecked states.
TimePicker
Breaking Changes
Now, you can access the floatLabelType Enum type directly instead of mentioning along with
the namespace as Syncfusion.EJ2.Inputs.FloatLabelType .
Tooltip
Bug Fixes
Tooltip positioning issue fixed while target placed right of the page.
TreeMap
95
The TreeMap is used to displayed the hierarchical or multi-level data to visualize the nested
rectangles.
Uploader
New Features
Added chunked upload support to upload large files asynchronously with pause and
resume options.
Support has been provided to resume automatically on failed chunk up to maximum retry
options.
Included option to handle retry upload through UI (User Interface).
Support to cancel the request while uploading a file is added.
96
Common
Starting with version 16.2 (2018 Vol 2), you need to include a valid license key (either paid
or trial key) within your applications. Please refer to this help topic for more information.
Breaking Changes
The API types are corrected from static Object to its corresponding type references in
16.2.41 version of Essential JS 2. Please refer this Migration from 16.1 to 16.2 link for
further details.
Button
Breaking Changes
Default color changed for the flat button
ButtonGroup
ButtonGroup is a graphical user interface that groups series of buttons horizontally or vertically.
Types, Sizes, and Styles - Provided with different types, sizes and predefined styles of
button.
Selection - Supports single and multiple selection behaviors.
Orientation - Supports horizontal and vertical orientations.
Nesting - Supports nesting with drop-down and split button components.
Accessibility - Built-in accessibility features to access all the button group using the
keyboard, screen readers, or other assistive technology devices.
CircularGauge
Bug Fixes
Provided one way binding support for Axes properties in Angular platform.
ColorPicker
Color picker is a user interface that is used to select and adjust color values.
Color specification: Supports Red Green Blue , Hue Saturation Value and Hex codes.
Mode: Supports Picker and Palette mode.
97
Inline: Supports inline type rendering of color picker.
Custom palettes: Allows you to customize palettes and supports multiple palette groups
rendering.
Opacity: Allows to set and change the opacity of the selected color.
Accessibility: Built-in accessibility features to access color picker using the keyboard,
screen readers, or other assistive technology devices.
Diagram
The diagram component visually represents information. It is also used to create diagrams like
flow charts, organizational charts, mind maps, and BPMN either through code or a visual
interface.
Nodes - Nodes are used to host graphical objects (path or controls) that can be arranged
and manipulated on a diagram page. Many predefined standard shapes are included.
Custom shapes can also be created and added easily.
Connectors - The relationship between two nodes is represented using a connector.
Labels - Labels are used to annotate nodes and connectors.
Interactive Features - Interactive features are used to improve the run time editing
experience of a diagram.
Data Binding - Generates diagram with nodes and connectors based on the information
provided from an external data source.
Commands - Supports a set of predefined commands that helps edit the diagram using
keyboard. It is also possible to configure new commands and key combinations.
Automatic Layout - Automatic layouts are used to arrange nodes automatically based on a
predefined layout logic. There is built-in support for organizational chart layout, hierarchical
tree layout, symmetric layout, radial tree layout, and mind map layout.
Overview Panel - The overview panel is used to improve navigation experience when
exploring large diagrams.
SymbolPalettes - The symbol palette is a gallery of reusable symbols and nodes that can
be dragged and dropped on the surface of a diagram.
Rulers - The ruler provides horizontal and vertical guides for measuring diagram objects in
diagram control.
Serialization - When saved in JSON format a diagram’s state persists, and then it can be
loaded back using serialization.
Exporting and Printing - Diagrams can be exported as .png, .jpeg, .bmp, and .svg image
files, and can also be printed as documents.
Gridlines - Gridlines are the pattern of lines drawn behind diagram elements. It provides a
visual guidance while dragging or arranging the objects on a diagram surface.
Page Layout - The drawing surface can be configured to page-like appearance using page
size, orientation, and margins.
Context Menu - Frequently used commands can easily be mapped to the context menu.
98
HeatMap
The HeatMap control is used to visualize a two-dimensional data in which the values are
represented in gradient or fixed colors.
Axis Types - Supports three different types of axes to populate the data, namely Numerical,
Categorical,and Datetime.
Axis Feature - Supports inverted axis, opposed position and axis intervals.
Legend - Supports legend which provides value information for the colors which represents
each values in HeatMap.
Data Binding - Supports binding data in JSON and two-dimensional array formats.
Rendering Modes - Supports automatic switching between SVG and Canvas rendering
modes based on the data source length.
Input
New Features
The clear button can be enabled/disabled dynamically through setClearButton method.
ListView
Breaking Changes
The following API namings are renamed.
unCheckAllItem uncheckAllItems
unCheckItem uncheckItem
New Features
UI-Virtualization implemented to render only viewable list items in a view port on loading
large number of data.
Maps
New Features
Support has been added for animating the shapes on zooming.
Support has been added to trim the maps title, when it exceeds the available width.
99
Support had been provided for printing and exporting the maps.
Support has been provided for printing.
MaskedTextBox
New Features
Provided option to show/hide clear button to reset the value in MaskedTextBox
NumericTextBox
New Features
Provided option to show/hide clear button to reset the value in NumericTextBox.
Prevented to type unwanted text and symbols in NumericTextBox.
RadioButton
Bug Fixes
Wrapped text of a RadioButton label overlaps with next RadioButton label issue fixed.
Sidebar
Breaking Changes
Target property supports both the id and class selectors to locate the target element.
New Features
Support for setting the open/close state of the Sidebar has been provided with isOpen
property.
Slider
Breaking Changes
The following API namings are renamed.
readOnly readonly
100
New Features
Limits implemented to limit movement interval of min and max values to certain range.
Drag interval implemented to interact with the range slider by dragging the range.
Provided to support custom value arrays.
Bootstrap theme tooltip appearance improved by enabling tooltip pointer.
SplitButton
Breaking Changes
UI changes based on design guidelines
Switch
Switch is a graphical user interface element that allows you to toggle between checked and
unchecked states.
Tooltip
Bug Fixes
Tooltip positioning issue fixed while target placed right of the page.
TreeMap
The TreeMap is used to displayed the hierarchical or multi-level data to visualize the nested
rectangles.
101
Uploader
New Features
Added chunked upload support to upload large files asynchronously with pause and
resume options.
Support has been provided to resume automatically on failed chunk up to maximum retry
options.
Included option to handle retry upload through UI (User Interface).
Support to cancel the request while uploading a file is added.
102
Common
Bug Fixes
Resolved api comments issue.
103
DropDownList
Breaking Changes
Resolved floatLabelType and sortOrder enumeration issue.
104
Common
Breaking Changes
Datamanager selector name changes from e-datamanager to e-data-manager .
105
Common
Bug Fixes
Resolved newtonsoft incompatible version warning.
106
Common
Essential JS 2 for ASP.NET Core and ASP.NET MVC is now available. It is a modern enterprise
UI toolkit that has been built from the ground up to be lightweight, responsive, modular, and
touch-friendly. All the component assemblies are published to NuGet.org as a public NuGet
package for your convenience and ease of setup. It comes with following list of components:
Chart
Maps
Circular Gauge
Linear Gauge
Grid
Schedule
Calendar
Autocomplete
Button
Check Box
Radio Button
Split Button
Drop-down Button
Combo Box
Date Picker
Date-Range Picker
Date-Time Picker
Drop-Down List
Form Validator
Multiselect Drop-Down
Masked Text Box
Numeric Text Box
Slider
Text Boxes
Time Picker
Uploader
List View
Dialog
Tooltip
Card
Navigation
Sidebar
Tree View
Tab
107
Toolbar
Context Menu
Accordion
Pager
Schedule
Schedule is an event calendar which facilitates user with the common Outlook-calendar features,
thus allowing the users to plan and manage their appointments and its time in an efficient way.
Views - Schedule is now availed with 6 different view modes – day, week, work week,
month, agenda and month agenda. It is possible to configure view-based settings on each
view mode. The Week view is set as active view by default.
Data binding - Seamless data binding with various client-side and remote data sources thus
allowing the data to load on demand by default to reduce the data transfer and loading time.
Recurrence - Allows the user to repeat a set of events on a daily, weekly, monthly, or yearly
basis.
Template - The key elements like events, date header, work cells and event tooltip comes
with the default template support which allows the flexible end-user customization to embed
any kind of text, images, or styles to it.
Time zone - Regardless of whatever time zone your system follows, Schedule supports
setting your own required time zone value to it as well as to each event – thus allowing the
events to display on its exact local time.
Customizable working days and hours - Users can set specific work hour range which is
visually differentiated with active colour. Also, the working days collection can be customized
with specific days, so that the remaining days will be considered as weekend.
Custom editor template - Template option is availed for event editor, thus allowing the
users to add their own custom editor design and also provides option to add additional fields
onto the default event editor.
Adaptive rendering - Adapts with optimal user interfaces for mobile and desktop form-
factors, thus helping the user’s application to scale elegantly across all the form-factors
without any additional effort.
Keyboard interaction - All the common actions such as traversing through the
appointments, multiple cell selection, add/edit/delete the appointments, navigate to other
views, dates and much more can be performed through keyboard inputs.
Localization - All the static text and date content can be localized to any desired language.
Also, it can be displayed with appropriate time mode and date-format as per the localized
language.
RTL - Supports displaying the component to display in the direction from right to left.
108
Breaking Changes
The below API types are corrected from 16.2.41 version of Essential JS 2.
109
Border object CircularGaugeBorder
namespace
ListView ListView Lists
changed
110
Tooltip IsSticky object bool
111
Overview
The ButtonGroup is a pure CSS component that groups the series of buttons together in a
vertical or horizontal manner. It supports checkbox and radio type ButtonGroup.
Key features
ButtonGroup types
Predefined styles
Orientation
Selection
Nesting
112
Getting Started
This section briefly explains about how to include a simple ButtonGroup in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Render()
@Html.EJS().Button("css").Content("CSS").Render()
@Html.EJS().Button("javacript").Content("Javascript").Render()
</div>
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Render()
@Html.EJS().Button("css").Content("CSS").Render()
@Html.EJS().Button("javacript").Content("Javascript").Render()
113
</div>
Orientation
ButtonGroup can be arranged in a vertical and horizontal orientation. By default, it is horizontally
aligned.
Vertical Orientation
ButtonGroup can be aligned vertically by using the built-in CSS class e-vertical to the target
element.
razor
default.cs
114
Types and Styles
This section explains about different types and styles of ButtonGroup.
ButtonGroup types
Outline ButtonGroup
An Outline ButtonGroup has a border with transparent background. To create Outline
ButtonGroup, e-outline class should be added to the target element and to each button
elements using CssClass property.
razor
default.cs
ButtonGroup does not have support for flat and round types.
ButtonGroup styles
The Essential JS 2 ButtonGroup has the following predefined styles. This can be achieved by
adding corresponding class name in each button elements using CssClass property.
Class Description
115
e-warning Used to represent an action with caution.
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("view").Content("View").CssClass('e-info').Render()
@Html.EJS().Button("edit").Content("Edit").Render()
@Html.EJS().Button("delete").Content("Delete").CssClass('e-danger').Render()
</div>
Predefined ButtonGroup styles provide only the visual indication. So, ButtonGroup content
should define the ButtonGroup style for the users of assistive technologies such as screen
readers.
116
Selection and Nesting
Selection
Single selection
ButtonGroup supports radio type selection in which only one button can be selected. This can be
achieved by adding input element along with id attribute with its corresponding label along with
for attribute inside the target element. In this ButtonGroup, the type of the input element should
be radio and e-btn is added to the label element.
razor
default.cs
<div class='e-btn-group'>
<input type="radio" id="radioleft" name="align" value="left" />
<label class="e-btn" for="radioleft">Left</label>
<input type="radio" id="radiomiddle" name="align" value="middle" />
<label class="e-btn" for="radiomiddle">Center</label>
<input type="radio" id="radioright" name="align" value="right"/>
<label class="e-btn" for="radioright">Right</label>
</div>
Multiple selection
ButtonGroup supports checkbox type selection in which multiple button can be selected. This can
be achieved by adding input element along with id attribute with its corresponding label along
with for attribute inside the target element. In this ButtonGroup, the type of the input element
should be checkbox and e-btn is added to the label element.
razor
default.cs
<div class='e-btn-group'>
117
<input type="checkbox" id="checkbold" name="font" value="bold"/>
<label class="e-btn" for="checkbold">Bold</label>
<input type="checkbox" id="checkitalic" name="font" value="italic" />
<label class="e-btn" for="checkitalic">Italic</label>
<input type="checkbox" id="checkline" name="font" value="underline"/>
<label class="e-btn" for="checkline">Underline</label>
</div>
Nesting
Nesting with other components can be possible in ButtonGroup. The following components can
be nested in ButtonGroup.
DropDownButton
SplitButton
DropDownButton
To initialize DropDownButton component refer DropDownButton Getting Started documentation .
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Render()
@Html.EJS().Button("css").Content("CSS").Render()
@Html.EJS().Button("javacript").Content("Javascript").Render()
@Html.EJS().DropDownButton("element").Content("More").Items((IEnumerable<object>)Vi
ewBag.items).Render()
</div>
118
});
items.Add(new
{
text = "Learn PHP"
});
items.Add(new
{
text = "Learn Bootstrap"
});
ViewBag.items = items;
return View();
}
SplitButton
To initialize SplitButton component refer SplitButton Getting Started documentation .
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("Cut").Content("Cut").Render()
@Html.EJS().Button("Copy").Content("Copy").Render()
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).Render()
</div>
119
}
120
Accessibility
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. ButtonGroup provides
built-in compliance with WAI-ARIA specifications. It helps the people with disabilities by providing
information about the widget for assistive technology in the screen readers. ButtonGroup
component contains the group role.
Properties Functionality
role Indicates the group for the container that holds two or more buttons.
Keyboard interaction
Normal behavior
razor
default.cs
<h5>Normal behavior</h5>
<div class='e-btn-group' role='group'>
@Html.EJS().Button("html").Render()
121
@Html.EJS().Button("css").Render()
@Html.EJS().Button("javacript").Render()
</div>
<h5>Checkbox type behavior</h5>
<div class='e-btn-group' role='group'>
<input type="checkbox" id="checkbold" name="font" />
<label class="e-btn" for="checkbold">Bold</label>
<input type="checkbox" id="checkitalic" name="font" />
<label class="e-btn" for="checkitalic">Italic</label>
<input type="checkbox" id="checkunderline" name="font" />
<label class="e-btn" for="checkunderline">Underline</label>
</div>
<h5>Radiobutton type behavior</h5>
<div class='e-btn-group' role='group'>
<input type="radio" id="radioleft" name="align" />
<label class="e-btn" for="radioleft">Left</label>
<input type="radio" id="radiomiddle" name="align" />
<label class="e-btn" for="radiomiddle">Center</label>
<input type="radio" id="radioright" name="align" />
<label class="e-btn" for="radioright">Right</label>
</div>
122
How to
Using createButtonGroup method, the Button options, selector, and cssClass is passed and the
corresponding classes is added to the elements.
The following example illustrates how to create ButtonGroup using createButtonGroup method
for basic, checkbox, and radio type behaviors.
razor
default.cs
<h5>Normal behavior</h5>
<div id='basic'>
<button></button>
<button></button>
<button></button>
</div>
<h5>Checkbox type behavior</h5>
<div id='checkbox'>
<input type="checkbox" id="checkbold" name="font" value="bold"/>
<input type="checkbox" id="checkitalic" name="font" value="italic"/>
<input type="checkbox" id="checkundeline" name="font" value="underline"/>
</div>
<h5>Radiobutton type behavior</h5>
123
<div id='radio'>
<input type="radio" id="radioleft" name="align" value="left"/>
<input type="radio" id="radiomiddle" name="align" value="middle"/>
<input type="radio" id="radioright" name="align" value="right"/>
</div>
<script>
ej.splitbuttons.createButtonGroup('#basic', {
buttons: [
{ content: 'HTML' },
{ content: 'CSS' },
{ content: 'Javascript'}
]
});
ej.splitbuttons.createButtonGroup('#checkbox', {
buttons: [
{ content: 'Bold' },
{ content: 'Italic' },
{ content: 'Undeline'}
]
});
ej.splitbuttons.createButtonGroup('#radio', {
buttons: [
{ content: 'Left' },
{ content: 'Center' },
{ content: 'Right'}
]
});
</script>
If null value is passed in button options, then that particular button will be skipped from
processing in createButtonGroup util function.
razor
124
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("left").Content("Left").IconCss("e-icons e-left-icon").Render()
@Html.EJS().Button("middle").Content("Center").IconCss("e-icons e-middle-icon").Ren
der()
@Html.EJS().Button("right").Content("Right").IconCss("e-icons e-right-icon").Render
()
</div>
<style>
.e-btn-group {
margin: 25px 5px 20px 20px;
}
.e-left-icon::before {
content: '\e75e';
}
.e-right-icon::before {
content: '\e75f';
}
.e-middle-icon::before {
content: '\e74b';
}
</style>
The following example illustrates how to create ButtonGroup with rounded corner.
razor
default.cs
125
</div>
Enable RTL
ButtonGroup supports RTL functionality. This can be achieved by adding e-rtl class to the
target element.
The following example illustrates how to create ButtonGroup with RTL support.
razor
default.cs
Disable
Particular button
To disable a particular button in a ButtonGroup, disabled attribute should be added to
corresponding button element.
Whole ButtonGroup
To disable whole ButtonGroup, disabled attribute should be added to all the button elements.
The following example illustrates how to disable the particular and the whole ButtonGroup.
razor
default.cs
126
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Render()
@Html.EJS().Button("css").Content("CSS").Disabled(true).Render()
@Html.EJS().Button("javasript").Content("Javascript").Render()
</div>
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Disabled(true).Render()
@Html.EJS().Button("css").Content("CSS").Disabled(true).Render()
@Html.EJS().Button("javasript").Content("Javascript").Disabled(true).Render()
</div>
Enable ripple
Ripple can be enabled by importing rippleEffect method from ej2-base and initialize
rippleEffect with .e-btn-group element, and selector as e-btn .
razor
default.cs
<div class='e-btn-group'>
@Html.EJS().Button("html").Content("HTML").Render()
@Html.EJS().Button("css").Content("CSS").Render()
@Html.EJS().Button("javacript").Content("Javascript").Render()
</div>
<script>
ej.base.enableRipple(true);
var button = document.querySelector('.e-btn-group');
ej.base.rippleEffect(button, {selector: 'e-btn'});
</script>
127
Form submit
The name attribute of the input element is used to group the radio/checkbox type ButtonGroup.
When the radio/checkbox type are grouped in the form, the checked items value attribute will be
posted to the server on form submit that can be retrieved through the name. The disabled
radio/checkbox type value will not be sent to the server on form submit.
In the following code snippet, the radio type ButtonGroup is explained with male value as
checked. Now, the value that is in checked state will be sent on form submit.
razor
default.cs
<form>
<div class='e-btn-group'>
<input type="radio" id="male" name="gender" value="male" checked/>
<label class="e-btn" for="male">Male</label>
<input type="radio" id="female" name="gender" value="female"/>
<label class="e-btn" for="female">Female</label>
<input type="radio" id="transgender" name="gender" value="transgender"/>
<label class="e-btn" for="transgender">Transgender</label>
</div>
<button class='e-btn e-primary'>Submit</button>
</form>
<style>
.e-btn-group, button {
margin: 20px 5px 20px 20px;
}
</style>
The following example illustrates how to show selected state on initial render.
razor
default.cs
128
<div class='e-btn-group'>
<input type="checkbox" id="checkbold" name="font" value="bold" checked/>
<label class="e-btn" for="checkbold">Bold</label>
<input type="checkbox" id="checkitalic" name="font" value="italic" />
<label class="e-btn" for="checkitalic">Italic</label>
<input type="checkbox" id="checkline" name="font" value="underline"/>
<label class="e-btn" for="checkline">Underline</label>
</div>
129
Overview
The purpose of this document is to build and run a simple Essential JS 2 application in ASP.NET
Core and, ASP.NET MVC.
130
Localization
Localization library allows you to localize the text content of the Essential JS 2 component.
Loading translations
To load translation object in your application use load function of L10n class.
<script>
ej.base.L10n.load({
'fr-BE': {
'Button': {
'id': 'Numéro de commande',
'date':'Date de commande'
}
}
});
</script>
<script>
ej.base.L10n.load({
'fr-BE': {
'Button': {
'id': 'Numéro de commande',
'date':'Date de commande'
}
}
});
ej.base.setCulture('fr-BE');
</script>
Note: Before changing a culture globally, ensure that locale text for the concerned culture is
loaded through L10n.load function.
131
Internationalization
The Internationalization library provides support for formatting and parsing date and number
objects using the official Unicode CLDR JSON data. The en-US locale is set as default culture
and USD is set as default currencyCode for all Essential JS 2 components.
ca-gregorian cldr/main/en/ca-gregorian.json
timeZoneNames cldr/main/en/timeZoneNames.json
numbers cldr/main/en/numbers.json
numberingSystems cldr/supplemental/numberingSystems.json
currencies cldr/main/en/currencies.json
<script>
ej.base.loadcldr(enNumberData, entimeZoneData);
</script>
132
Setting Global Culture
<script>
ej.base.setCulture('ar');
</script>
<script>
ej.base.setCurrencyCode('QAR');
</script>
Note: If global culture is not set then en-US is set as default locale and USD is set as
default currency code.
Manipulating Numbers
No Properties Description
133
Indicates whether to enable the group separator or
6 useGrouping
not . By default grouping value will be true.
Format
Specifier Description Input
Output
Percent specifier
denotes the instance.formatNumber (1,
% ‘0100 %’
percentage type {format: '0000 %' })
format.
134
Denotes separate
instance.formatNumber (-120,
; formats for positive, ‘(120.00)’
negative and zero {format: '###.##;(###.00);-0'});
values.
Denotes the
'String' characters enclosed
instance.formatNumber (-123.44,
(single within single Quote(') ‘123.44 @’
{format: "####.## '@'"})
Quotes) to be replaced in the
resultant string.
Note: If custom format pattern is specified other NumberFormatOptions properties will not
be considered.
Number formatting
getNumberFormat
The getNumberFormat method which will return a function that formats given number based on
the NumberFormatOptions specified.
<script>
var intl = new ej.base.Internationalization();
var nFormatter = intl.getNumberFormat({ skeleton: 'C3', currency: 'USD',minimumInte
gerDigits:8});
var formattedValue = nFormatter(1234545.65)
document.querySelector('.result').innerHTML = formattedValue;
</script>
formatNumber
The formatNumber method which takes two arguments numeric value and
NumberFormatOptions and returns the formatted string.
<script>
var intl = new ej.base.Internationalization();
var formattedString = intl.formatNumber(12345.65, { format:'C5' , useGrouping: false
,
minimumSignificantDigits:1, maximumSignificantDigits:3 });
document.querySelector('.result').innerHTML = formattedString;
</script>
Parsing
getNumberParser
135
The getNumberParser method which will return a function that parses given string based on the
NumberFormatOptions specified.
<script>
var intl = new ej.base.Internationalization();
var nParser = intl.getNumberParser({ format:'P2' , useGrouping: false});
var val = nParser('123567.45%');
document.querySelector('.result').innerHTML = val + '';
</script>
parseNumber
The parseNumber method which takes two arguments the string value, NumberFormatOptions
and returns the numeric value.
<script>
var intl = new ej.base.Internationalization();
var val = intl.parseNumber('$01,234,545.650', { format: 'C3', currency: 'USD', mini
mumIntegerDigits: 8 });
document.querySelector('.result').innerHTML = val + '';
</script>
Manipulating DateTime
Options Descriptions
skeleton Specifies the format in which the dateTime format will process
136
skeleton Option input Format Output
Additional skeletons
Apart from the standard date type formats additional format are supported by using the additional
skeletons given in below table.
d {skeleton:'d'} 7
E {skeleton:'E'} Mon
Ed {skeleton:'Ed'} 7 Mon
137
Gy {skeleton:'Gy' } 2016 AD
h {skeleton:'h'} 12 PM
H {skeleton:'H'} 12
hm {skeleton:'hm'} 12:59 PM
Hm {skeleton:'Hm'} 12:59
M {skeleton:'M'} 11
Md {skeleton:'Md'} 11/7
ms {skeleton:'ms'} 59:13
y {skeleton:'y' } 2016
yM {skeleton:'yM' } 11/2016
Custom Formats
To use the custom date and time formats we need to specify the date/time pattern directly in the
format property. Custom format string must contain one or more of the following standard
date/time symbols
Symbols Description
138
G Denotes the era in the date
h/H Denotes the hour. h for 12 hour and H for 24 hours format.
m Denotes minutes.
s Denotes seconds.
' (single To display words in the formatted date you can specify the words with in
quotes) the single quotes
<script>
var intl = new ej.base.Internationalization();
var formattedString = intl.formatDate(new Date('1/12/2014 10:20:33'), { format: '\'
year:\'y' \'month:\' MM' });
//Output: "year:2014 month:01"
</script>
Note: If format property is given in options other properties are not considered.
Formatting
getDateFormat
The getDateFormat method which will return a function that formats given date object based on
the DateFormatOptions specified.
<script>
var intl = new ej.base.Internationalization();
var dFormatter = intl.getDateFormat({ skeleton: 'full', type: 'dateTime' });
var formattedString = dFormatter(new Date('1/12/2014 10:20:33'));
document.querySelector('.result').innerHTML = formattedString;
</script>
formatDate
139
The formatDate method which takes two arguments date object, DateFormatOptions and
returns the formatted string.
<script>
var intl = new ej.base.Internationalization();
var date = new Date();
var formattedString = intl.formatDate(new Date('1/12/2014 10:20:33'), { skeleton:
'GyMMM' });
document.querySelector('.result').innerHTML = formattedString;
</script>
Parsing
getDateParser
The getDateParser method which will return a function that parses given string based on the
DateFormatOptions specified.
<script>
var intl = new ej.base.Internationalization();
var dParser = intl.getDateParser({skeleton: 'full', type: 'dateTime'});
var val = dParser('Friday, November 4, 2016 at 1:03:04 PM GMT+05:30');
document.querySelector('.result').innerHTML = val.toString();
</script>
parseDate
The parseDate method which takes two arguments string value, DateFormatOptions and
returns the date Object.
<script>
var intl = new ej.base.Internationalization();
var val = intl.parseDate('11/2016',{skeleton: 'yM'});
document.querySelector('.result').innerHTML = val.toString();
</script>
140
Right-To-Left
Right To Left (RTL) can be enabled for Essential JS 2 components by calling enableRtl with
true . This will render all the Essential JS 2 components in right to left direction. Find the code
snippet for this below.
<script>
// Enables Right to left alignment for all controls
ej.base.enableRtl(true);
</script>
razor
@Html.EJS().Button("normalbtn").EnableRtl(true).Content("Normal").Render()
141
Overview
The Button is a graphical user interface element that triggers an event on its click action. It can
contain a text, an image, or both.
Key Features
Button types .
Predefined Button styles .
Supports text and icon in the Button .
142
Getting Started
This section briefly explains about how to include a simple Button in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
@Html.EJS().Button("element").Content("Button").Render()
razor
default.cs
@Html.EJS().Button("element").Content("Button").Render()
143
Change Button type
To change the default Button to flat Button, set the cssClass property to e-flat .
razor
flatbutton.cs
@Html.EJS().Button("element").Content("Button").CssClass("e-flat").Render()
144
Types and Styles
This section explains the different styles and types of Buttons.
Button styles
The Essential JS 2 Button has the following predefined styles that can be defined using the
cssClass property.
Class Description
razor
styles.cs
@section ControlsSection{
@Html.EJS().Button("primarybtn").Content("Primary").CssClass("e-primary").Render()
@Html.EJS().Button("successbtn").Content("Success").CssClass("e-success").Render()
@Html.EJS().Button("infobtn").Content("Info").CssClass("e-info").Render()
@Html.EJS().Button("warningbtn").Content("Warning").CssClass("e-warning").Render()
@Html.EJS().Button("dangerbtn").Content("Danger").CssClass("e-danger").Render()
@Html.EJS().Button("linkbtn").Content("Link").CssClass("e-link").Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
145
{
return View();
}
Predefined Button styles provide only the visual indication. So, Button content should define
the Button style for the users of assistive technologies such as screen readers.
Button types
The types of Essential JS 2 Button are as follows:
Basic types
Flat Button
Outline Button
Round Button
Toggle Button
Basic types
The basic Button types are explained below.
Type Description
Reset This Button resets all the controls to their initial values.
razor
basicbutton.cs
@section ControlsSection{
@Html.EJS().Button("submit").Type("submit").Content("Submit").Render()
@Html.EJS().Button("reset").Type("reset").Content("Reset").Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
146
public ActionResult BasicButton()
{
return View();
}
Flat Button
The Flat Button is styled with no background color. To create a flat Button, set the cssClass
property to e-flat .
Outline Button
An outline Button has a border with transparent background. To create an outline Button, set the
cssClass property to e-outline .
Round Button
A round Button is shaped like a circle. Usually, it contains an icon representing its action. To
create a round Button, set the cssClass property to e-round .
razor
buttontypes.cs
@section ControlsSection{
@Html.EJS().Button("flat").Content("Flat").CssClass("e-flat").Render()
@Html.EJS().Button("outline").Content("Outline").CssClass("e-outline").Render()
@Html.EJS().Button("round").IconCss("e-icons e-plus-icon").CssClass("e-round").IsP
rimary(true).Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
.e-plus-icon::before {
content: '\e823';
}
</style>
147
public ActionResult ButtonTypes()
{
return View();
}
Toggle Button
A toggle Button allows you to change between the two states. The Button is active in toggled
state and can be recognized through the e-active class. The functionality of the toggle Button
is handled by click event. To create a toggle Button, set the isToggle property to true . In the
following code snippet, the toggle Button text changes to play/pause based on the state of the
Button with the use of click event.
razor
togglebutton.cs
@section ControlsSection{
@Html.EJS().Button("togglebtn").Content("Play").CssClass("e-flat").IconCss("e-icon
s e-play-icon").IsToggle(true).Render()
}
<style>
.e-play-icon::before {
content: '\e798';
}
.e-pause-icon::before {
content: '\e753';
}
</style>
<script>
148
public ActionResult ToggleButton()
{
return View();
}
Icons
The Button can have an icon to provide the visual representation of the action. To place the icon
on a Button, set the iconCss property to e-icons with the required icon CSS. By default, the
icon is positioned to the left side of the Button. You can customize the icon's position by using the
iconPosition property.
razor
buttonicon.cs
@section ControlsSection{
@Html.EJS().Button("iconbutton").Content("PREVIOUS").IconCss("e-icons e-prev-icon"
).Render()
@Html.EJS().Button("iconposbtn").Content("STOP").IconCss("e-icons e-open-icon").Re
nder()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
.e-open-icon::before {
content: '\e782';
}
.e-prev-icon::before {
content: '\e797';
}
</style>
149
The Essential JS 2 provides a set of icons that can be loaded by applying e-icons class
name to the element. You can also use third party icons on the Button using the iconCss
property.
Button size
The two types of Button sizes are default and small. To change the size of the default Button to
small Button, set the cssClass property to e-small .
razor
size.cs
@section ControlsSection{
@Html.EJS().Button("smallbtn").Content("SMALL").CssClass("e-small").Render()
@Html.EJS().Button("normalbtn").Content("NORMAL").Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
150
How To
The following section explains how to customize various aspects of the Button.
razor
blockbutton.cs
@section ControlsSection{
@Html.EJS().Button("blockbtn").Content("BLOCKBUTTON").CssClass("e-block").Render()
@Html.EJS().Button("primarybtn").Content("BLOCKBUTTON").CssClass("e-block").IsPrim
ary(true).Render()
@Html.EJS().Button("successbtn").Content("BLOCKBUTTON").CssClass("e-block e-succes
s").Render()
}
<style>
button {
margin: 25px 0;
}
</style>
151
corner of the Button can be customized through the e-custom class for all states (hover, focus,
and active).
razor
custombutton.cs
@section ControlsSection{
@Html.EJS().Button("custom").Content("CUSTOM").CssClass("e-custom").Render()
}
<style>
.e-custom {
border-radius: 0;
height: 30px;
width: 80px;
}
button {
margin: 25px 5px 20px 20px;
}
</style>
In the following sample, the height and width of the large button is customized as 50px and
120px and the height and width of the small button is customized as 30px and 25px .
razor
customsize.cs
152
@section ControlsSection{
@Html.EJS().Button("largebtn").Content("Large Button").CssClass("e-big-btn").Rende
r()
@Html.EJS().Button("smallbtn").IconCss("e-icons e-add-icon").CssClass("e-small-btn
").Render()
}
<style>
.e-big-btn {
height: 50px;
width: 120px;
}
.e-small-btn.e-icon-btn {
padding: 0 6px;
line-height: 24px;
}
button {
margin: 25px 5px 20px 20px;
}
.e-add-icon::before {
content: '\e823';
}
</style>
153
You can customize the appearance of the input and anchor elements using predefined styles
through the class property. In the following code snippet, the input element is customized as a
link Button by setting the e-btn e-link class, and the anchor element is customized as a
primary Button by setting the e-btn e-primary class.
razor
@section ControlsSection{
<div>
<input type="button" id="inputbtn" value="Input Button" class="e-btn e-link">
</div><br>
<div>
<a id="anchorbtn" class="e-btn e-primary" href="#">Google</a>
</div>
}
Repeat Button
The Repeat button is a type of Button in that the click event is triggered at regular time interval
from the pressed state till the released state.
The following example explains about how to achieve Repeat Button in mouse and touch events.
razor
repeatbutton.cs
@section ControlsSection{
<div class='btncontainer'>
@Html.EJS().Button("button").Content("Button").Render()
</div>
<div class='event' style="height:auto;">
<table title='Event Trace' style="width:100%">
<tbody>
<tr>
<th>Event Trace</th>
</tr>
<tr>
<td>
<div class="eventarea" style="height: 250px;overflow: auto">
<span id="eventlog" style="word-break: normal;"></span>
</div>
</td>
</tr>
<tr>
<td>
<div class="evtbtn" style="padding:20px 0 0 20px">
154
@Html.EJS().Button("clear").Content("Clear").Render()
</div>
</td>
</tr>
</tbody>
</table>
</div>
}
<style>
hr {
margin: 1px 10px 1px 0px;
border-top: 1px solid #eee;
}
.btncontainer {
float: left;
width: 40%;
}
.event {
float: right;
width: 60%;
border-left: 1px solid #D7D7D7;
}
#eventlog b {
color: #388e3c;
}
</style>
<script>
document.getElementById("clear").addEventListener('click', function () {
document.getElementById('eventlog').innerHTML = '';
});
document.getElementById("button").addEventListener('mousedown', function () {
event.preventDefault();
timeout = setInterval(clickEventHandler, 200);
});
document.getElementById("button").addEventListener('touchstart', function () {
event.preventDefault();
timeout = setInterval(clickEventHandler, 200);
});
document.getElementById("button").addEventListener('mouseup', function () {
clearInterval(timeout);
155
});
document.getElementById("button").addEventListener('touchend', function () {
clearInterval(timeout);
});
document.getElementById("button").addEventListener('click', function () {
appendSpanElement('Button click event triggered.<hr>');
});
function clickEventHandler(e){
appendSpanElement('Button click event triggered.<hr>');
}
function appendSpanElement(text){
var span = document.createElement('span');
span.innerHTML = text;
var log = document.getElementById('eventlog');
log.insertBefore(span, log.firstChild);
}
</script>
razor
disabledbutton.cs
@section ControlsSection{
@Html.EJS().Button("disabled").Content("Disabled").Disabled(true).Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
156
</style>
Right-To-Left
Button component has RTL support. This can be achieved by setting enableRtl as true.
The following example illustrates how to enable right-to-left support in Button component.
razor
rtl.cs
@section ControlsSection{
@Html.EJS().Button("rtl").Content("Settings").IconCss("e-icons e-setting-icon").En
ableRtl(true).Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
.e-setting-icon::before {
content: '\e7cf';
}
</style>
razor
tooltip.cs
@section ControlsSection{
@Html.EJS().Button("primarybtn").Title("Primary Button").Content("Button").IsPrima
ry(true).Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
razor
link.cs
@section ControlsSection{
@Html.EJS().Button("button").CssClass("e-link").Render()
}
<style>
button {
margin: 25px 5px 20px 20px;
}
158
document.getElementById("button").innerHTML = '<a href="https://www.google.com/" target
='_blank'>Go to Google</a>';
</style>
159
Overview
The Calendar is a graphical user interface component that displays a Gregorian Calendar, and
allows a user to select a date.
Key Features
The features of the Calendar are:
Date Range
Globalization
Customization
Calendar Views
Accessibility
160
Getting Started
This section briefly explains how to include a simple Calendar control in your ASP.NET MVC
application. You can refer to ASP.NET MVC Getting Started documentation page for system
requirements, and configure common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
razor
@Html.EJS().Calendar("calendar").Render();
razor
getting-started.cs
@Html.EJS().Calendar("calendar").Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
161
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
Here the Calendar allows you to select a date within the range from 5th to 27th of this month.
razor
daterange.cs
@Html.EJS().Calendar("calendar").Min(ViewBag.minDate).Max(ViewBag.maxDate).Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.minDate= new DateTime(DateTime.Now.Year,DateTime.Now.Month,05);
ViewBag.maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 27);
return View();
}
}
}
162
Date Range
Calendar provides an option to select a date value within a specified range by defining the min
and max properties. The min date should always be lesser than the max date. If the value of
min or max properties are changed through code behind, then update the value property to
be set within the specified range. Or else, if the value is out of specified date range and less than
min date, value property will be updated with min date or the value is higher than max date,
value property will be updated with max date.
The following example allows you to select a date within the range of 7th to 27th days in a month.
razor
daterange.cs
@Html.EJS().Calendar("element").Value(ViewBag.value).Min(ViewBag.minDate).Max(ViewBag.
maxDate).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.minDate= new DateTime(DateTime.Now.Year,DateTime.Now.Month,07);
ViewBag.maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 27);
ViewBag.value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 14);
return View();
}
}
}
163
Globalization
Globalization is the combination of internationalization and localization. You can adapt the
component to various languages by parsing and formatting the date or number
(Internationalization), and also add culture specific customization and translation to the text
(localization).
By default, Calendar date format, week and month names are specific to American English
culture. It utilizes the Essential JavaScript 2 Internationalization package to parse and
format the date object based on the culture by uses the official UNICODE CLDR JSON data.
To go with the different culture other than English , follow the below steps.
Install the CLDR-Data package by using the below command (it installs the CLDR JSON
data). To know more about CLDR-Data refer the CLDR-Data link.
Once the package installed, you can find the culture specific JSON data under the location
\node_modules\cldr-data .
Now use the loadCldr method to load the culture specific CLDR JSON data.
In ASP.NET MVC refer the culture files directly from \node_modules\cldr-data location. But in
ASP.NET Core, the static file contents are should present under wwwroot folder. For this,
manually copy the CLDR-Data from the node_modules folder and place inside the wwwroot
folder and refer from the \wwwroot\cldr-data location as like the below code examples
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../wwwroot/
cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
164
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
function loadCultureFiles(de) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node_mod
ules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
Before changing to a culture other than English , ensure that locale text for the concerned
culture is loaded through load method of L10n class.
razor
international.cs
@Html.EJS().Calendar("element").Render()
<script>
165
document.addEventListener('DOMContentLoaded', function () {
calendarObject = document.getElementById('calendar').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
"de": {
"calendar": {
"today": "heute"
}
}
});
loadCultureFiles('de');
calendarObject.locale = 'de';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax('location.origin + location.pathname + '/../node_mo
dules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
166
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
Right-To-Left
The Calendar supports right-to-left functionality for languages like Arabic, Hebrew, etc. To display
the text in the right-to-left direction, use enableRtl property.
The following example demonstrates the Calendar in Arabic culture with Right-To-Left
direction.
razor
rtl.cs
@Html.EJS().Calendar("element").EnableRtl(true).Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
calendarObject = document.getElementById('calendar').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
"en": {
"calendar": {
"today": "Today"
}
}
});
loadCultureFiles('ar');
calendarObject.locale = 'ar';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
167
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
168
Customization
Each day cell of the Calendar can be customized by using the renderDayCell event.
The following section demonstrates how to disable or highlight specific dates in a Calendar.
Disable weekends
You can disable weekends of every month in a Calendar by using the renderDayCell event. The
renderDayCell event offers the following arguments on each day cell creation to help you
disable the dates.
View Description
razor
customization.cs
@Html.EJS().Calendar("element").RenderDayCell("disableDate").Value(@ViewBag.value).Ren
der();
<script>
function disableDate(args) {
if (args.date.getDay() === 0 || args.date.getDay() === 6) {
args.isDisabled = true;
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
169
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTim
e.Now.Date);
return View();
}
}
}
You can customize the appearance of the Calendar by overriding the existing styles. The
following list of CSS class names are used to customize the Calendar component.
The following example highlights the World Health Day (every 7th April) and World Forest Day
(every 21st March) by using the custom icon and ToolTip.
razor
cellformat.cs
170
@Html.EJS().Calendar("element").Value(@ViewBag.value).RenderDayCell("customDates").Rend
er()
<script>
var addClass = ej.base.addClass;
function customDates(args) {
/*Date need to be customized*/
var span;
if (args.date.getDate() === 7 && args.date.getMonth() == 3) {
span = document.createElement('span');
span.setAttribute('class', 'e-icons highlight');
addClass([args.element], ['special']);
args.element.setAttribute('title', 'World health day !');
args.element.setAttribute('data-val', 'World health day !');
args.element.appendChild(span);
}
if (args.date.getDate() === 21 && args.date.getMonth() == 2) {
span = document.createElement('span');
span.setAttribute('class', 'e-icons highlight');
addClass([args.element], ['special']);
args.element.setAttribute('title', 'World forest day !');
args.element.setAttribute('data-val', 'World forest day !');
args.element.appendChild(span);
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult SpecialDates()
{
ViewBag.value = new DateTime(2017, 3, 10);
return View();
}
171
}
}
172
Calendar Views
The Calendar has the following pre-defined views that provide a flexible way to navigate back
and forth when selecting dates.
View Description
When view is defined to the start property of the Calendar, it allows you to set the initial view
on rendering.
The following example demonstrates how to set the year as the start view of the Calendar.
razor
views.cs
@Html.EJS().Calendar("element").Value(@ViewBag.value).Start(Syncfusion.EJ2.Calendar.Cal
endarView.Year).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year, DateTime.Now.Month,DateTime
.Now.Date );
return View();
}
}
}
173
View restriction
By defining the start and depth property with the different view, drill- down and drill-up views
navigation can be limited to the user. Calendar views will be drill-down up to the view which is set
in depth property and drill-up up to the view which is set in start property.
The following example displays the Calendar in decade view, and allows you to select a date in
month view.
Depth view should always be smaller than the start view. If the depth and start views
are the same, then the Calendar view remains unchanged.
razor
restriction.cs
@Html.EJS().Calendar("element").Value(@ViewBag.value).Depth(Syncfusion.EJ2.Calendar.Cal
endarView.Year).Start(Syncfusion.EJ2.Calendar.CalendarView.Decade).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year, DateTime.Now.Month,DateTime
.Now.Date );
return View();
}
}
}
174
Accessibility
The web accessibility makes web content and web applications more accessible for disabled
people. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies.
It helps disabled persons by providing information about the widget for assistive technology in the
screen readers. Calendar component contains grid role and grid cell for each day cell.
Aria-label: This attribute provides text labels for an object for the previous and next month's
elements. It helps the screen reader object to read.
Role: Gives information to assistive technologies about how to handle each element in a
widget.
Grid-cell: Defines the individual cell that can be focussed and selected.
Keyboard interaction
You can use the following keys to interact with the Calendar. This component implements
keyboard navigation support by following the WAI-ARIA practices.
Press To do this
175
Page Down Focuses the same date of the next month.
Shift + Page Down Focuses the same date for the next year.
Control + Upper Moves to the inner level of view like month to year and year to
Arrow decade.
Control + Down Moves out from the depth level view like decade to year and
Arrow year to month.
razor
accessibility.cs
@Html.EJS().Calendar("element").Render()
<script>
document.addEventListener('keyup', function (e) {
if (e.altKey && e.keyCode === 84) {
// press alt+t to focus the control.
var calendarObj = document.getElementById("element").ej2_instances[0];
calendarObj.element.querySelectorAll('.e-content table')[0].focus();
}
})
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
176
return View();
}
}
}
177
How To
The following section explains how to customize various aspects of Calendar.
1. To the created event of the Calendar, add the required elements to make clear and today
buttons visible. In the following example, div with two Essential JS 2 button components are
used.
2. When the e-footer class is used, the div tag acts as the footer.
3. Using these two buttons, today's date can be selected and cleared.
4. Bind the required event handler to the button tags to update the value.
razor
settoday.cs
@Html.EJS().Calendar("element").Created("onCreate").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('.e-footer-container .e-clear').addEventListener('click', fu
nction () {
calendarObject = document.getElementById('calendar').ej2_instances[0];
calendarObject.value = new Date();
calendarObject.dataBind();
});
});
function onCreate() {
//creates the custom element for clear button.
var clearBtn = document.createElement('button');
var footerElement = document.getElementsByClassName('e-footer-container')[0];
clearBtn.className = 'e-btn e-clear e-flat';
clearBtn.textContent = 'Clear';
footerElement.prepend(clearBtn);
this.element.appendChild(footerElement);
}
</script>
<style>
178
.e-clear { /* csslint allow: adjoining-classes*/
margin-right: 81px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
Using the styles below, you can bring the dates of other months to visibility from its hidden state.
razor
179
showdates.cs
@Html.EJS().Calendar("element").Render()
<style>
display: block;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
180
The following example demonstrates how to skip a month in the Calendar while clicking the
previous and next icons. In the example below, the navigated event is used to skip a month
with navigateTo method.
razor
skipmonth.cs
@Html.EJS().Calendar("element").Navigated("onNavigate").Render()
<script>
function onNavigate(args) {
var date;
if ((args.event.currentTarget).classList.contains('e-next')) {
//Increments the month while clicking the next icon.
date = new Date(args.date.setMonth(args.date.getMonth() + 1));
}
if ((args.event.currentTarget).classList.contains('e-prev')) {
//Decrements the month while clicking the previous icon.
date = new Date(args.date.setMonth(args.date.getMonth() - 1));
}
if (args.view == 'month') {
calendarObject = document.getElementById('element').ej2_instances[0];
calendarObject.navigateTo('month', date);
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
181
Render the Calendar with week numbers
You can enable weekNumbers in the Calendar by using the weekNumber property.
razor
weeknumber.cs
@Html.EJS().Calendar("element").WeekNumber(true).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
The following example shows the Calendar with Tuesday as the first day of the week.
razor
firstday.cs
182
@Html.EJS().Calendar("element").FirstDayOfWeek(2).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class CalendarController : Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
183
Overview
The Card is a small container in which user can show defined content in specific structure. It is a
pure CSS component built with markup and styles.
Key features
1. Header: Header supports to include title, subtitle along with image.
2. Images and Title: Support to include images with customizable caption positions in it.
3. Action Buttons: Supports to add buttons within the card either in vertical or horizontal
alignment.
4. Horizontal Card: Allows to align card elements horizontally and also allows to stack the
content vertically within horizontal alignment.
184
Getting Started
This section briefly explains about how to include a simple Card in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
You can include heading inside the Card header by adding a div element with e-card-
header-caption class, and also content will be added by adding element with e-card-
content . For detailed information, refer to the Header and Content.
razor
controller.cs
/*Razor CodeBlock*/
185
</div>
<div class="e-card-content">
Advanced UWP: Communicating with Windows 10 and Other Apps, the second
in a five-part series written by Succinctly series
author Matteo Pagani. To download the complete white paper, and other p
apers in the series, visit
the White Paper section of Syncfusion’s Technology Resource Portal.
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
186
Header and Content
Header
The Card can be created with header title, sub title and images. For adding header you need to
create div element with the class e-card-header added.
Card provides below elements and corresponding class definitions to include header.
Elements Description
Class Description
e-card-header- To group the title and subtitle within the header which acts as
caption wrapper.
Place the div element with e-card-header-title class inside the header caption for
adding main title.
Place the div element with e-card-sub-title class inside the header caption element for
adding sub-title.
Image
Card header has an option for adding images in the header. It is aligned with either before or
after the header based on the HTML element positioned in the header structure.
The header image can be added by creating a div element with e-card-header-image
class which can be placed before or after the header caption wrapper element.
razor
187
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
Content
Content in Card holds texts, images, links and all possible HTML elements. Its adaptable within
the Card root element.
razor
controller.cs
188
/*Razor CodeBlock*/
@section ControlsSection {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
189
Images and Divider
Images
The Card supports to include images within the elements, you can add image as direct element
anywhere inside card root by adding the e-card-image class to div element. Using the class
defined, you can write CSS styles to load images to that element.
Title
Card image is supported to include a title or caption for the image. By default, Title is placed over
the image on left-bottom position with overlay.
razor
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
<div class="e-card">
<div class="e-card-image">
<div class="e-card-title">JavaScript </div>
</div>
<div class="e-card-content"> JavaScript Succinctly was written to give read
ers an accurate, concise examination of JavaScript objects and their supporting nuances
, such as complex values, primitive values, scope, inheritance, the head object, and mo
re. </div>
</div>
190
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
Divider
Divider used to separate the elements inside the card. You can add divider inside the card
elements to separate it.
Place the div element with e-card-separator class inside the card element for adding a
divider.
razor
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
191
upon commerce and etc.,
</div>
<div class="e-card-separator"></div>
<div class="e-card-content">
Malaysia is one of the Southeast Asian countries, on a peninsula of the
Asian continent, to a certain extent; it can be recognized
as part of the Asian continent.
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
192
Action Buttons
You can include Action buttons within the Card and customize them. Action button is a div
element with e-card-actions class followed by button tag or anchor tag within the card root
element.
For adding action buttons you can create button or anchor tag with e-card-btn class within
the card action element.
Vertical
By default, action buttons positioned in horizontal alignment , and also it can be aligned to show
in vertical alignment by adding e-card-vertical class.
razor
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
193
<button class="e-card-btn">LIKE</button>
<button class="e-card-btn">SHARE</button>
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
194
Horizontal Card
By default, all the card elements are aligned vertically one after the other as in the DOM. You can
achieve the element to align horizontally as well by adding the class e-card-horizontal in the
root card element.
Stacked cards
An horizontally aligned card can push a specific column to align vertical using e-card-
stacked class. This will align the stacked section vertically aligned differentiating from
horizontal layout.
Class Description
razor
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
195
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public partial class CardController : Controller
{
public IActionResult htmldom()
{
return View();
}
}
}
196
How To
razor
controller.cs
/*Razor CodeBlock*/
<script>
function changed(e) {
let cardEle = document.querySelector('.e-card');
let titleEle = cardEle.querySelector('.e-card-image .e-card-title');
titleEle.className = ''
titleEle.classList.add('e-card-title');
titleEle.classList.add(e.value.toLowerCase());
}
</script>
@section ControlsSection {
<div class="e-card">
<div class="e-card-image">
<div class="e-card-title">Node.js</div>
</div>
<div class="e-card-content">
Node.js is a wildly popular platform for writing web applications t
hat has revolutionized web development in many ways, enjoying
support across the open source community as well as industry.
</div>
</div>
<div id="default" style='padding-top:75px;'>
@Html.EJS().DropDownList("games").Placeholder("Select Position").DataSource((IEnumer
able <object>)ViewBag.dataSource).change("changed").Render()
</div>
197
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public class DropDownListController : Controller
{
public IActionResult simpledata()
{
ViewBag.dataSource = new string[] { "BottomLeft", "TopLeft", "TopRight", "B
ottomRight"};
return View();
}
}
}
razor
controller.cs
/*Razor CodeBlock*/
@section ControlsSection {
using System;
using System.Collections.Generic;
198
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
public class ListViewController : Controller
{
public IActionResult arraydata()
{
List<object> listdata = new List<object>();
listdata.Add(new { todoList = "Pay Bills" });
listdata.Add(new { todoList = "Call Chris" });
listdata.Add(new { todoList = "Meet Andrew" });
listdata.Add(new { todoList = "Visit Manager" });
listdata.Add(new { todoList = "Customer Meeting" });
ViewBag.dataSource = listdata;
return View();
}
}
}
199
Overview
The Chart control is used to visualize the data with user interactivity and provides customizing
options to configure the data visually. It can bind data from datasource such as array of JSON
objects , OData web services or DataManager . All chart elements are rendered using Scalable
Vector Graphics (SVG).
Key Features
Supports 16 interactive chart types starting from line series to stacking series.
Support to bind local and remote datasource.
Supports multiple axes, and able to plot data with different data types such as numbers,
datetime, logarithmic and string.
Supports interactive features like zooming, crosshair, trackball, tooltip and selection.
200
Getting Started
System Requirements
To work with ASP.NET Core 1.0, you need to make sure is whether you have installed the
following software on your machine
DotNetCore 2.0
Select the Tools->Nuget Package Manager->Package Manager settings the dialog window
will open.
Navigate to the Nuget Package Manager->Package Sources from the options dialog.
Select the newly created Package Source and rename the source name using the Name
input box.
https://api.nuget.org/v3/index.json
Adding TagHelpers
Now open _viewImports.cshtml file from the views folder and add the following namespace
for components references and Tag Helper support.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
201
@addTagHelper *, Syncfusion.EJ2
Adding ScriptManager
Add ScriptManager to the bottom of the layout.cshtml page. The ScriptManager used to
place our control initialization script in the page.
<ej-scripts> </ej-scripts>
Enable Legend
You can use legend for the chart by setting the visible property to true in legendSettings
object.
razor
legend.cs
202
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
203
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
razor
datalabel.cs
204
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
Enable Tooltip
205
The tooltip is useful when you cannot display information by using the data labels due to space
constraints. You can enable tooltip by setting the enable property as true in tooltip object.
razor
tooltip.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
206
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
207
Working with Data
Chart can visualise data bound from local or remote data.
Local Data
You can bind a simple JSON data to the chart using dataSource property in series. Now map
the fields in JSON to xName and yName properties.
razor
local-data.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
ChartArea(area => area.Border(ViewBag.chartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("x").YNam
e("y").DataSource("series1").Name("Product X").Add();
}).
PrimaryXAxis(px => px.Skeleton("y").Title("Years").MajorGridLines(ViewBag.majorGridL
ines).
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift).
LabelFormat("y")).
PrimaryYAxis(py => py.Title("Price").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
MinorTickLines(ViewBag.minorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None).
LabelFormat("${value}").EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.
Shift).
Title("Profit")).
Title("Stock Price Analysis").
LegendSettings(lg => lg.Visible(true)).Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > .5) {
value += Math.random();
208
}
else {
value -= Math.random();
}
point1 = { x: new Date(1960, (i + 1), i), y: Math.round(value) };
series1.push(point1);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult LocalData()
{
return View();
}
}
}
Remote Data
You can also bind remote data to the chart using DataManager . The DataManager requires
minimal information like webservice URL, adaptor and crossDomain to interact with service
endpoint properly. Assign the instance of DataManager to the dataSource property in series and
map the fields of data to xName and yName properties. You can also use the query property of
the series to filter the data.
razor
remote-data.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("Assignee").Marker(ViewBag.marker).
YName("Estimate").DataSource("dataManager").
209
Query("query").
Name("Story Point").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: RemoteData
public ActionResult RemoteData()
{
ViewBag.labelStyle = new
{
color = "transparent"
};
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.animation = new { enable = false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.marker = new
{
210
dataLabel = new
{
visible = true,
position = "Top",
font = new { fontWeight = "600", color = "#ffffff" }
}
};
return View();
}
}
}
Empty points
The Data points that uses the null or undefined as value are considered as empty points.
Empty data points are ignored and not plotted in the Chart. When the data is provided by using
the points property, By using emptyPointSettings property in series, you can customize the
empty point. Default mode of the empty point is Gap .
razor
empty-points.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").ChartArea(ca => ca.Border(ViewBag.border))
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column)
.Name("Profit")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.Width(2)
.EmptyPointSettings(ViewBag.emptyPointSettings)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.Title("Product")
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.Interval(1)
)
.Title("Annual Product-Wise Profit Analysis")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
211
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: EmptyPointChart
public ActionResult EmptyPointChart()
{
List<EmptyPointChartData> chartData = new List<EmptyPointChartData>
{
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10 };
ViewBag.emptyPointSettings = new
{
mode="Average"
};
return View();
}
public class EmptyPointChartData
{
public string xValue;
public Nullable<double> yValue;
}
}
}
212
Customizing empty point
Specific color for empty point can be set by fill property in emptyPointSettings . Border for a
empty point can be set by border property.
razor
custom-emptypoint.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").ChartArea(ca => ca.Border(ViewBag.border))
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column)
.Name("Profit")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.Width(2)
.EmptyPointSettings(ViewBag.emptyPointSettings)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.Title("Product")
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.Interval(1)
)
.Title("Annual Product-Wise Profit Analysis")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: EmptyPointChart
public ActionResult EmptyPointChart()
213
{
List<EmptyPointChartData> chartData = new List<EmptyPointChartData>
{
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10 };
ViewBag.emptyPointSettings = new
{
mode="Average",
fill="green",
border= new { color: "black", width: 2}
};
return View();
}
public class EmptyPointChartData
{
public string xValue;
public Nullable<double> yValue;
}
}
}
214
Chart Dimensions
razor
size.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.Minimum(2)
.Maximum(5).
.Interval(2)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
215
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
In Pixel
razor
pixel.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.Minimum(2)
.Maximum(5).
216
.Interval(2)).
Title("Olympic Medal Counts - RIO").Size('450') .Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
In Percentage
By setting value in percentage, chart gets its dimension with respect to its container. For
example, when the height is ‘50%’, chart renders to half of the container height.
razor
percentage.cs
217
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.Minimum(2)
.Maximum(5).
.Interval(2)).
Title("Olympic Medal Counts - RIO").Size("75%").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
218
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Note: When you do not specify the size, it takes 450px as the height and window size as
its width.
219
Category Axis
Category axis are used to represent, the string values instead of numbers.
razor
column.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
220
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Labels Placement
By default, category labels are placed between the ticks in an axis, this can also be placed on
ticks using labelPlacement property.
razor
placement.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
221
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Range
Range of the category axis can be customized using minimum , maximum and interval
property of the axis.
razor
range.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
222
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.Minimum(2)
.Maximum(5).
.Interval(2)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
index.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
224
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
List<ColumnChartData> chartData1 = new List<ColumnChartData>
{
new ColumnChartData { x= "USA1", yValue= 46 },
new ColumnChartData { x= "GBR1", yValue= 27 },
new ColumnChartData { x= "CHN1", yValue= 26 },
new ColumnChartData { x= "UK1", yValue= 26 },
new ColumnChartData { x= "AUS1", yValue= 26 },
new ColumnChartData { x= "IND1", yValue= 26 },
new ColumnChartData { x= "DEN1", yValue= 26 },
new ColumnChartData { x= "MEX1", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
225
Numeric Axis
You can use numeric axis to represent numeric values of data in chart. By default, the
valueType of an axis is Double .
razor
double.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
226
new ChartData { xValue = 20, yValue = 24, yValue1 = 44 },
new ChartData { xValue = 30, yValue = 36, yValue1 = 48 },
new ChartData { xValue = 40, yValue = 38, yValue1 = 50 },
new ChartData { xValue = 50, yValue = 54, yValue1 = 66 },
new ChartData { xValue = 60, yValue = 57, yValue1 = 78 },
new ChartData { xValue = 70, yValue = 70, yValue1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Range
Range for an axis, will be calculated automatically based on the provided data, you can also
customize the range of the axis using minimum , maximum and interval property of the axis.
razor
range.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
227
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
Range Padding
Padding can be applied to the minimum and maximum extremes of the axis range by using the
rangePadding property. Numeric axis supports following types of padding.
None
Round
Additional
228
Normal
Auto
Numeric - None
When the rangePadding is set to None , minimum and maximum of an axis is based on the
data.
razor
none.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
229
new ChartData { xValue = 10, yValue = 21, yValue1 = 28 },
new ChartData { xValue = 20, yValue = 24, yValue1 = 44 },
new ChartData { xValue = 30, yValue = 36, yValue1 = 48 },
new ChartData { xValue = 40, yValue = 38, yValue1 = 50 },
new ChartData { xValue = 50, yValue = 54, yValue1 = 66 },
new ChartData { xValue = 60, yValue = 57, yValue1 = 78 },
new ChartData { xValue = 70, yValue = 70, yValue1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Numeric - Round
When the rangePadding is set to Round , minimum and maximum will be rounded to the nearest
possible value divisible by interval. For example, when the minimum is 3.5 and the interval is 1,
then the minimum will be rounded to 3.
razor
round.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
230
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
Numeric - Additional
When the rangePadding is set to Additional , interval of an axis will be padded to the minimum
and maximum of the axis.
razor
additional.cs
231
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
232
public class ChartData
{
public double xValue;
public double yValue;
public double yValue1;
}
}
}
Numeric - Normal
When the rangePadding is set to Normal , padding is applied to the axis based on default range
calculation.
razor
normal.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
233
public partial class ChartController : Controller
{
Numeric - Auto
When the rangePadding is set to Auto ,horizontal numeric axis takes None as padding
calculation, while the vertical numeric axis takes Normal as padding calculation.
razor
auto.cs
@ControlSection {
@Html.EJS().Charts("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).S
eries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
234
to)
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Tooltip(tt => tt.Enable(true)).Load("load"
).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
Label Format
235
Numeric Label Format
Numeric labels can be formatted by using the labelFormat property. Numeric labels supports all
globalize format.
razor
label-format.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
236
new ChartData { xValue = 40, yValue = 38, yValue1 = 50 },
new ChartData { xValue = 50, yValue = 54, yValue1 = 66 },
new ChartData { xValue = 60, yValue = 57, yValue1 = 78 },
new ChartData { xValue = 70, yValue = 70, yValue1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
The following table describes the result of applying some commonly used label formats on
numeric values.
razor
237
custom.cs
@ControlSection {
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).Se
ries(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("German
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
238
return View();
}
239
DateTime and DateTimeCategory Axis
DateTime Axis
Date time axis uses date time scale and displays the date time values as axis labels in the
specified format.
razor
datetime.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
240
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
DateTimeCategory Axis
Date-time category axis is used to display the date-time values with non-linear intervals. For
example, the business days alone have been depicted in a week here.
razor
dateCategory.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTimeCateg
ory).LabelFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
241
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
242
Range
Range for an axis, will be calculated automatically based on the provided data, you can also
customize the range of the axis using minimum , maximum and interval property of the axis.
razor
range.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y").Minimum(new DateTime(2005, 1, 1)).Maximum(new DateTime(2010, 1, 1))
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
243
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
ViewBag.minimum = new DateTime(2015, 1, 1);
ViewBag.maximum = new DateTime(2012, 01, 01)
return View();
}
Interval Customization
Date time intervals can be customized by using the interval and intervalType properties of
the axis. For example, when you set interval as 2 and intervalType as years, it considers 2 years
as interval. DateTime axis supports following interval types,
Auto
Years
Months
Days
Hours
Minutes
Seconds
razor
interval.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
244
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y").IntervalType("Months")
).PrimaryYAxis(py => py.LabelFormat("{value}%").Interval(20).Minimum(0).Maximum(
100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
245
public DateTime xValue;
public double yValue;
public double yValue1;
}
}
}
Padding can be applied to the minimum and maximum extremes of the range by using the
rangePadding property. Date time axis supports the following types of padding,
None
Round
Additional
DateTime - None
When the rangePadding is set to None , minimum and maximum of the axis is based on the
data.
razor
none.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
246
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
DateTime - Round
When the rangePadding is set to Round , minimum and maximum will be rounded to the nearest
possible value divisible by interval. For example, when the minimum is 15th Jan, interval is 1 and
the interval type is ‘month’, then the axis minimum will be Jan 1st.
razor
round.cs
@using Syncfusion.EJ2;
@ControlSection{
247
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Round).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
248
}
DateTime - Additional
When the rangePadding is set to Additional , interval of an axis will be padded to the minimum
and maximum of the axis.
Label Format
You can format and parse the date to all globalize format using labelFormat property in an axis.
razor
label-format.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("yMd")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
249
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
The following table describes the result of applying some common date time formats to the
labelFormat property
Label Format
Label Value Result Description
Property Value
new
The Date is displayed in day
Date(2000, EEEE Monday
format
03, 10)
new
The Date is displayed in
Date(2000, yMd 04/10/2000
month/date/year format
03, 10)
250
new
The Shorthand month for the
Date(2000, MMM Apr
date is displayed
03, 10)
new
Time of the date value is
Date(2000, hm 12:00 AM
displayed as label
03, 10)
new
12:00:00 The Label is displayed in
Date(2000, hms
AM hours:minutes:seconds format
03, 10)
razor
custom.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
251
public IActionResult Line()
{
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
252
Logarithmic Axis
Logarithmic axis uses logarithmic scale and it is very useful in visualizing data, when it has
numeric values in both lower order of magnitude (eg: 10-6) and higher order of magnitude (eg:
106).
razor
log.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => px.ValueType(Syncfusion.EJ2.Charts.ValueType.Logarithmic).L
abelFormat("{value}%").RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None).Inter
val(20).Minimum(0).Maximum(100)
).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
253
ue1 = 48 },
new ChartData { xValue = new DateTime(2008, 01, 01), yValue = 1000, yVa
lue1 = 50 },
new ChartData { xValue = new DateTime(2009, 01, 01), yValue = 8000, yVa
lue1 = 66 },
new ChartData { xValue = new DateTime(2010, 01, 01), yValue = 90000, yV
alue1 = 78 },
new ChartData { xValue = new DateTime(2011, 01, 01), yValue = 99000, yV
alue1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Range
Range of an axis, will be calculated automatically based on the provided data, you can also
customize the range of the axis using minimum , maximum and interval property of the axis.
razor
range.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => px.ValueType(Syncfusion.EJ2.Charts.ValueType.Logarithmic).L
abelFormat("{value}%").RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None).Minim
um(10).Maximum(1000)
).Render()
}
254
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
Logarithmic Base
255
Logarithmic base can be customized by using the logBase property of the axis. For example
when the logBase is 5, the axis values follows 5-2, 5-1, 50, 51, 52 etc.
razor
base.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => px.ValueType(Syncfusion.EJ2.Charts.ValueType.Logarithmic).L
abelFormat("{value}%").LogBase(8)
).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
256
alue1 = 78 },
new ChartData { xValue = new DateTime(2011, 01, 01), yValue = 99000, yV
alue1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Logarithmic Interval
Logarithmic axis interval can be customized by using the interval property of the axis. When
the logarithmic base is 10 and logarithmic interval is 2, then the axis labels are placed at an
interval of 102. The default value of the interval is 1.
razor
interval.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => px.ValueType(Syncfusion.EJ2.Charts.ValueType.Logarithmic).L
abelFormat("{value}%").RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None).Inter
val(2)
).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
257
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
258
Axis Labels
razor
hide.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue")
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Hides)
.LabelFormat("y")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Render()
}
259
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
260
razor
rotate45.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue")
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Hides)
.LabelFormat("y")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
261
public partial class ChartController : Controller
{
razor
rotate90.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
262
.YName("yValue")
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Hides)
.LabelFormat("y")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
263
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
razor
position.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column)
.XName("x")
.YName("y")
.Marker(ViewBag.marker)
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
}).PrimaryXAxis(px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.MajorGridLines(ViewBag.majorGridLines)
.IsIndexed(true)
264
.LabelRotation(90)
.Interval(1)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Rotate90)
).PrimaryYAxis(py => py.Maximum(120)
.Minimum(0)
.Interval(30)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle)
).Title("Fruits and Vegetables - Season").ChartArea(area => area.Border(ViewBag.
ChartBorder))
.LegendSettings(lg=>lg.Visible(false))
.Load("load")
.Render()
<script>
var load = function (args) {
var selectedTheme = location.hash.split('/')[1];
selectedTheme = selectedTheme ? selectedTheme : 'Material';
args.chart.theme = (selectedTheme.charAt(0).toUpperCase() + selectedTheme.s
lice(1));
args.chart.width = ej.base.Browser.isDevice ? "100%" : "60%";
args.chart.primaryXAxis.border = { type: "Rectangle", width: 1 };
args.chart.primaryXAxis.multiLevelLabels = (ej.base.Browser.isDevice ? ([
{
border: { type: 'Rectangle' },
categories: [
{ start: -0.5, end: 2.5, text: 'In Season', },
{ start: 2.5, end: 5.5, text: 'Out of Season', },
{ start: 5.5, end: 7.5, text: 'In Season', },
{ start: 7.5, end: 9.5, text: 'Out of Season', },
]
}, {
border: { type: 'Rectangle' },
textStyle: { fontWeight: 'Bold' },
categories: [
{ start: -0.5, end: 5.5, text: 'Fruits', },
{ start: 5.5, end: 9.5, text: 'Vegetables', },
]
}]) : [
{
border: { type: 'Rectangle' },
categories: [
{ start: -0.5, end: 0.5, text: 'Seedless', },
{ start: 0.5, end: 2.5, text: 'Seeded', },
{ start: 2.5, end: 3.5, text: 'Seedless', },
{ start: 3.5, end: 5.5, text: 'Seeded', },
{ start: 5.5, end: 6.5, text: 'Seedless', },
{ start: 6.5, end: 7.5, text: 'Seeded', },
{ start: 7.5, end: 8.5, text: 'Seedless', },
265
{ start: 8.5, end: 9.5, text: 'Seeded', }
]
}, {
border: { type: 'Rectangle' },
categories: [
{ start: -0.5, end: 2.5, text: 'In Season', },
{ start: 2.5, end: 5.5, text: 'Out of Season', },
{ start: 5.5, end: 7.5, text: 'In Season', },
{ start: 7.5, end: 9.5, text: 'Out of Season', },
]
}, {
border: { type: 'Rectangle' },
textStyle: { fontWeight: 'Bold' },
categories: [
{ start: -0.5, end: 5.5, text: 'Fruits', },
{ start: 5.5, end: 9.5, text: 'Vegetables', },
]
}])
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
266
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Multilevel Labels
Any number of levels of labels can be added to an axis using the multiLevelLabels property.
This property can be configured using the following properties:
Categories
Using the categories property, you can configure the start , end , text , and
maximumTextWidth of multilevel labels.
razor
category.cs
267
).Title("Inflation - Consumer Price").Tooltip(tt => tt.Enable(true)).Load("load"
).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Chart;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: MultiLevelLabels
public ActionResult MultiLevelLabels()
{
List<MultiLevelLabelsData> chartData = new List<MultiLevelLabelsData>
{
new MultiLevelLabelsData { x = "Grapes", y = 28 },
new MultiLevelLabelsData { x = "Apples", y = 87 },
new MultiLevelLabelsData { x = "Pears", y = 42 },
new MultiLevelLabelsData { x = "Grapes", y = 13 },
new MultiLevelLabelsData { x = "Apples", y = 13 },
new MultiLevelLabelsData { x = "Pears", y = 10 },
new MultiLevelLabelsData { x = "Tomato", y = 31 },
new MultiLevelLabelsData { x = "Potato", y = 96 },
new MultiLevelLabelsData { x = "Cucumber",y = 41 },
new MultiLevelLabelsData { x = "Onion", y = 59 }
};
ViewBag.dataSource = chartData;
return View();
}
public class MultiLevelLabelsData
{
public string x;
public double y;
}
}
}
Overflow
Using the overflow property, you can trim or wrap the multilevel labels.
razor
268
overflow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Chart;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: MultiLevelLabels
public ActionResult MultiLevelLabels()
{
List<MultiLevelLabelsData> chartData = new List<MultiLevelLabelsData>
{
new MultiLevelLabelsData { x = "Grapes", y = 28 },
new MultiLevelLabelsData { x = "Apples", y = 87 },
new MultiLevelLabelsData { x = "Pears", y = 42 },
new MultiLevelLabelsData { x = "Grapes", y = 13 },
new MultiLevelLabelsData { x = "Apples", y = 13 },
new MultiLevelLabelsData { x = "Pears", y = 10 },
new MultiLevelLabelsData { x = "Tomato", y = 31 },
269
new MultiLevelLabelsData { x = "Potato", y = 96 },
new MultiLevelLabelsData { x = "Cucumber",y = 41 },
new MultiLevelLabelsData { x = "Onion", y = 59 }
};
ViewBag.dataSource = chartData;
return View();
}
public class MultiLevelLabelsData
{
public string x;
public double y;
}
}
}
Alignment
The alignment property provides option to position the multilevel labels at far , center , or
near .
razor
Text customization
270
The textStyle property of multilevel labels provides options to customize the size , color ,
fontFamily , fontWeight , fontStyle , opacity , textAlignment and textOverflow .
razor
text-custom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Chart;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: MultiLevelLabels
public ActionResult MultiLevelLabels()
{
List<MultiLevelLabelsData> chartData = new List<MultiLevelLabelsData>
{
new MultiLevelLabelsData { x = "Grapes", y = 28 },
new MultiLevelLabelsData { x = "Apples", y = 87 },
new MultiLevelLabelsData { x = "Pears", y = 42 },
271
new MultiLevelLabelsData { x = "Grapes", y = 13 },
new MultiLevelLabelsData { x = "Apples", y = 13 },
new MultiLevelLabelsData { x = "Pears", y = 10 },
new MultiLevelLabelsData { x = "Tomato", y = 31 },
new MultiLevelLabelsData { x = "Potato", y = 96 },
new MultiLevelLabelsData { x = "Cucumber",y = 41 },
new MultiLevelLabelsData { x = "Onion", y = 59 }
};
ViewBag.dataSource = chartData;
return View();
}
public class MultiLevelLabelsData
{
public string x;
public double y;
}
}
}
Border customization
Using the border property, you can customize the width , color , and type . The type of
border are Rectangle , Brace , WithoutBorder , WithoutTopBorder ,
WithoutTopandBottomBorder and CurlyBrace .
razor
border-custom.cs
272
).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Chart;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: MultiLevelLabels
public ActionResult MultiLevelLabels()
{
List<MultiLevelLabelsData> chartData = new List<MultiLevelLabelsData>
{
new MultiLevelLabelsData { x = "Grapes", y = 28 },
new MultiLevelLabelsData { x = "Apples", y = 87 },
new MultiLevelLabelsData { x = "Pears", y = 42 },
new MultiLevelLabelsData { x = "Grapes", y = 13 },
new MultiLevelLabelsData { x = "Apples", y = 13 },
new MultiLevelLabelsData { x = "Pears", y = 10 },
new MultiLevelLabelsData { x = "Tomato", y = 31 },
new MultiLevelLabelsData { x = "Potato", y = 96 },
new MultiLevelLabelsData { x = "Cucumber",y = 41 },
new MultiLevelLabelsData { x = "Onion", y = 59 }
};
ViewBag.dataSource = chartData;
return View();
}
public class MultiLevelLabelsData
{
public string x;
public double y;
}
}
}
273
razor
edge.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue")
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Hide)
.LabelFormat("y")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
274
public partial class ChartController : Controller
{
Labels Customization
The labelStyle property of an axis provides options to customize the color , font-family ,
font-size and font-weight of the axis labels.
razor
labels-custom.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
275
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue")
.DataSource(ViewBag.dataSource)
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Hides)
.LabelFormat("y").
.LabelStyle("ViewBag.label")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
276
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
ViewBag.label = new { font-weigth = '800', font-style = 'italic'}
return View();
}
razor
custom-point.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").ChartArea(area => area.Border(ViewBag.ChartBorder)).
Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue")
.DataSource(ViewBag.dataSource)
277
.Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Width(2)
.XName("xValue")
.YName("yValue1")
.DataSource(ViewBag.dataSource)
.Name("England").Add();
}).PrimaryXAxis( px =>
px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.MajorGridLines(ViewBag.majorGridLines)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Hides)
.LabelFormat("y")
).PrimaryYAxis(py =>
py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)
.LineStyle(ViewBag.lineStyle)
.Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").AxisLabelRender("axisLabel").Render()
<script>
function axislabel(args) {
if(args.text === 'France') {
args.labelStyle.color = 'Red';
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
278
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
279
Axis Customization
Axis Crossing
An axis can be positioned in the chart area using crossesAt and crossesInAxis properties.
The crossesAt property specifies the values (datetime, numeric, or logarithmic) at which the
axis line has to be intersected with the vertical axis or vice-versa, and the crossesInAxis
property specifies the axis name with which the axis line has to be crossed.
razor
axis-cross.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
). crossesAt(15)).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
). crossesAt(5)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
280
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Title
You can add a title to the axis using title property to provide quick information to the user
about the data plotted in the axis.
razor
title.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
).TitleStyle(ViewBag.titleStyle)).
Title("Olympic Medal Counts - RIO").Render()
}
281
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
ViewBag.titleStyle = new { size="16px", color="grey", fontFamily="Segoe UI"
, fontWeight="bold"}
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
tick.cs
@using Syncfusion.EJ2;
282
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
).MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)).
PrimaryyAxis(px => px.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
ViewBag.majorTickLines = new { color = 'red', width = 5 }
ViewBag.minorTickLines = new { color = 'blue', width = 0 }
return View();
283
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
grid.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
).MajorGridLines(ViewBag.majorGridLines)
.MinorGridLines(ViewBag.minorGridLines)).
PrimaryyAxis(px => px.MajorTickLines(ViewBag.majorTickLines)
.MinorTickLines(ViewBag.minorTickLines)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
284
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
ViewBag.majorGridLines = new { color = 'red', width = 1 }
ViewBag.minorGridLines = new { color = 'blue', width = 0 }
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Multiple Axis
In addition to primary X and Y axis, we can add n number of axis to the chart. Series can be
associated with this axis, by mapping with axis's unique name.
razor
multiple.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("y").
DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).YAxisName("yAxis").XName(
"x").Marker(ViewBag.marker).YName("y1").DataSource(ViewBag.dataSource).Name("Japan").Ad
d();
285
.Interval(1).LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Rotate90)
).Axes(ax =>
{
ax.OpposedPosition(true).RowIndex(0).Minimum(24).Maximum(36).Interval(2).Nam
e("yAxis").LabelFormat("{value}°C").Add();
}
)
).Title("Weather Condition JPN vs DEU").ChartArea(area => area.Border(ViewBag.ChartBord
er)).Tooltip(tt => tt.Enable(true)).LegendSettings(lg=>lg.Visible(false)).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MultipleAxes()
{
List<MultipleAxesChartData> chartData = new List<MultipleAxesChartData>
{
new MultipleAxesChartData { x = "Sun", y = 35, y1 = 30 },
new MultipleAxesChartData { x = "Mon", y = 40, y1 = 28 },
new MultipleAxesChartData { x = "Tue", y = 80, y1 = 29 },
new MultipleAxesChartData { x = "Wed", y = 70, y1 = 30 },
new MultipleAxesChartData { x = "Thu", y = 65, y1 = 33 },
new MultipleAxesChartData { x = "Fri", y = 55, y1 = 32 },
new MultipleAxesChartData { x = "Sat", y = 50, y1 = 34 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10, border = new
{ width = 2, color = "#F8AB1D" } };
return View();
}
public class MultipleAxesChartData
{
public string x;
public double y;
public double y1;
}
}
}
286
Inversed Axis
When an axis is inversed, highest value of the axis comes closer to origin and vice versa. To
place an axis in inversed manner set this property isInversed to true.
razor
inversed.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
).IsInversed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
287
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Opposed Position
To place an axis opposite from its original position, set opposedPosition property of the axis to
true.
razor
opposed.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
).OpposedPosition(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
288
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
289
Strip lines
EJ2 chart supports horizontal and vertical strip lines and customization of stripline in both
orientation.
razor
horizontal.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
StripLines(ViewBag.yAxisStripLine ).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
290
{
List<StripLineChartData> chartData = new List<StripLineChartData>
{
new StripLineChartData { x = "Sun", y = 28 },
new StripLineChartData { x = "Mon", y = 27 },
new StripLineChartData { x = "Tue", y = 33 },
new StripLineChartData { x = "Wed", y = 36 },
new StripLineChartData { x = "Thu", y = 28 },
new StripLineChartData { x = "Fri", y = 30 },
new StripLineChartData { x = "Sat", y = 31 }
};
ViewBag.dataSource = chartData;
List<ChartStripLine> yAxisStripline = new List<ChartStripLine>();
ChartStripLine ystripline1 = new ChartStripLine();
ystripline1.Start = "30";
ystripline1.End = "35";
ystripline1.Visible = true;
yAxisStripline.Add(ystripline1);
ViewBag.yAxisStripLine = yAxisStripline;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Vertical Striplines
You can create vertical stripline by adding the stripline in the horizontal axis and set visible
option to true. Striplines are rendered in the specified start to end range and you can add more
than one stripline for an axis.
razor
vertical.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
291
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
StripLines(ViewBag.xAxisStripLine).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<StripLineChartData> chartData = new List<StripLineChartData>
{
new StripLineChartData { x = "Sun", y = 28 },
new StripLineChartData { x = "Mon", y = 27 },
new StripLineChartData { x = "Tue", y = 33 },
new StripLineChartData { x = "Wed", y = 36 },
new StripLineChartData { x = "Thu", y = 28 },
new StripLineChartData { x = "Fri", y = 30 },
new StripLineChartData { x = "Sat", y = 31 }
};
ViewBag.dataSource = chartData;
ChartStripLine xstripline1 = new ChartStripLine();
xstripline1.Start = "1";
xstripline1.End = "2.5";
xstripline1.Visible = true;
xAxisStripline.Add(xstripline1);
ViewBag.xAxisStripLine = xAxisStripline;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
292
}
}
razor
custom-stripline.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
StripLines(ViewBag.xAxisStripLine).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
293
List<StripLineChartData> chartData = new List<StripLineChartData>
{
new StripLineChartData { x = "Sun", y = 28 },
new StripLineChartData { x = "Mon", y = 27 },
new StripLineChartData { x = "Tue", y = 33 },
new StripLineChartData { x = "Wed", y = 36 },
new StripLineChartData { x = "Thu", y = 28 },
new StripLineChartData { x = "Fri", y = 30 },
new StripLineChartData { x = "Sat", y = 31 }
};
ViewBag.dataSource = chartData;
ChartStripLine xstripline1 = new ChartStripLine();
xstripline1.startFromOrigin = true;
xstripline1.Size = 4;
xstripline1.ZIndex = "Behind";
xstripline1.Opacity = 0.5;
xstripline1.Visible = true;
xAxisStripline.Add(xstripline1);
ViewBag.xAxisStripLine = xAxisStripline;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
custom-striptext.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
294
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
StripLines(ViewBag.xAxisStripLine).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<StripLineChartData> chartData = new List<StripLineChartData>
{
new StripLineChartData { x = "Sun", y = 28 },
new StripLineChartData { x = "Mon", y = 27 },
new StripLineChartData { x = "Tue", y = 33 },
new StripLineChartData { x = "Wed", y = 36 },
new StripLineChartData { x = "Thu", y = 28 },
new StripLineChartData { x = "Fri", y = 30 },
new StripLineChartData { x = "Sat", y = 31 }
};
ViewBag.dataSource = chartData;
ChartStripLine xstripline1 = new ChartStripLine();
xstripline1.startFromOrigin = true;
xstripline1.Size = 3;
xstripline1.ZIndex = "Behind";
xstripline1.Opacity = 0.5;
xstripline1.Visible = true;
xstripline1.Text = "Good";
xstripline1.TextStyle = new { size = "18px" };
xstripline1.VerticalAlignment = "Middle";
xstripline1.HorizontalAlignment= "Middle";
xstripline1.Rotation = 90;
xstripline1.Visible = true;
295
ChartStripLine xstripline2 = new ChartStripLine();
xstripline2.Start = "4";
xstripline2.End = "6";
xstripline2.Text = "Poor";
xstripline1.VerticalAlignment = "Start";
xstripline1.HorizontalAlignment= "End";
xstripline1.Rotation = 90;
xstripline2.Visible = true;
xAxisStripline.Add(xstripline1);
xAxisStripline.Add(xstripline2);
ViewBag.xAxisStripLine = xAxisStripline;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
296
Multiple Panes
Chart area can be divided into multiple panes using rows and columns .
Rows
To split the chart area vertically into number of rows, use rows property of the chart.
You can allocate space for each row by using the height property. The value can be either
in percentage or in pixel.
To associate a vertical axis to a particular row, specify its index to rowIndex property of the
axis.
To customize each row’s bottom line, use border property.
razor
row.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Rows(rows =>
{
rows.Height("50%").Add();
rows.Height("50%").Add();
})
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("y").
DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).YAxisName("yAxis").XName(
"x").Marker(ViewBag.marker).YName("y1").DataSource(ViewBag.dataSource).Name("Japan").Ad
d();
297
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MultipleAxes()
{
List<MultipleAxesChartData> chartData = new List<MultipleAxesChartData>
{
new MultipleAxesChartData { x = "Sun", y = 35, y1 = 30 },
new MultipleAxesChartData { x = "Mon", y = 40, y1 = 28 },
new MultipleAxesChartData { x = "Tue", y = 80, y1 = 29 },
new MultipleAxesChartData { x = "Wed", y = 70, y1 = 30 },
new MultipleAxesChartData { x = "Thu", y = 65, y1 = 33 },
new MultipleAxesChartData { x = "Fri", y = 55, y1 = 32 },
new MultipleAxesChartData { x = "Sat", y = 50, y1 = 34 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10, border = new
{ width = 2, color = "#F8AB1D" } };
return View();
}
public class MultipleAxesChartData
{
public string x;
public double y;
public double y1;
}
}
}
For spanning the vertical axis along multiple row, you can use span property of an axis.
razor
row-span.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
Rows(rows =>
{
298
rows.Height("50%").Add();
rows.Height("50%").Add();
}).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("y").
DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).YAxisName("yAxis").XName(
"x").Marker(ViewBag.marker).YName("y1").DataSource(ViewBag.dataSource).Name("Japan").Ad
d();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MultipleAxes()
{
List<MultipleAxesChartData> chartData = new List<MultipleAxesChartData>
{
new MultipleAxesChartData { x = "Sun", y = 35, y1 = 30 },
new MultipleAxesChartData { x = "Mon", y = 40, y1 = 28 },
new MultipleAxesChartData { x = "Tue", y = 80, y1 = 29 },
new MultipleAxesChartData { x = "Wed", y = 70, y1 = 30 },
new MultipleAxesChartData { x = "Thu", y = 65, y1 = 33 },
new MultipleAxesChartData { x = "Fri", y = 55, y1 = 32 },
new MultipleAxesChartData { x = "Sat", y = 50, y1 = 34 }
};
ViewBag.dataSource = chartData;
299
ViewBag.marker = new { visible = true, width = 10, height = 10, border = new
{ width = 2, color = "#F8AB1D" } };
return View();
}
public class MultipleAxesChartData
{
public string x;
public double y;
public double y1;
}
}
}
Columns
To split the chart area horizontally into number of columns, use columns property of the chart.
You can allocate space for each column by using the width property. The given width can
be either in percentage or in pixel.
To associate a horizontal axis to a particular column, specify its index to columnIndex
property of the axis.
To customize each column’s bottom line, use border property.
razor
column.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Columns(columns =>
{
columns.width("50%").Add();
columns.width("50%").Add();
})
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("y").
DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).YAxisName("yAxis").XName(
"x").Marker(ViewBag.marker).YName("y1").DataSource(ViewBag.dataSource).Name("Japan").Ad
d();
300
e("yAxis").LabelFormat("{value}°C").Add();
}
)
).Title("Weather Condition JPN vs DEU").ChartArea(area => area.Border(ViewBag.ChartBord
er)).Tooltip(tt => tt.Enable(true)).LegendSettings(lg=>lg.Visible(false)).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MultipleAxes()
{
List<MultipleAxesChartData> chartData = new List<MultipleAxesChartData>
{
new MultipleAxesChartData { x = "Sun", y = 35, y1 = 30 },
new MultipleAxesChartData { x = "Mon", y = 40, y1 = 28 },
new MultipleAxesChartData { x = "Tue", y = 80, y1 = 29 },
new MultipleAxesChartData { x = "Wed", y = 70, y1 = 30 },
new MultipleAxesChartData { x = "Thu", y = 65, y1 = 33 },
new MultipleAxesChartData { x = "Fri", y = 55, y1 = 32 },
new MultipleAxesChartData { x = "Sat", y = 50, y1 = 34 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10, border = new
{ width = 2, color = "#F8AB1D" } };
return View();
}
public class MultipleAxesChartData
{
public string x;
public double y;
public double y1;
}
}
}
For spanning the horizontal axis along multiple column, you can use span property of an axis.
301
razor
column-span.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Columns(columns =>
{
columns.width("50%").Add();
columns.width("50%").Add();
})
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("y").
DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).YAxisName("yAxis").XName(
"x").Marker(ViewBag.marker).YName("y1").DataSource(ViewBag.dataSource).Name("Japan").Ad
d();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MultipleAxes()
{
List<MultipleAxesChartData> chartData = new List<MultipleAxesChartData>
{
302
new MultipleAxesChartData { x = "Sun", y = 35, y1 = 30 },
new MultipleAxesChartData { x = "Mon", y = 40, y1 = 28 },
new MultipleAxesChartData { x = "Tue", y = 80, y1 = 29 },
new MultipleAxesChartData { x = "Wed", y = 70, y1 = 30 },
new MultipleAxesChartData { x = "Thu", y = 65, y1 = 33 },
new MultipleAxesChartData { x = "Fri", y = 55, y1 = 32 },
new MultipleAxesChartData { x = "Sat", y = 50, y1 = 34 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new { visible = true, width = 10, height = 10, border = new
{ width = 2, color = "#F8AB1D" } };
return View();
}
public class MultipleAxesChartData
{
public string x;
public double y;
public double y1;
}
}
}
303
Chart Types
Essential JS 2 Chart chart supports 14 types of series.
Line Charts
Line
razor
line.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
304
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Step Line
razor
stepline.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
305
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StepLine).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StepLine).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
306
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Spline
razor
spline.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Spline).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Spline).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
307
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
308
}
Spline Area
razor
splinearea.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.SplineArea).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.SplineArea).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
309
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Multicolored Line
To render a multicolored line series, use the series type as MultiColoredLine . Here, the
individual colors to the data can be mapped by using pointColorMapping .
razor
multi-line.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.MultiColoredLine).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
310
Name("Gold").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46, color="FF0000" },
new ChartData { x= "GBR", yValue= 27, color= "00FF00" },
new ChartData { x= "CHN", yValue= 26, color= "00F000" },
new ChartData { x= "UK", yValue= 56, color= "0000FF" },
new ChartData { x= "AUS", yValue= 12, color= "FE0000" },
new ChartData { x= "IND", yValue= 26, color= "00EECC" },
new ChartData { x= "DEN", yValue= 26, color= "CCFFEE" },
new ChartData { x= "MEX", yValue= 34, color= "CCDDBB" },
};
return View();
}
public class ChartData
{
public string x;
public double yValue;
public string color;
}
}
}
311
stroke , stroke-width and dashArray of all line type series can be customized by using
fill , width and dashArray properties.
razor
custom-line.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
XName("x").
YName("yValue").
DashArray("20,5").
Fill("#FF0000").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
XName("x").
DashArray("10,5").
Fill("#000000").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
312
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Area Charts
Area
razor
area.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
313
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
314
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Range Area
razor
rangearea.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.RangeArea).
Marker(ViewBag.Marker).
XName("x").
High("yValue").
Low("yValue2").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
315
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue = 46, yValue2 = 23},
new ChartData { x= "GBR", yValue = 27, yValue2 = 43 },
new ChartData { x= "CHN", yValue = 26,, yValue2 = 54 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ChartData
{
public string x;
public double yValue;
public double yValue2;
}
}
}
Stacked Area
razor
stackedarea.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackedArea).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackedArea).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
316
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
317
public string x;
public double yValue;
}
}
}
razor
stackedarea100.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackedArea100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackedArea100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
318
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Step Area
razor
steparea.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StepArea).
319
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StepArea).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
320
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Multicolored area
To render a multicolored area series, use the series type as MultiColoredArea . The required
segments of the series can be customized using the value , color , and dashArray .
razor
multicolor-area.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
XName("x").
YName("yValue").
PointColorMapping("Color").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
XName("x").
YName("yValue").
PointColorMapping("Color").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
321
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46, color="FF0000" },
new ChartData { x= "GBR", yValue= 27, color= "00FF00" },
new ChartData { x= "CHN", yValue= 26, color= "00F000" },
new ChartData { x= "UK", yValue= 56, color= "0000FF" },
new ChartData { x= "AUS", yValue= 12, color= "FE0000" },
new ChartData { x= "IND", yValue= 26, color= "00EECC" },
new ChartData { x= "DEN", yValue= 26, color= "CCFFEE" },
new ChartData { x= "MEX", yValue= 34, color= "CCDDBB" },
};
return View();
}
public class ChartData
{
public string x;
public double yValue;
public string color;
}
}
}
fill, width and dashArray properties can be customized by fill , width and dashArray
properties.
razor
custom-area.cs
322
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Fill("FF00FF").
DashArray("10, 5").
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Fill("FFF0FF").
DashArray("20, 5").
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
323
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Column Charts
Column
razor
column.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
324
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
325
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Range Column
razor
rangecolumn.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.RangeColumn).
Marker(ViewBag.Marker).
XName("x").
High("yValue").
Low("yValue2").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
326
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue = 46, yValue2 = 23},
new ChartData { x= "GBR", yValue = 27, yValue2 = 43 },
new ChartData { x= "CHN", yValue = 26,, yValue2 = 54 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ChartData
{
public string x;
public double yValue;
public double yValue2;
}
}
}
Stacked Column
razor
stackedcolumn.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
327
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
328
To render a 100% stacked column series, use series type as StackingColumn100 .
razor
stackedcolumn100.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
329
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Stacking Group
You can use the stackingGroup property to group the stacked columns and 100% stacked
columns. Columns with same group name are stacked on top of each other.
razor
group.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
StackingGroup("first")
Name("Gold").
.Add();
330
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingColumn).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
StackingGroup("second").
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
331
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
fill and border of all column type series can be customized using fill and border
properties. For customizing a specify point, please refer the pointRender .
Bar Charts
Bar
razor
bar.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Bar).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Bar).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
332
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
333
}
}
Stacked bar
razor
stackedbar.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
334
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
razor
stackedbar100.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
335
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar100).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
336
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Stacking Group
You can use the stackingGroup property to group the stacked bar and 100% stacked bar.
Columns with same group name are stacked on top of each other.
razor
group.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar).
XName("x").
YName("yValue").
StakingGroup("first").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.StackingBar).
XName("x").
YName("yValue").
StakingGroup("second").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
337
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
338
Customization of Bar Charts
fill and border of all bar type series can be customized using fill and border . For
customizing a specify point, please refer the pointRender .
razor
custom-bar.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Bar).
XName("x").
YName("yValue").
Fill("#FFCCBB").
DashArray("10,5).
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Bar).
XName("x").
YName("yValue").
Fill("#FFCCBB").
DashArray("10,5").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace Chart.Controllers
{
public partial class ChartController : Controller
{
339
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 },
new ChartData { x= "UK", yValue= 56 },
new ChartData { x= "AUS", yValue= 12 },
new ChartData { x= "IND", yValue= 26 },
new ChartData { x= "DEN", yValue= 26 },
new ChartData { x= "MEX", yValue= 34 },
};
List<ChartData> chartData1 = new List<ChartData>
{
new ChartData { x= "USA", yValue= 56 },
new ChartData { x= "GBR", yValue= 17 },
new ChartData { x= "CHN", yValue= 36 },
new ChartData { x= "UK", yValue= 16 },
new ChartData { x= "AUS", yValue= 46 },
new ChartData { x= "IND", yValue= 16 },
new ChartData { x= "DEN", yValue= 12 },
new ChartData { x= "MEX", yValue= 32 },
};
ViewBag.dataSource = chartData1;
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
Scatter Charts
To render a scatter series, use series type as Scatter .
razor
scatter.cs
@section ControlsSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter).
XName("x").
340
YName("y").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
Title("Olympic Medal Counts - RIO").Load("load").Render()
<script>
function load(args) {
args.chart.series[0].dataSource = [
{ 'x': 115, 'y': 57 }, { 'x': 138, 'y': 57 }, { 'x': 166, 'y': 57 }, { 'x': 122, 'y'
: 57 },
{ 'x': 126, 'y': 57 }, { 'x': 130, 'y': 57 }, { 'x': 125, 'y': 57 }, { 'x': 144, 'y'
: 57 },
{ 'x': 150, 'y': 57 }, { 'x': 120, 'y': 57 }, { 'x': 125, 'y': 57 }, { 'x': 130, 'y'
: 57 },
{ 'x': 103, 'y': 58 }, { 'x': 116, 'y': 58 }, { 'x': 130, 'y': 58 }, { 'x': 126, 'y'
: 58 },
{ 'x': 136, 'y': 58 }, { 'x': 148, 'y': 58 }, { 'x': 119, 'y': 58 }, { 'x': 141, 'y'
: 58 },
{ 'x': 159, 'y': 58 }, { 'x': 120, 'y': 58 }, { 'x': 135, 'y': 58 }, { 'x': 163, 'y'
: 58 },
{ 'x': 119, 'y': 59 }, { 'x': 131, 'y': 59 }, { 'x': 148, 'y': 59 }, { 'x': 123, 'y'
: 59 },
{ 'x': 137, 'y': 59 }, { 'x': 149, 'y': 59 }, { 'x': 121, 'y': 59 }, { 'x': 142, 'y'
: 59 },
{ 'x': 160, 'y': 59 }, { 'x': 118, 'y': 59 }, { 'x': 130, 'y': 59 }, { 'x': 146, 'y'
: 59 },
{ 'x': 119, 'y': 60 }, { 'x': 133, 'y': 60 }, { 'x': 150, 'y': 60 }, { 'x': 133, 'y'
: 60 },
{ 'x': 149, 'y': 60 }, { 'x': 165, 'y': 60 }, { 'x': 130, 'y': 60 }, { 'x': 139, 'y'
: 60 },
{ 'x': 154, 'y': 60 }, { 'x': 118, 'y': 60 }, { 'x': 152, 'y': 60 }, { 'x': 154, 'y'
: 60 },
{ 'x': 130, 'y': 61 }, { 'x': 145, 'y': 61 }, { 'x': 166, 'y': 61 }, { 'x': 131, 'y'
: 61 },
{ 'x': 143, 'y': 61 }, { 'x': 162, 'y': 61 }, { 'x': 131, 'y': 61 }, { 'x': 145, 'y'
: 61 },
{ 'x': 162, 'y': 61 }, { 'x': 115, 'y': 61 }, { 'x': 149, 'y': 61 }, { 'x': 183, 'y'
: 61 },
{ 'x': 121, 'y': 62 }, { 'x': 139, 'y': 62 }, { 'x': 159, 'y': 62 }, { 'x': 135, 'y'
: 62 },
{ 'x': 152, 'y': 62 }, { 'x': 178, 'y': 62 }, { 'x': 130, 'y': 62 }, { 'x': 153, 'y'
: 62 },
{ 'x': 172, 'y': 62 }, { 'x': 114, 'y': 62 }, { 'x': 135, 'y': 62 }, { 'x': 154, 'y'
: 62 },
{ 'x': 126, 'y': 63 }, { 'x': 141, 'y': 63 }, { 'x': 160, 'y': 63 }, { 'x': 135, 'y'
: 63 },
{ 'x': 149, 'y': 63 }, { 'x': 180, 'y': 63 }, { 'x': 132, 'y': 63 }, { 'x': 144, 'y'
341
: 63 },
{ 'x': 163, 'y': 63 }, { 'x': 122, 'y': 63 }, { 'x': 146, 'y': 63 }, { 'x': 156, 'y'
: 63 },
{ 'x': 133, 'y': 64 }, { 'x': 150, 'y': 64 }, { 'x': 176, 'y': 64 }, { 'x': 133, 'y'
: 64 },
{ 'x': 149, 'y': 64 }, { 'x': 176, 'y': 64 }, { 'x': 136, 'y': 64 }, { 'x': 157, 'y'
: 64 },
{ 'x': 174, 'y': 64 }, { 'x': 131, 'y': 64 }, { 'x': 155, 'y': 64 }, { 'x': 191, 'y'
: 64 },
{ 'x': 136, 'y': 65 }, { 'x': 149, 'y': 65 }, { 'x': 177, 'y': 65 }, { 'x': 143, 'y'
: 65 },
{ 'x': 149, 'y': 65 }, { 'x': 184, 'y': 65 }, { 'x': 128, 'y': 65 }, { 'x': 146, 'y'
: 65 },
{ 'x': 157, 'y': 65 }, { 'x': 133, 'y': 65 }, { 'x': 153, 'y': 65 }, { 'x': 173, 'y'
: 65 },
{ 'x': 141, 'y': 66 }, { 'x': 156, 'y': 66 }, { 'x': 175, 'y': 66 }, { 'x': 125, 'y'
: 66 },
{ 'x': 138, 'y': 66 }, { 'x': 165, 'y': 66 }, { 'x': 122, 'y': 66 }, { 'x': 164, 'y'
: 66 },
{ 'x': 182, 'y': 66 }, { 'x': 137, 'y': 66 }, { 'x': 157, 'y': 66 }, { 'x': 176, 'y'
: 66 },
{ 'x': 149, 'y': 67 }, { 'x': 159, 'y': 67 }, { 'x': 179, 'y': 67 }, { 'x': 156, 'y'
: 67 },
{ 'x': 179, 'y': 67 }, { 'x': 186, 'y': 67 }, { 'x': 147, 'y': 67 }, { 'x': 166, 'y'
: 67 },
{ 'x': 185, 'y': 67 }, { 'x': 140, 'y': 67 }, { 'x': 160, 'y': 67 }, { 'x': 180, 'y'
: 67 },
{ 'x': 145, 'y': 68 }, { 'x': 155, 'y': 68 }, { 'x': 170, 'y': 68 }, { 'x': 129, 'y'
: 68 },
{ 'x': 164, 'y': 68 }, { 'x': 189, 'y': 68 }, { 'x': 150, 'y': 68 }, { 'x': 157, 'y'
: 68 },
{ 'x': 183, 'y': 68 }, { 'x': 144, 'y': 68 }, { 'x': 170, 'y': 68 }, { 'x': 180, 'y'
: 68 }
];
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
342
{
public partial class ChartController : Controller
{
public IActionResult Column()
return View();
}
}
Bubble Chart
To render a bubble series, use series type as Bubble .
razor
bubble.cs
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Bubble).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
343
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
size property can be used to map the size value specified in data source.
razor
bubble-size.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.BUbble).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
Size("size").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
344
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46, size = 100 },
new ColumnChartData { x= "GBR", yValue= 27, size = 20 },
new ColumnChartData { x= "CHN", yValue= 26, size = 200 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
public double size;
}
}
}
345
Polar Chart and Radar Chart
Polar Chart
To render a polar series, use series type as Polar .
Draw Types
Polar drawType property is used to change the series plotting type to line, column, area, range
column, spline, scatter, stacking area and stacking column. The default value of drawType is
Line .
Line
To render a line draw type, use series drawType as Line . isClosed property specifies
whether to join start and end point of a line series used in polar chart to form a closed path.
Default value of isClosed is true.
razor
polar-line.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Line)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
346
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarLine()
{
List<PolarLineChartData> chartData = new List<PolarLineChartData>
{
new PolarLineChartData { xValue = "Jan", yValue = -7.1 },
new PolarLineChartData { xValue = "Feb", yValue = -3.7 },
new PolarLineChartData { xValue = "Mar", yValue = 0.8 },
new PolarLineChartData { xValue = "Apr", yValue = 6.3 },
new PolarLineChartData { xValue = "May", yValue = 13.3 },
new PolarLineChartData { xValue = "Jun", yValue = 18.0 },
new PolarLineChartData { xValue = "Jul", yValue = 19.8 },
new PolarLineChartData { xValue = "Aug", yValue = 18.1 },
new PolarLineChartData { xValue = "Sep", yValue = 13.1 },
new PolarLineChartData { xValue = "Oct", yValue = 4.1 },
new PolarLineChartData { xValue = "Nov", yValue = -3.8 },
new PolarLineChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
347
{
public string xValue;
public double yValue;
}
}
}
Spline
razor
polar-spline.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Spline)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
348
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarSpline()
{
List<PolarSplineChartData> chartData = new List<PolarSplineChartData>
{
new PolarSplineChartData { xValue = "Jan", yValue = -7.1 },
new PolarSplineChartData { xValue = "Feb", yValue = -3.7 },
new PolarSplineChartData { xValue = "Mar", yValue = 0.8 },
new PolarSplineChartData { xValue = "Apr", yValue = 6.3 },
new PolarSplineChartData { xValue = "May", yValue = 13.3 },
new PolarSplineChartData { xValue = "Jun", yValue = 18.0 },
new PolarSplineChartData { xValue = "Jul", yValue = 19.8 },
new PolarSplineChartData { xValue = "Aug", yValue = 18.1 },
new PolarSplineChartData { xValue = "Sep", yValue = 13.1 },
new PolarSplineChartData { xValue = "Oct", yValue = 4.1 },
new PolarSplineChartData { xValue = "Nov", yValue = -3.8 },
new PolarSplineChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
{
public string xValue;
public double yValue;
}
}
}
Area
349
razor
polar-area.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Area)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
350
public ActionResult PolarArea()
{
List<PolarAreaChartData> chartData = new List<PolarAreaChartData>
{
new PolarAreaChartData { xValue = "Jan", yValue = -7.1 },
new PolarAreaChartData { xValue = "Feb", yValue = -3.7 },
new PolarAreaChartData { xValue = "Mar", yValue = 0.8 },
new PolarAreaChartData { xValue = "Apr", yValue = 6.3 },
new PolarAreaChartData { xValue = "May", yValue = 13.3 },
new PolarAreaChartData { xValue = "Jun", yValue = 18.0 },
new PolarAreaChartData { xValue = "Jul", yValue = 19.8 },
new PolarAreaChartData { xValue = "Aug", yValue = 18.1 },
new PolarAreaChartData { xValue = "Sep", yValue = 13.1 },
new PolarAreaChartData { xValue = "Oct", yValue = 4.1 },
new PolarAreaChartData { xValue = "Nov", yValue = -3.8 },
new PolarAreaChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
{
public string xValue;
public double yValue;
}
}
}
Stacked Area
razor
polar-stackedarea.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingArea)
351
.Name("2013")
.XName("x")
.YName("y")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingArea)
.Name("2014")
.XName("x")
.YName("y1")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingArea)
.Name("2015")
.XName("x")
.YName("y2")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingArea)
.Name("2016")
.XName("x")
.YName("y3")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}M")
.Interval(5000)
.Minimum(20000)
.Maximum(0)
)
.Title("GDP, Current Prices (in Billions)")
.Tooltip(tp => tp.Enable(true))
.Load("load").Render()
)
}
using System;
using System.Collections.Generic;
352
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarStackedArea()
{
List<PolarStackedAreaData> data = new List<PolarStackedAreaData>
{
new PolarStackedAreaData { x= "JPN", text = "Japan", y= 5156, y1= 48
49, y2= 4382, y3= 4939 },
new PolarStackedAreaData { x= "DEU", text = "Germany", y= 3754, y1=
3885, y2= 3365, y3= 3467 },
new PolarStackedAreaData { x= "FRA", text = "France", y= 2809, y1= 2
844, y2= 2420, y3= 2463 },
new PolarStackedAreaData { x= "GBR", text = "UK", y= 2721, y1= 3002,
y2= 2863, y3= 2629 },
new PolarStackedAreaData { x= "BRA", text = "Brazil", y= 2472, y1= 2
456, y2= 1801, y3= 1799 },
new PolarStackedAreaData { x= "RUS", text = "Russia", y= 2231, y1= 2
064, y2= 1366, y3= 1281 },
new PolarStackedAreaData { x= "ITA", text = "Italy", y= 2131, y1= 21
55, y2= 1826, y3= 1851 },
new PolarStackedAreaData { x= "IND", text = "India", y= 1857, y1= 20
34, y2= 2088, y3= 2256 },
new PolarStackedAreaData { x= "CAN", text = "Canada", y= 1843, y1= 1
793, y2= 1553, y3= 1529 }
};
ViewBag.dataSource = data;
return View();
}
public class PolarStackedAreaData
{
public string x;
public double y;
public double y1;
public double y2;
public double y3;
public string text;
}
}
}
Column
353
To render a column draw type, use series drawType as Column .
razor
polar-column.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Column)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
354
public partial class ChartController : Controller
{
public ActionResult PolarColumn()
{
List<PolarColumnChartData> chartData = new List<PolarColumnChartData>
{
new PolarColumnChartData { xValue = "Jan", yValue = -7.1 },
new PolarColumnChartData { xValue = "Feb", yValue = -3.7 },
new PolarColumnChartData { xValue = "Mar", yValue = 0.8 },
new PolarColumnChartData { xValue = "Apr", yValue = 6.3 },
new PolarColumnChartData { xValue = "May", yValue = 13.3 },
new PolarColumnChartData { xValue = "Jun", yValue = 18.0 },
new PolarColumnChartData { xValue = "Jul", yValue = 19.8 },
new PolarColumnChartData { xValue = "Aug", yValue = 18.1 },
new PolarColumnChartData { xValue = "Sep", yValue = 13.1 },
new PolarColumnChartData { xValue = "Oct", yValue = 4.1 },
new PolarColumnChartData { xValue = "Nov", yValue = -3.8 },
new PolarColumnChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
{
public string xValue;
public double yValue;
}
}
}
Stacked Column
razor
polar-stackedcolumn.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
355
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingColumn)
.Name("2013")
.XName("x")
.YName("y")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingColumn)
.Name("2014")
.XName("x")
.YName("y1")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingColumn)
.Name("2015")
.XName("x")
.YName("y2")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.StackingColumn)
.Name("2016")
.XName("x")
.YName("y3")
.Width(2)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}M")
.Interval(5000)
.Minimum(20000)
.Maximum(0)
)
.Title("GDP, Current Prices (in Billions)")
.Tooltip(tp => tp.Enable(true))
.Load("load").Render()
)
}
356
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarStackedColumn()
{
List<PolarStackedColumnData> data = new List<PolarStackedColumnData>
{
new PolarStackedColumnData { x= "JPN", text = "Japan", y= 5156, y1=
4849, y2= 4382, y3= 4939 },
new PolarStackedColumnData { x= "DEU", text = "Germany", y= 3754, y1
= 3885, y2= 3365, y3= 3467 },
new PolarStackedColumnData { x= "FRA", text = "France", y= 2809, y1=
2844, y2= 2420, y3= 2463 },
new PolarStackedColumnData { x= "GBR", text = "UK", y= 2721, y1= 3002
, y2= 2863, y3= 2629 },
new PolarStackedColumnData { x= "BRA", text = "Brazil", y= 2472, y1=
2456, y2= 1801, y3= 1799 },
new PolarStackedColumnData { x= "RUS", text = "Russia", y= 2231, y1=
2064, y2= 1366, y3= 1281 },
new PolarStackedColumnData { x= "ITA", text = "Italy", y= 2131, y1=
2155, y2= 1826, y3= 1851 },
new PolarStackedColumnData { x= "IND", text = "India", y= 1857, y1=
2034, y2= 2088, y3= 2256 },
new PolarStackedColumnData { x= "CAN", text = "Canada", y= 1843, y1=
1793, y2= 1553, y3= 1529 }
};
ViewBag.dataSource = data;
return View();
}
public class PolarStackedColumnData
{
public string x;
public double y;
public double y1;
public double y2;
public double y3;
public string text;
}
}
}
357
Range Column
razor
polar-rangecolumn.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.RangeColumn)
.Name("Germany")
.XName("x")
.High("high")
.Low("low")
.Width(2)
.Border(ViewBag.border)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.StartAngle(90)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}˚C")
.Interval(5)
.Minimum(0)
.Maximum(20)
)
.Title("Maximum and Minimum Temperature")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
358
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: PolarRadarRangeColumn
public ActionResult PolarRadarRangeColumn()
{
List<PolarRangeColumnData> data = new List<PolarRangeColumnData>
{
new PolarRangeColumnData { x= "Jan", low= 2.7, high= 7.1 },
new PolarRangeColumnData { x= "Feb", low= 3.9, high= 7.7 },
new PolarRangeColumnData { x= "Mar", low= 3.2, high= 7.5 },
new PolarRangeColumnData { x= "Apr", low= 4.5, high= 9.8 },
new PolarRangeColumnData { x= "May", low= 6.7, high= 11.4 },
new PolarRangeColumnData { x= "June", low= 8.4, high= 14.4 },
new PolarRangeColumnData { x= "July", low= 11.6, high= 17.2 },
new PolarRangeColumnData { x= "Aug", low= 12.7, high= 17.9 },
new PolarRangeColumnData { x= "Sep", low= 9.5, high= 15.1 },
new PolarRangeColumnData { x= "Oct", low= 5.0, high= 10.5 },
new PolarRangeColumnData { x= "Nov", low= 3.2, high= 7.9 },
new PolarRangeColumnData { x= "Dec", low= 6.1, high= 9.1 }
};
ViewBag.dataSource = data;
ViewBag.border = new ChartBorder { Width = 3, Color = "white" };
ViewBag.data = new string[] { "Polar", "Radar" };
return View();
}
public class PolarRangeColumnData
{
public string x;
public double low;
public double high;
}
}
}
Scatter
razor
polar-scatter.cs
@using Syncfusion.EJ2;
359
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Scatter)
.Name("2015")
.XName("x")
.YName("y")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
)
.PrimaryYAxis(yaxis =>
yaxis.Interval(2)
.Minimum(0)
.Maximum(8)
)
.Title("Real GDP Growth")
.Tooltip(tp => tp.Enable(true))
.Load("load").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: PolarRadarScatter
public ActionResult PolarRadarScatter()
{
List<PolarScatterData> data = new List<PolarScatterData>
{
new PolarScatterData { text= "Myanmar", x= "MMR", y= 7.3 },
360
new PolarScatterData { text= "India", x= "IND", y= 7.9 },
new PolarScatterData { text= "Bangladesh", x= "BGD", y= 6.8 },
new PolarScatterData { text= "Cambodia", x= "KHM", y= 7.0 },
new PolarScatterData { text= "China", x= "CHN", y= 6.9 },
new PolarScatterData { text= "Bhutan", x= "BTN", y= 6.1 },
new PolarScatterData { text= "Iceland", x= "ISL", y= 4.1 },
new PolarScatterData { text= "Nepal", x= "NPL", y= 2.7 },
new PolarScatterData { text= "Pakistan", x= "PAK", y= 4.0 },
new PolarScatterData { text= "Poland", x= "POL", y= 3.9 },
new PolarScatterData { text= "Australia", x= "AUS", y= 2.4 },
new PolarScatterData { text= "Korea", x= "KOR", y= 2.8 },
new PolarScatterData { text= "Singapore", x= "SGP", y= 1.9 },
new PolarScatterData { text= "Canada", x= "CAN", y= 0.9 },
new PolarScatterData { text= "Germany", x= "DEU", y= 1.5 },
new PolarScatterData { text= "Denmark", x= "DNK", y= 1.6 },
new PolarScatterData { text= "France", x= "FRA", y= 1.3 },
new PolarScatterData { text= "Austria", x= "AUT", y= 1.0 }
};
ViewBag.dataSource = data;
ViewBag.marker1 = new {
height = 10,
width = 10,
dataLabel = new { name = "text" }
};
return View();
}
public class PolarScatterData
{
public string text;
public string x;
public double y;
}
}
}
Radar Chart
To render a radar series, use series type as Radar .
Draw Type
Line
To render a line draw type, use series drawType as Line . isClosed property specifies
whether to join start and end point of a line series used in polar chart to form a closed path.
Default value of isClosed is true.
361
razor
radar-line.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Radar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Line)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
362
public ActionResult PolarLine()
{
List<RadarLineChartData> chartData = new List<RadarLineChartData>
{
new RadarLineChartData { xValue = "Jan", yValue = -7.1 },
new RadarLineChartData { xValue = "Feb", yValue = -3.7 },
new RadarLineChartData { xValue = "Mar", yValue = 0.8 },
new RadarLineChartData { xValue = "Apr", yValue = 6.3 },
new RadarLineChartData { xValue = "May", yValue = 13.3 },
new RadarLineChartData { xValue = "Jun", yValue = 18.0 },
new RadarLineChartData { xValue = "Jul", yValue = 19.8 },
new RadarLineChartData { xValue = "Aug", yValue = 18.1 },
new RadarLineChartData { xValue = "Sep", yValue = 13.1 },
new RadarLineChartData { xValue = "Oct", yValue = 4.1 },
new RadarLineChartData { xValue = "Nov", yValue = -3.8 },
new RadarLineChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class RadarLineChartData
{
public string xValue;
public double yValue;
}
}
}
Customization
Start Angle
You can customize the start angle of the polar series using startAngle property. By default,
startAngle is 0 degree.
razor
start-angle.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
363
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Column)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
.Marker(ViewBag.marker1)
.StartAngle(90)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarColumn()
{
List<PolarColumnChartData> chartData = new List<PolarColumnChartData>
{
new PolarColumnChartData { xValue = "Jan", yValue = -7.1 },
364
new PolarColumnChartData { xValue = "Feb", yValue = -3.7 },
new PolarColumnChartData { xValue = "Mar", yValue = 0.8 },
new PolarColumnChartData { xValue = "Apr", yValue = 6.3 },
new PolarColumnChartData { xValue = "May", yValue = 13.3 },
new PolarColumnChartData { xValue = "Jun", yValue = 18.0 },
new PolarColumnChartData { xValue = "Jul", yValue = 19.8 },
new PolarColumnChartData { xValue = "Aug", yValue = 18.1 },
new PolarColumnChartData { xValue = "Sep", yValue = 13.1 },
new PolarColumnChartData { xValue = "Oct", yValue = 4.1 },
new PolarColumnChartData { xValue = "Nov", yValue = -3.8 },
new PolarColumnChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
{
public string xValue;
public double yValue;
}
}
}
Coefficient in axis
You can customize the radius of the polar series and radar series using coefficient property.
By default, coefficient is 100.
razor
co-efficient.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Polar)
.DrawType(Syncfusion.EJ2.Charts.ChartDrawType.Area)
.Name("Warmest")
.XName("xValue")
.YName("yValue")
.Width(2)
365
.Marker(ViewBag.marker1)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelPlacement(Syncfusion.EJ2.Charts.LabelPlacement.OnTicks)
.Interval(1)
.Coefficient(100)
.Title("Months")
)
.PrimaryYAxis(yaxis =>
yaxis.Title("Temperature (Celsius)").LabelFormat("{value}°C")
.Interval(10)
.Minimum(-25)
.Maximum(25)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
)
.Title("Alaska Weather Statistics - 2016").Tooltip(tp=>tp.Enable(true)).Load("loa
d").Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult PolarArea()
{
List<PolarAreaChartData> chartData = new List<PolarAreaChartData>
{
new PolarAreaChartData { xValue = "Jan", yValue = -7.1 },
new PolarAreaChartData { xValue = "Feb", yValue = -3.7 },
new PolarAreaChartData { xValue = "Mar", yValue = 0.8 },
new PolarAreaChartData { xValue = "Apr", yValue = 6.3 },
new PolarAreaChartData { xValue = "May", yValue = 13.3 },
new PolarAreaChartData { xValue = "Jun", yValue = 18.0 },
new PolarAreaChartData { xValue = "Jul", yValue = 19.8 },
new PolarAreaChartData { xValue = "Aug", yValue = 18.1 },
new PolarAreaChartData { xValue = "Sep", yValue = 13.1 },
new PolarAreaChartData { xValue = "Oct", yValue = 4.1 },
366
new PolarAreaChartData { xValue = "Nov", yValue = -3.8 },
new PolarAreaChartData { xValue = "Dec", yValue = -6.8 },
};
ViewBag.dataSource = chartData;
ViewBag.marker1 = new {
visible = true,
height = 10,
width = 10,
shape = "Pentagon",
};
return View();
}
public class PolarLineChartData
{
public string xValue;
public double yValue;
}
}
}
See Also
Data label
Tooltip
367
Financial Charts
Financial charts are used to illustrate the movements in the price of a financial instrument over
time.
Hilo
Hilo Series illustrates the price movements in stock using the high and low values. To render a
Hilo series, use series type as Hilo .
Hilo series requires 3 fields (x, high and low) to show the high and low price in the stock.
razor
hilo.cs
@using Syncfusion.EJ2;
@section ControlsSection{
<script src="chart/series/hilo/financial-data.js"></script>
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Hilo).XName("x").High("hig
h").Low("low").Close("close").Open("Open").DataSource("returnValue").Name("Apple Inc").
Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Maj
orGridLines(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip)
).ChartArea(area => area.Border(ViewBag.ChartBorder)).Crosshair(cr => cr.Enable(
true).LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Line(ViewBag.line)).Load("load"
).LegendSettings(lg => lg.Visible(false)).Tooltip(tt => tt.Enable(true).Shared(true)).T
itle("AAPL Historical").Load("load").Render()
}
<script>
var dataSource = window.chartData;
var date1 = new Date('2017-01-01');
var returnValue = dataSource.filter(filterValue);
function filterValue(value) {
return value.x >= date1;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
368
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Hilo()
{
ViewBag.line = new
{
width = 0.02,
};
ViewBag.majorGridLines = new { width = 0.0001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
HiloOpenClose series requires 5 fields (x, high, low, open and close) to show the high, low, open
and close price values in the stock.
razor
hilo-openclose.cs
@using Syncfusion.EJ2;
@section ControlsSection{
<script src="chart/series/hilo/financial-data.js"></script>
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.HiloOpenClose).XName("x").
High("high").Low("low").Close("close").Open("open").DataSource("returnValue").Name("War
mest").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Maj
orGridLines(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.Minimum(100).Maximum(180).Interval(20).MajorTickLines(Vi
ewBag.majorTickLines).LineStyle(ViewBag.lineStyle).Title("Price").LabelFormat("${value}"
)
369
).ChartArea(area => area.Border(ViewBag.ChartBorder)).Crosshair(cr => cr.Enable(
true).Line(ViewBag.line).LineType(Syncfusion.EJ2.Charts.LineType.Vertical)).Load("load"
).LegendSettings(lg => lg.Visible(false)).Tooltip(tt => tt.Enable(true).Shared(true)).T
itle("AAPL Historical").Load("load").Render()
}
<script>
var dataSource = window.chartData;
var date1 = new Date('2017-01-01');
var returnValue = dataSource.filter(filterValue);
function filterValue(value) {
return value.x >= date1;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult HiloOpenClose()
{
ViewBag.line =new {
width= 0.02,
};
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
370
By default, bullFillColor is set as red and bearFillColor is set as green.
razor
custom-openclose.cs
@using Syncfusion.EJ2;
@section ControlsSection{
<script src="chart/series/hilo/financial-data.js"></script>
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.HiloOpenClose)
.XName("x").High("high").Low("low")
.Close("close")
.Open("open")
.DataSource("returnValue")
.BearFillColor("#2ecd71")
.BullFillColor("#e74c3d")
.Name("Warmest").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Maj
orGridLines(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.Minimum(100).Maximum(180).Interval(20).MajorTickLines(Vi
ewBag.majorTickLines).LineStyle(ViewBag.lineStyle).Title("Price").LabelFormat("${value}"
)
).ChartArea(area => area.Border(ViewBag.ChartBorder)).Crosshair(cr => cr.Enable(
true).Line(ViewBag.line).LineType(Syncfusion.EJ2.Charts.LineType.Vertical)).Load("load"
).LegendSettings(lg => lg.Visible(false)).Tooltip(tt => tt.Enable(true).Shared(true)).T
itle("AAPL Historical").Load("load").Render()
}
<script>
var dataSource = window.chartData;
var date1 = new Date('2017-01-01');
var returnValue = dataSource.filter(filterValue);
function filterValue(value) {
return value.x >= date1;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
371
public partial class ChartController : Controller
{
public ActionResult HiloOpenClose()
{
ViewBag.line =new {
width= 0.02,
};
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
Candle
Candle series are similar to Hilo Open Close series, are used to represent the low, high, open
and closing price over time. To render a candle series, use series type as Candle .
razor
candle.cs
@using Syncfusion.EJ2;
@section ControlsSection{
<script src="chart/series/hilo/financial-data.js"></script>
@Html.EJS().Chart("container").Rows(rows =>
{
rows.Height("30%").Add();
rows.Height("70%").Add();
}).Axes(ax =>
{
ax.Name("secondary").
OpposedPosition(true).
Minimum(100).
Maximum(180).
RowIndex(1).
PlotOffset(30).
Title("Price").LabelFormat("${value}").
Interval(20).MajorTickLines(ViewBag.majorTickLines).LineStyle(ViewBag.lineStyle)
.Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("x").YName("
372
volume").Name("Volume").DataSource("returnValue").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").High("h
igh").Low("low").Close("close").Open("open").DataSource("returnValue").YAxisName("secon
dary").Name("Apple Inc").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Maj
orGridLines(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.Minimum(500000000).Maximum(130000000).ValueType(Syncfusi
on.EJ2.Charts.ValueType.Logarithmic).OpposedPosition(true).Title("Volume").LineStyle(Vi
ewBag.lineStyle)
).Crosshair(cr => cr.Enable(true).LineType(Syncfusion.EJ2.Charts.LineType.Vertic
al)).ChartArea(area => area.Border(ViewBag.ChartBorder)).LegendSettings(lg => lg.Visibl
e(true)).Tooltip(tt => tt.Enable(true).Shared(true)).Title("AAPL Historical").Width("60
%").Load("load").Render()
}
<script>
var dataSource = window.chartData;
var date1 = new Date('2017-01-01');
var returnValue = dataSource.filter(filterValue);
function filterValue(value) {
return value.x >= date1;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Candle()
{
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairTooltip= new { enable= true };
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
return View();
}
}
}
Hollow Candles
373
Candle charts allow to visually compare the current price with previous price by customizing the
appearance.
States Description
Filled candle sticks are filled when the close value is lesser than the open value
Unfilled candle sticks are unfilled when the close value is greater than the open value
The color of the candle will be defined by comparing with previous values.
Bear color will be applied when the current closing value is greater than the previous closing
value. Bull color will be applied when the current closing value is less than the previous closing
value.
Solid Candles
bearFillColor will be applied when the opening value is less than the closing value.
bullFillColor will be applied when the opening value is greater than closing value.
razor
solid-candles.cs
@using Syncfusion.EJ2;
@section ControlsSection{
<script src="chart/series/hilo/financial-data.js"></script>
@Html.EJS().Chart("container").Rows(rows =>
{
rows.Height("30%").Add();
rows.Height("70%").Add();
}).Axes(ax =>
{
ax.Name("secondary").
OpposedPosition(true).
Minimum(100).
Maximum(180).
RowIndex(1).
PlotOffset(30).
Title("Price").LabelFormat("${value}").
Interval(20).MajorTickLines(ViewBag.majorTickLines).LineStyle(ViewBag.lineStyle)
.Add();
}
).Series(series =>
374
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column)
.XName("x").YName("volume")
.Name("Volume")
.DataSource("returnValue").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle)
.XName("x").High("high")
.Low("low")
.Close("close")
.Open("open")
.BearFillColor("#2ecd71")
.BullFillColor("#e74c3d")
.DataSource("returnValue")
.YAxisName("secondary")
.Name("Apple Inc").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Maj
orGridLines(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.Minimum(500000000).Maximum(130000000).ValueType(Syncfusi
on.EJ2.Charts.ValueType.Logarithmic).OpposedPosition(true).Title("Volume").LineStyle(Vi
ewBag.lineStyle)
).Crosshair(cr => cr.Enable(true).LineType(Syncfusion.EJ2.Charts.LineType.Vertic
al)).ChartArea(area => area.Border(ViewBag.ChartBorder)).LegendSettings(lg => lg.Visibl
e(true)).Tooltip(tt => tt.Enable(true).Shared(true)).Title("AAPL Historical").Width("60
%").Load("load").Render()
}
<script>
var dataSource = window.chartData;
var date1 = new Date('2017-01-01');
var returnValue = dataSource.filter(filterValue);
function filterValue(value) {
return value.x >= date1;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Candle()
375
{
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairTooltip= new { enable= true };
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
return View();
}
}
}
See Also
Data label
Tooltip
376
Box and whisker
To render a box and whisker chart, use series type as BoxAndWhisker . The field y requires n
number of data or it should contains minimum of five values to plot a segment.
razor
box.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(
series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.BoxAndWhisker).
Name("Department").
DataSource(ViewBag.dataSource).
XName("xValue").
YName("yValue").
Marker(ViewBag.marker).Add();
}).PrimaryXAxis(
xAxis =>
xAxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Tr
im)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
.MajorGridLines(ViewBag.gridlines)
).PrimaryYAxis(
yAxis =>
yAxis.Minimum(10).
Maximum(60).
Interval(10).
Title("Age").
MajorGridLines(ViewBag.gridlines).
MajorTickLines(ViewBag.ticklines)
).Title("Employee Age Group in Various Department").LegendSettings(
legend => {
legend.Visible(false);
}).Tooltip(
tooltip =>
{
tooltip.Enable(true);
}).ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
377
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult BoxAndWhisker()
{
Double[] y1 = { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34,
32, 34, 36, 35, 38 };
Double[] y2 = { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 };
Double[] y3 = { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 };
Double[] y4 = { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 };
Double[] y5 = { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 };
Double[] y6 = { 27, 26, 28, 29, 29, 29, 32, 35, 32, 38, 53 };
Double[] y7 = { 21, 23, 24, 25, 26, 27, 28, 30, 34, 36, 38 };
Double[] y8 = { 26, 28, 29, 30, 32, 33, 35, 36, 52 };
Double[] y9 = { 28, 29, 30, 31, 32, 34, 35, 36 };
378
public class BoxAndWhiskerChartData
{
public string xValue;
public double[] yValue;
}
}
}
boxPlotMode
You can change the rendering mode of the Box and Whisker series using the boxPlotMode
property. The default boxPlotMode is exclusive .The other boxPlotMode available are
inclusive and normal .
To render a box and whisker chart, use series type as BoxAndWhisker . The field y requires n
number of data or it should contains minimum of five values to plot a segment.
razor
box-plot.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(
series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.BoxAndWhisker).
Name("Department").
BoxPlotMode("Normal").
DataSource(ViewBag.dataSource).
XName("xValue").
YName("yValue").
Marker(ViewBag.marker).Add();
}).PrimaryXAxis(
xAxis =>
xAxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Tr
im)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
.MajorGridLines(ViewBag.gridlines)
).PrimaryYAxis(
yAxis =>
yAxis.Minimum(10).
Maximum(60).
379
Interval(10).
Title("Age").
MajorGridLines(ViewBag.gridlines).
MajorTickLines(ViewBag.ticklines)
).Title("Employee Age Group in Various Department").LegendSettings(
legend => {
legend.Visible(false);
}).Tooltip(
tooltip =>
{
tooltip.Enable(true);
}).ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult BoxAndWhisker()
{
Double[] y1 = { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34,
32, 34, 36, 35, 38 };
Double[] y2 = { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 };
Double[] y3 = { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 };
Double[] y4 = { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 };
Double[] y5 = { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 };
Double[] y6 = { 27, 26, 28, 29, 29, 29, 32, 35, 32, 38, 53 };
Double[] y7 = { 21, 23, 24, 25, 26, 27, 28, 30, 34, 36, 38 };
Double[] y8 = { 26, 28, 29, 30, 32, 33, 35, 36, 52 };
Double[] y9 = { 28, 29, 30, 31, 32, 34, 35, 36 };
380
new BoxAndWhiskerChartData { xValue = "Inventory", yValue = y7 },
new BoxAndWhiskerChartData { xValue = "Graphics", yValue = y8 },
new BoxAndWhiskerChartData { xValue = "Training", yValue = y9 },
};
ViewBag.dataSource = chartData;
ViewBag.marker = new
{
visible = true,
height = 10,
width = 10
};
ViewBag.gridlines = new { width = 0.00001 };
ViewBag.ticklines = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class BoxAndWhiskerChartData
{
public string xValue;
public double[] yValue;
}
}
}
showMean
In Box and Whisker series showMean property is used to show the box and whisker average
value. The default value of showMean is false.
razor
box-mean.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(
series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.BoxAndWhisker).
Name("Department").
BoxPlotMode("Normal").
ShowMean("false").
DataSource(ViewBag.dataSource).
XName("xValue").
YName("yValue").
Marker(ViewBag.marker).Add();
}).PrimaryXAxis(
381
xAxis =>
xAxis.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
.LabelIntersectAction(Syncfusion.EJ2.Charts.LabelIntersectAction.Tr
im)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift)
.MajorGridLines(ViewBag.gridlines)
).PrimaryYAxis(
yAxis =>
yAxis.Minimum(10).
Maximum(60).
Interval(10).
Title("Age").
MajorGridLines(ViewBag.gridlines).
MajorTickLines(ViewBag.ticklines)
).Title("Employee Age Group in Various Department").LegendSettings(
legend => {
legend.Visible(false);
}).Tooltip(
tooltip =>
{
tooltip.Enable(true);
}).ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult BoxAndWhisker()
{
Double[] y1 = { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34,
32, 34, 36, 35, 38 };
Double[] y2 = { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 };
Double[] y3 = { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 };
Double[] y4 = { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 };
Double[] y5 = { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 };
Double[] y6 = { 27, 26, 28, 29, 29, 29, 32, 35, 32, 38, 53 };
Double[] y7 = { 21, 23, 24, 25, 26, 27, 28, 30, 34, 36, 38 };
Double[] y8 = { 26, 28, 29, 30, 32, 33, 35, 36, 52 };
382
Double[] y9 = { 28, 29, 30, 31, 32, 34, 35, 36 };
Waterfall Chart
Waterfall chart helps to understand the cumulative effect of the sequentially introduced positive
and negative values. To render a Waterfall series, use series type as Waterfall .
intermediateSumIndexes property of waterfall is used to represent the in between the sum
values and sumIndexes is used to represent the cumulative sum values.
razor
waterfall.cs
@using Syncfusion.EJ2;
@section ControlsSection{
383
@Html.EJS().Chart("container").Series(series =>
{
series.Width(2).XName("xValue").YName("yValue").IntermediateSumIndexes(ViewBag.i
ntermediateSumIndexes).SumIndexes(ViewBag.sumIndexes).Marker(ViewBag.marker).Name("USA"
).ColumnWidth(0.9).Type(Syncfusion.EJ2.Charts.ChartSeriesType.Waterfall).DataSource(Vie
wBag.dataSource).Add();
}
).ChartArea(area => area.Border(ViewBag.ChartBorder)).PrimaryXAxis(py => py.ValueTyp
e(Syncfusion.EJ2.Charts.ValueType.Category).MajorGridLines(ViewBag.majorGridLines).Plot
Offset(20)).PrimaryYAxis(py => py.Minimum(0).Maximum(5000).Interval(1000).MajorGridLine
s(ViewBag.majorGridLines).Title("Expenditure")).Title("Company Revenue and Profit").Leg
endSettings(lg => lg.Visible(true)).Tooltip(tl => tl.Enable(true)).Load("load").TextRen
der("textRender").AxisLabelRender("axisLabelRender").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Waterfall()
{
List<WaterfallChartData> chartData = new List<WaterfallChartData>
{
new WaterfallChartData { xValue = "Income", yValue = 4711 },
new WaterfallChartData { xValue = "Sales", yValue = -1015 },
new WaterfallChartData { xValue = "Development", yValue = -688 },
new WaterfallChartData { xValue = "Revenue", yValue = 1030 },
new WaterfallChartData { xValue = "Balance" },
new WaterfallChartData { xValue = "Expense", yValue = -361 },
new WaterfallChartData { xValue = "Tax", yValue = -695 },
new WaterfallChartData { xValue = "Net Profit" },
};
ViewBag.dataSource = chartData;
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.intermediateSumIndexes = new int[] {4};
ViewBag.sumIndexes = new int[] {7};
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.chartArea = new
{
border = new
384
{
width = 0.1
}
};
ViewBag.marker=new
{
dataLabel= new { visible =true, font= new { color= "#ffffff" } }
};
return View();
}
public class WaterfallChartData
{
public string xValue;
public double yValue;
}
}
}
The negative changes of waterfall charts is represented by using negativeFillColor and the
summary changes are represented by using summaryFillColor properties.
razor
custom-waterfall.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Width(2).XName("xValue").YName("yValue").IntermediateSumIndexes(ViewBag.i
ntermediateSumIndexes).SumIndexes(ViewBag.sumIndexes).Marker(ViewBag.marker).NegativeFi
llColor("#e56590").Name("USA").ColumnWidth(0.9).Type(Syncfusion.EJ2.Charts.ChartSeriesT
ype.Waterfall).DataSource(ViewBag.dataSource).Add();
}
).ChartArea(area => area.Border(ViewBag.ChartBorder)).PrimaryXAxis(py => py.ValueTyp
e(Syncfusion.EJ2.Charts.ValueType.Category).MajorGridLines(ViewBag.majorGridLines).Plot
Offset(20)).PrimaryYAxis(py => py.Minimum(0).Maximum(5000).Interval(1000).MajorGridLine
s(ViewBag.majorGridLines).Title("Expenditure")).Title("Company Revenue and Profit").Leg
endSettings(lg => lg.Visible(true)).Tooltip(tl => tl.Enable(true)).Load("load").TextRen
der("textRender").AxisLabelRender("axisLabelRender").Render()
}
using System;
385
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Waterfall
public ActionResult Waterfall()
{
List<WaterfallChartData> chartData = new List<WaterfallChartData>
{
new WaterfallChartData { xValue = "Income", yValue = 4711 },
new WaterfallChartData { xValue = "Sales", yValue = -1015 },
new WaterfallChartData { xValue = "Development", yValue = -688 },
new WaterfallChartData { xValue = "Revenue", yValue = 1030 },
new WaterfallChartData { xValue = "Balance" },
new WaterfallChartData { xValue = "Expense", yValue = -361 },
new WaterfallChartData { xValue = "Tax", yValue = -695 },
new WaterfallChartData { xValue = "Net Profit" },
};
ViewBag.dataSource = chartData;
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.intermediateSumIndexes = new int[] {4};
ViewBag.sumIndexes = new int[] {7};
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.chartArea = new
{
border = new
{
width = 0.1
}
};
ViewBag.marker=new
{
dataLabel= new { visible =true, font= new { color= "#ffffff" } }
};
return View();
}
public class WaterfallChartData
{
public string xValue;
public double yValue;
}
386
}
razor
errorbar.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
387
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
ViewBag.errorBar = new { visible = true, verticalError = 3, horizontalError
= 3 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
To change the error bar rendering type using type option of error bar. To change the error bar
line length you can use verticalError property.
razor
error-type.cs
@using Syncfusion.EJ2;
388
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
389
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
ViewBag.errorBar = new { visible = true, type=Percentage, verticalError = 3
};
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
To customize the error bar type, set error bar type as Custom and then change the
horizontal/vertical positive and negative error of error bar.
razor
custom-error.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
390
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
391
ViewBag.errorBar = new { visible = true, type="Custom", mode="Both", verti
calPostiveError=3, horizontalPositiveError=2,
verticalNegativeError=3, horizontalNegativeError=2
};
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
Error bar mode is used to define whether the error bar line has to be drawn horizontally, vertically
or in both side. To change the error bar mode use mode option.
razor
error-mode.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
392
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
ViewBag.errorBar = new { visible = true, mode = "Horizontal" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
393
Changing Error Bar Direction
To change the error bar direction to plus, minus or both side using direction option.
razor
error-direction.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
394
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
ViewBag.errorBar = new { visible = true, mode = "Horizontal", direction = "
Minus" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
To customize the error bar cap length, width and fill color, you can use errorBarCap option.
razor
error-cap.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container")
.Series(sr =>
{
sr.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.Name("Sales")
.XName("xValue")
395
.YName("yValue")
.Marker(ViewBag.marker)
.ErrorBar(ViewBag.errorBar)
.DataSource(ViewBag.dataSource).Add();
})
.PrimaryXAxis(xaxis =>
xaxis.MinorGridLines(ViewBag.gridlines)
.Interval(1)
.ValueType(Syncfusion.EJ2.Charts.ValueType.Category)
)
.PrimaryYAxis(yaxis =>
yaxis.LabelFormat("{value}%")
.LineStyle(ViewBag.linestyle)
.Minimum(15)
.Maximum(45)
)
.Title("Sales Distribution of Car by Region")
.Tooltip(tp => tp.Enable(true))
.LegendSettings(lg => lg.Visible(false))
.Load("load").ChartArea(area => area.Border(ViewBag.ChartBorder)).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult ErrorBar()
{
List<ErrorBarChartData> chartData = new List<ErrorBarChartData>
{
new ErrorBarChartData { xValue = "IND", yValue = 24 },
new ErrorBarChartData { xValue = "AUS", yValue = 20 },
new ErrorBarChartData { xValue = "USA", yValue = 35 },
new ErrorBarChartData { xValue = "DEU", yValue = 27 },
new ErrorBarChartData { xValue = "ITA", yValue = 30 },
new ErrorBarChartData { xValue = "UK", yValue = 41 },
new ErrorBarChartData { xValue = "RUS", yValue = 26 }
};
ViewBag.dataSource = chartData;
396
ViewBag.gridlines = new { width = 0 };
ViewBag.linestyle = new { width = 0 };
ViewBag.marker = new {
Width = 10,
Height = 10
};
ViewBag.errorBar = new { visible = true, errorBarCap = new {
length = 10,
width = 10,
color = '#0000ff'
} };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class ErrorBarChartData
{
public string xValue;
public double yValue;
}
}
}
Vertical Chart
In EJ2 chart, you can draw a chart in vertical manner by changing orientation of the axis. All
series types support this feature. You can use isTransposed property in chart to render a chart
in vertical manner.
razor
vertical.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Spline).
Marker(ViewBag.Marker).
XName("xValue").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").IsTransposed(true).Render()
using System;
397
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<VerticalChartData> chartData = new List<VerticalChartData>
{
new VerticalChartData { xValue = "Sun", yValue = 15 },
new VerticalChartData { xValue = "Mon", yValue = 22 },
new VerticalChartData { xValue = "Tue", yValue = 32 },
new VerticalChartData { xValue = "Wed", yValue = 31 },
new VerticalChartData { xValue = "Thu", yValue = 29 },
new VerticalChartData { xValue = "Fri", yValue = 24 },
new VerticalChartData { xValue = "Sat", yValue = 18 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string xValue;
public double yValue;
}
}
}
See Also
Data label
Tooltip
398
Chart Series
Multiple Series
You can add multiple series to the chart by using series property. The series are rendered in
the order as it is added to the series array.
razor
multiple-series.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
399
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
List<ColumnChartData> chartData1 = new List<ColumnChartData>
{
new ColumnChartData { x= "USA1", yValue= 46 },
new ColumnChartData { x= "GBR1", yValue= 27 },
new ColumnChartData { x= "CHN1", yValue= 26 },
new ColumnChartData { x= "UK1", yValue= 26 },
new ColumnChartData { x= "AUS1", yValue= 26 },
new ColumnChartData { x= "IND1", yValue= 26 },
new ColumnChartData { x= "DEN1", yValue= 26 },
new ColumnChartData { x= "MEX1", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Combination Series
Combination of different types like Line, column etc, can be rendered in a chart.
Bar series cannot be combined with any other series as the axis orientation is different from
other series.
razor
combination.cs
@using Syncfusion.EJ2;
400
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
.Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource1).
Name("Silver").
.Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)
.IsIndexed(true)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "UK", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "IND", yValue= 26 },
new ColumnChartData { x= "DEN", yValue= 26 },
new ColumnChartData { x= "MEX", yValue= 26 },
};
401
List<ColumnChartData> chartData1 = new List<ColumnChartData>
{
new ColumnChartData { x= "USA1", yValue= 46 },
new ColumnChartData { x= "GBR1", yValue= 27 },
new ColumnChartData { x= "CHN1", yValue= 26 },
new ColumnChartData { x= "UK1", yValue= 26 },
new ColumnChartData { x= "AUS1", yValue= 26 },
new ColumnChartData { x= "IND1", yValue= 26 },
new ColumnChartData { x= "DEN1", yValue= 26 },
new ColumnChartData { x= "MEX1", yValue= 26 },
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
402
Technical Indicators
A technical indicator is a mathematical calculation based on historic price, volume or open
interest information that aims to forecast financial market direction.
Accumulation Distribution
Accumulation Distribution combines price and volume to show how money may be flowing into or
out of stock. To render a Accumulation Distribution Indicator, use indicator type as
AccumulationDistribution . To calculate the signal line volume field is additionally added with
dataSource .
razor
ad.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/ad/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").
OpposedPosition(true).
Minimum(-7000000000).
Maximum(5000000000).
Interval(6000000000).
Title("Accumulation Distribution").MajorTickLines(ViewBag.majorTickLines).LineSt
yle(ViewBag.lineStyle).
RowIndex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").KPeriod(2).DPeriod(3).YAxisName("secondary").Period(3
).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.AccumulationDistribution).Field(Syncfu
403
sion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Add();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => {
px.ZoomFactor(0.2).MajorGridLines(dataT).ZoomPosition(0.6).MajorGridLine
s(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime);
}).PrimaryYAxis(py => py.RowIndex(1).OpposedPosition(true).LineStyle(ViewBag
.lineStyle).Title("Price").Minimum(80).Maximum(170).Interval(30).LabelFormat("${value}"
).PlotOffset(25)
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: AccumulationDistribution
public ActionResult AccumulationDistribution()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
razor
404
atr.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/atr/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").LineStyle(ViewBag.Line).Title("ATR").MajorTickLines(Vie
wBag.majorGridLines).OpposedPosition(true).Minimum(0).Maximum(14).Interval(7).RowIndex(0
).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").KPeriod(2).DPeriod(3).YAxisName("secondary").Period(3
).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Atr).Field(Syncfusion.EJ2.Charts.Finan
cialDataFields.Close).SeriesName("Apple Inc").Add();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).MajorGridLines(Vie
wBag.Line).ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
).PrimaryYAxis(py => py.LineStyle(ViewBag.Line).RowIndex(1).OpposedPositio
n(true).Title("Price").Minimum(80).Maximum(170).Interval(30).LabelFormat("{value}M").Pl
otOffset(25)
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
405
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: ATR
public ActionResult ATR()
{
ViewBag.Line = new
{
width = 0.0001
};
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
Bollinger Band
A chart overlay that shows the upper and lower limits of normal price movements based on the
standard deviation of prices. To render a Bollinger Band, use indicator type as BollingerBand .
Bollinger band will be represented by three lines (upperLine, lowerLine, signalLine).Bollinger
Band default values of the period is 14 and standardDeviations is 2.
razor
bollinger.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/bollinger/financial-data.js"></script>
@section ControlsSection{
@(Html.EJS().Chart("container-vertical").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle)
.XName("x")
.YName("y")
.High("high")
.Low("low")
.Open("open")
.Close("close")
.Volume("volume")
.BearFillColor("#2ecd71")
.BullFillColor("#e74c3d")
.DataSource("dataSource")
.Name("Apple Inc")
406
.Width(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff")
.Period(14)
.UpperLine(ViewBag.upperline)
.LowerLine(ViewBag.lowerline)
.Animation(ViewBag.animation)
.Type(Syncfusion.EJ2.Charts.TechnicalIndicators.BollingerBands)
.Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close)
.SeriesName("Apple Inc").Add();
})
.ZoomSettings(zn => zn.EnableSelectionZooming(true)
.Mode(Syncfusion.EJ2.Charts.ZoomMode.X))
.Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enable(tr
ue))
.PrimaryXAxis(px => px.ZoomFactor(0.2).CrosshairTooltip(ViewBag.crosshairtoolti
p).MajorGridLines(ViewBag.gridlines).ZoomPosition(0.6).ValueType(Syncfusion.EJ2.Charts.
ValueType.DateTime))
.PrimaryYAxis(py => py.Title("Price").Minimum(50).Maximum(170).Interval(30).Lin
eStyle(ViewBag.linestyle).LabelFormat("{value}M"))
.Title("AAPL 2012-2017")
.Tooltip(tl => tl.Enable(true).Shared(true))
.LegendSettings(lg => lg.Visible(false))
.ChartArea(area => area.Border(ViewBag.ChartBorder)).Load("load").Render()
)
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Bollinger()
{
ViewBag.animation = new { enable = true };
ViewBag.upperline = new { color = "#ffb735", width = 1 };
407
ViewBag.lowerline = new { color = "#f2ec2f", width = 1 };
ViewBag.gridlines = new { width = 0.0001 };
ViewBag.linestyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairtooltip = new { enable = true };
return View();
}
}
}
Customization of BollingerBand
stroke , stroke-width , and color of upperLine can be customized by using, upperLine , and
the lowerLine can be customized by using lowerLine properties of indicator.
razor
ema.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/ema/financial-data.js"></script>
@section ControlsSection{
@(Html.EJS().Chart("container-vertical").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle)
.XName("x")
.YName("y")
.High("high")
.Low("low")
.Open("open")
.Close("close")
.Volume("volume")
.BearFillColor("#2ecd71")
.BullFillColor("#e74c3d")
.DataSource("dataSource")
.Name("Apple Inc")
.Width(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff")
.Period(14)
.Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Ema)
408
.Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close)
.SeriesName("Apple Inc").Add();
})
.ZoomSettings(zn => zn.EnableSelectionZooming(true)
.Mode(Syncfusion.EJ2.Charts.ZoomMode.X))
.Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enable(tr
ue))
.PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).MajorGridLines(ViewBag
.border).ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime))
.PrimaryYAxis(py => py.Title("Price").Minimum(50).LineStyle(ViewBag.border).Max
imum(170).Interval(30).LabelFormat("{value}M"))
.Title("AAPL 2012-2017")
.Tooltip(tl => tl.Enable(true).Shared(true))
.LegendSettings(lg => lg.Visible(false))
.ChartArea(area => area.Border(ViewBag.ChartBorder)).Load("load").Render()
)
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Bollinger()
{
ViewBag.animation = new { enable = true };
ViewBag.upperline = new { color = "#ffb735", width = 1 };
ViewBag.lowerline = new { color = "#f2ec2f", width = 1 };
ViewBag.gridlines = new { width = 0.0001 };
ViewBag.linestyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairtooltip = new { enable = true };
return View();
}
}
}
409
Momentum
Momentum shows the speed at which the price of the stock is changing. To render a Momentum
indicator, use indicator type as Momentum . Momentum indicator will be represented by two
lines (upperLine, signalLine).In momentum indicator the upperBand value is always render at the
value 100.
razor
momentum.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/momentum/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").OpposedPosition(true).Minimum(80).Maximum(120).Interval(
20).Title("Momentum").LineStyle(ViewBag.lineStyle).MajorGridLines(ViewBag.majorGridLine
s).MajorTickLines(ViewBag.majorTickLines).RowIndex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff")
.YAxisName("secondary")
.UpperLine(ViewBag.upperline)
.Period(3)
.Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Momentum)
.Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close)
.SeriesName("Apple Inc").Add();
})
.ZoomSettings(zn => zn.EnableSelectionZooming(true)
.Mode(Syncfusion.EJ2.Charts.ZoomMode.X))
.Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enable(
true)
)
.PrimaryXAxis(px => px.ZoomFactor(0.2)
.ZoomPosition(0.6)
.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
410
.CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.RowIndex(1)
.OpposedPosition(true).Title("Price")
.Minimum(50).Maximum(170)
.Interval(30)
.LabelFormat("{value}M")
.PlotOffset(25)
.LineStyle(ViewBag.lineStyle)
).Title("AAPL 2012-2017")
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Tooltip(tl => tl.Enable(true).Shared(true))
.LegendSettings(lg => lg.Visible(false)).Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Momentum()
{
ViewBag.animation = new { enable = true };
ViewBag.upperline = new { color = "#ffb735", width = 1 };
ViewBag.lowerline = new { color = "#f2ec2f", width = 1 };
ViewBag.gridlines = new { width = 0.0001 };
ViewBag.linestyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairtooltip = new { enable = true };
return View();
}
}
}
Customization of MomentumIndicator
411
razor
custom-momentum.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/momentum/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").OpposedPosition(true).Minimum(80).Maximum(120).Interval(
20).Title("Momentum").LineStyle(ViewBag.lineStyle).MajorGridLines(ViewBag.majorGridLine
s).MajorTickLines(ViewBag.majorTickLines).RowIndex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff")
.YAxisName("secondary")
.UpperLine(ViewBag.upperline)
.Period(3)
.Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Momentum)
.Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close)
.SeriesName("Apple Inc").Add();
})
.ZoomSettings(zn => zn.EnableSelectionZooming(true)
.Mode(Syncfusion.EJ2.Charts.ZoomMode.X))
.Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enable(
true)
)
.PrimaryXAxis(px => px.ZoomFactor(0.2)
.ZoomPosition(0.6)
.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.MajorGridLines(ViewBag.majorGridLines)
.CrosshairTooltip(ViewBag.crosshairTooltip)
).PrimaryYAxis(py => py.RowIndex(1)
.OpposedPosition(true).Title("Price")
.Minimum(50).Maximum(170)
.Interval(30)
.LabelFormat("{value}M")
.PlotOffset(25)
412
.LineStyle(ViewBag.lineStyle)
).Title("AAPL 2012-2017")
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Tooltip(tl => tl.Enable(true).Shared(true))
.LegendSettings(lg => lg.Visible(false)).Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Momentum()
{
ViewBag.animation = new { enable = true };
ViewBag.upperline = new { color = "#ff0000", width = 1 };
ViewBag.lowerline = new { color = "#f2ec2f", width = 1 };
ViewBag.gridlines = new { width = 0.0001 };
ViewBag.linestyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairtooltip = new { enable = true };
return View();
}
}
}
razor
macd.cs
@using Syncfusion.EJ2;
413
<script src="chart/technical-indicators/macd/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").Title("MACD").OpposedPosition(true).Minimum(-3.5).Maxim
um(3.5).MajorTickLines(ViewBag.majorTickLines).MajorGridLines(ViewBag.majorGridLines).I
nterval(3.5).RowIndex(0).LineStyle(ViewBag.lineStyle).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").MacdType(Syncfusion.EJ2.Charts.MacdType.Both).MacdPosi
tiveColor("#2ecd71").MacdNegativeColor("#e74c3d").Fill("#6063ff").YAxisName("secondary"
).FastPeriod(8).SlowPeriod(5).Period(3).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.
Macd).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Ad
d();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime).MajorGridLines(ViewBag.majorGridLines)
).PrimaryYAxis(py => py.RowIndex(1).OpposedPosition(true).LabelFormat("${v
alue}M").Title("Price").Minimum(50).Maximum(170).Interval(30).LineStyle(ViewBag.lineSty
le).LabelFormat("{value}M").PlotOffset(25)
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
414
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MACD()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
return View();
}
}
}
Customization of MACD
razor
custom-macd.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/macd/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").Title("MACD").OpposedPosition(true).Minimum(-3.5).Maxim
um(3.5).MajorTickLines(ViewBag.majorTickLines).MajorGridLines(ViewBag.majorGridLines).I
nterval(3.5).RowIndex(0).LineStyle(ViewBag.lineStyle).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
415
}).Indicators(id =>
{
id.Fill("#6063ff").MacdType(Syncfusion.EJ2.Charts.MacdType.Both).MacdPosi
tiveColor("#2ecd71").MacdNegativeColor("#e74c3d").Fill("#6063ff").YAxisName("secondary"
).FastPeriod(8).SlowPeriod(5).Period(3).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.
Macd).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Ad
d();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime).MajorGridLines(ViewBag.majorGridLines)
).PrimaryYAxis(py => py.RowIndex(1).OpposedPosition(true).LabelFormat("${v
alue}M").Title("Price").Minimum(50).Maximum(170).Interval(30).LineStyle(ViewBag.lineSty
le).LabelFormat("{value}M").PlotOffset(25)
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult MACD()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
return View();
}
}
}
416
Relative Strength Index (RSI)
RSI shows how strongly a stock is moving in its current direction. To render a RSI Indicator, use
indicator type as Rsi .RSI indicator will be represented by three lines (upperBand, lowerBand,
signalLine). The upperBand and lowerBand values are customized by overBought and
overSold properties of indicator and the signalLine is calculated by RSI formula.
razor
rsi.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/rsi/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").OpposedPosition(true).Title("RSI").Minimum(0).Maximum(1
20).MajorTickLines(ViewBag.majorTickLines)
.MajorGridLines(ViewBag.majorGridLines).LineStyle(ViewBag.lineStyle).Interval(60).RowIn
dex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").ShowZones(true).OverBought(70).LowerLine(ViewBag.lowe
rLine).UpperLine(ViewBag.upperLine).OverSold(30).YAxisName("secondary").Period(3).Type(
Syncfusion.EJ2.Charts.TechnicalIndicators.Rsi).Field(Syncfusion.EJ2.Charts.FinancialDat
aFields.Close).SeriesName("Apple Inc").Add();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).MajorGridLines(Vie
wBag.majorGridLines).ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
).PrimaryYAxis(py => py.RowIndex(1).OpposedPosition(true).Title("Price").M
ajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle).Minimum(50).Maximum(170).Interval(30).LabelFormat("${valu
e}").PlotOffset(25)
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
417
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult RSI()
{
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.upperLine = new { color = "#e74c3d" };
ViewBag.lowerLine = new { color = "#2ecd71" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
razor
sma.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/sma/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YName("
y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillColor(
418
"#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Width(2)
.Add();
}).Indicators(id =>
{
id.Fill("#6063ff").Period(14).Type(Syncfusion.EJ2.Charts.TechnicalIndicators
.Sma).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Ad
d();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Charts
.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enab
le(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).CrosshairTooltip(V
iewBag.crosshairTooltip).MajorGridLines(ViewBag.majorGridLines).ValueType(Syncfusion.EJ
2.Charts.ValueType.DateTime)
).PrimaryYAxis(py => py.Title("Price").Minimum(50).Maximum(170).Interval(30
).LineStyle(ViewBag.lineStyle).LabelFormat("{value}M")
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult SMA()
{
ViewBag.majorGridLines = new { width = 0.1 };
ViewBag.lineStyle = new { width = 0.1 };
ViewBag.animation = new { enable = false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.crosshairTooltip = new { enable = true };
return View();
}
}
}
419
Stochastic
It shows how a stock is, when compared to previous state. To render a Stochastic indicator, use
indicator type as Stochastic . stochastic indicator will be represented by four lines (upperLine,
lowerLine, periodLine, signalLine). In stochastic indicator the upperBand value and lowerBand
value is customized by overBought and overBought properties of indicators and the periodLine
and signalLine is render based on stochastic formula.
razor
stochastic.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/stochastic/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").OpposedPosition(true).Minimum(0).Maximum(120).LineStyle
(ViewBag.lineStyle).MajorGridLines(ViewBag.majorGridLines).MajorTickLines(ViewBag.major
TickLines)
.Interval(60).RowIndex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").KPeriod(2).DPeriod(3).YAxisName("secondary").Period(3
).LowerLine(ViewBag.lowerLine).UpperLine(ViewBag.upperLine).PeriodLine(ViewBag.periodLi
ne).Animation(ViewBag.animation).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Stochas
tic).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Add
();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime).MajorGridLines(ViewBag.majorGridLines)
).ChartArea(area => area.Border(ViewBag.ChartBorder)).PrimaryYAxis(py => p
y.RowIndex(1).OpposedPosition(true).Title("Price").LineStyle(ViewBag.lineStyle).Minimum(
80).Maximum(170).Interval(30).LabelFormat("{value}M").PlotOffset(25)
).Title("AAPL 2012-2017").Tooltip(tl => tl.Enable(true).Shared(true)).Lege
420
ndSettings(lg => lg.Visible(false)).Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Stochastic()
{
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.animation = new { enable = false };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.upperLine =new { color = "#e74c3d" };
ViewBag.lowerLine = new { color = "#2ecd71" };
ViewBag.periodLine =new { color = "#f2ec2f" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
Customization of StochasticIndicator
stroke , stroke-width , and color of upperLine can be customized by using, upperLine , the
lowerLine can be customized by using lowerLine and the periodLine can be customized by
using periodLine properties of indicator. To customize the period to find the average price
using kPeriod and dPeriod properties.
razor
custom-stochastic.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/stochastic/financial-data.js"></script>
@section ControlsSection{
421
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").OpposedPosition(true).Minimum(0).Maximum(120).LineStyle
(ViewBag.lineStyle).MajorGridLines(ViewBag.majorGridLines).MajorTickLines(ViewBag.major
TickLines)
.Interval(60).RowIndex(0).Add();
}
).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YNa
me("y").High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillCo
lor("#2ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Widt
h(2).Add();
}).Indicators(id =>
{
id.Fill("#6063ff").KPeriod(2).DPeriod(3).YAxisName("secondary").Period(3
).LowerLine(ViewBag.lowerLine).UpperLine(ViewBag.upperLine).PeriodLine(ViewBag.periodLi
ne).Animation(ViewBag.animation).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.Stochas
tic).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Add
();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime).MajorGridLines(ViewBag.majorGridLines)
).ChartArea(area => area.Border(ViewBag.ChartBorder)).PrimaryYAxis(py => p
y.RowIndex(1).OpposedPosition(true).Title("Price").LineStyle(ViewBag.lineStyle).Minimum(
80).Maximum(170).Interval(30).LabelFormat("{value}M").PlotOffset(25)
).Title("AAPL 2012-2017").Tooltip(tl => tl.Enable(true).Shared(true)).Lege
ndSettings(lg => lg.Visible(false)).Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
422
{
public partial class ChartController : Controller
{
public ActionResult Stochastic()
{
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.animation = new { enable = false };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.upperLine =new { color = "#0f0000" };
ViewBag.lowerLine = new { color = "#080000" };
ViewBag.periodLine =new { color = "#f2ec2f" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
razor
tma.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/tma/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Candle).XName("x").YName("
y").Animation(ViewBag.animation)
.High("high").Low("low").Open("open").Close("close").Volume("volume").BearFillColor("#2
ecd71").BullFillColor("#e74c3d").DataSource("dataSource").Name("Apple Inc").Width(2).Ad
d();
}).Indicators(id =>
{
id.Fill("#6063ff").Period(3).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.
Tma).Field(Syncfusion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Add
();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Charts
.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).Enab
le(true)
423
).PrimaryXAxis(px => px.ZoomFactor(0.2).ZoomPosition(0.6).CrosshairTooltip(V
iewBag.crosshairTooltip).MajorGridLines(ViewBag.majorGridLines)
.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
).PrimaryYAxis(py => py.Title("Price").Minimum(50).Maximum(170).Interval(30
)
.LineStyle(ViewBag.lineStyle).LabelFormat("{value}M")
).Title("AAPL 2012-2017").ChartArea(area => area.Border(ViewBag.ChartBorde
r)).Tooltip(tl => tl.Enable(true).Shared(true)).LegendSettings(lg => lg.Visible(false))
.Load("load").Render()
}
<script>
var dataSource = window.chartData;
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult TMA()
{
ViewBag.crosshairTooltip= new { enable= true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.animation = new { enable = false };
return View();
}
}
}
stroke , stroke-width , and color of signalLine can be customized by using, fill , width
and dashArray properties and the period property is used to predict the data forecast
calculations. The field value is used to the compare the current price with previous price. It is
applicable to Bollinger bands and moving averages. The showZones property is used to
shows/Hides the overBought and overSold regions. It is applicable for RSI and stochastic
indicators.
424
razor
custom-tma.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
425
Data Source
Usually technical indicators are added along with a financial series. The seriesName represents
the series, the data of which has to be analysed through indicators.
Technical indicators can also be added without series using dataSource property of indicator.
razor
datasource.cs
@using Syncfusion.EJ2;
<script src="chart/technical-indicators/ad/financial-data.js"></script>
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Rows(rows =>
{
rows.Height("40%").Add();
rows.Height("60%").Add();
}).Axes(ax =>
{
ax.Name("secondary").
OpposedPosition(true).
Minimum(-7000000000).
Maximum(5000000000).
Interval(6000000000).
Title("Accumulation Distribution").MajorTickLines(ViewBag.majorTickLines).LineSt
yle(ViewBag.lineStyle).
RowIndex(0).Add();
}
).Indicators(id =>
{
id.Fill("#6063ff").KPeriod(2).DPeriod(3).YAxisName("secondary").Period(3
).Type(Syncfusion.EJ2.Charts.TechnicalIndicators.AccumulationDistribution).Field(Syncfu
sion.EJ2.Charts.FinancialDataFields.Close).SeriesName("Apple Inc").Add();
}).ZoomSettings(zn => zn.EnableSelectionZooming(true).Mode(Syncfusion.EJ2.Ch
arts.ZoomMode.X)).Crosshair(cr => cr.LineType(Syncfusion.EJ2.Charts.LineType.Vertical).
Enable(true)
).PrimaryXAxis(px => {
px.ZoomFactor(0.2).MajorGridLines(dataT).ZoomPosition(0.6).MajorGridLine
s(ViewBag.majorGridLines).CrosshairTooltip(ViewBag.crosshairTooltip).ValueType(Syncfusi
on.EJ2.Charts.ValueType.DateTime);
}).PrimaryYAxis(py => py.RowIndex(1).OpposedPosition(true).LineStyle(ViewBag
.lineStyle).Title("Price").Minimum(80).Maximum(170).Interval(30).LabelFormat("${value}"
).PlotOffset(25)
}
<script>
var dataSource = window.chartData;
</script>
426
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult AccumulationDistribution()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.crosshairTooltip = new { enable = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
427
Trendlines
Trendlines are used to show the direction and speed of price.
Trendlines can be generated for Cartesian type series (Line, Column, Scatter, Area, Candle, Hilo
etc.) except bar type series. You can add more than one trendline to a series.
Linear
A linear trendline is a best fit straight line that is used with simpler data sets. To render a linear
trendline, use trendline type as Linear .
razor
linear.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
428
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Linear;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Exponential
429
An exponential trendline is a curved line that is most useful when data values rise or fall at
increasingly higher rates. You cannot create an exponential trendline, if your data contains zero
or negative values.
razor
exponential.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
.Width(2).Add();
}).PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabe
lPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
430
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Exponential;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Logarithmic
A logarithmic trendline is a best-fit curved line that is most useful when the rate of change in the
data increases or decreases quickly and then levels out.
razor
logarithmic.cs
431
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
432
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Logarithmic;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Polynomial
A polynomial trendline is a curved line that is used when data fluctuates.
razor
polynomial.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
433
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
434
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Polynomial;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Power
A power trendline is a curved line that is best used with data sets that compare measurements
that increase at a specific rate.
razor
power.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("powerData")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
435
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Power;
436
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Moving Average
A moving average trendline smoothen out fluctuations in data to show a pattern or trend more
clearly.
razor
movingaverage.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("powerData")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
437
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.MovingAverage;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Customization of Trendlines
438
The fill and width properties are used to customize the appearance of the trendline.
razor
custom-trendline.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("powerData")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
439
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.MovingAverage;
line.Width = 3;
line.Name = "MovingAverage";
line.Fill = "#C64A75";
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Forecasting
Trendlines forecasting is the prediction of future/past situations.
Forward Forecasting
The value set for forwardForecast is used to determine the distance moving towards the future
trend.
440
razor
forward-forecast.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
.Width(2).Add(); })
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
441
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Linear;
line.ForwardForecast = 5;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
Backward Forecasting
The value set for the backwardForecast is used to determine the past trends.
razor
backward-forecast.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Trendlines(ViewBag.trendLines)
.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line)
.XName("x").YName("y")
.Marker(ViewBag.marker)
.DataSource("series1")
.Name("Rupees")
.Width(2).Add(); })
442
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLab
elPlacement.Shift)
.MajorGridLines(ViewBag.majorGridLines))
.PrimaryYAxis(py => py.Title("Rupees against Dollars")
.Interval(10)
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Title("Historical Indian Rupee Rate (INR USD)")
.LegendSettings(lg => lg.Visible(false))
.Tooltip(tt => tt.Enable(true)).Render()
}
<script type="text/javascript">
var series1 = [];
var yValue = [7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11
, 11.36, 12.34, 12.60, 12.95,
13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36,
41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41
, 48.32, 45.65, 46.61, 53.34, 58.53];
var point1;
var i;
var j = 0;
for (i = 1973; i <= 2013; i++) {
point1 = { x: i, y: yValue[j] };
series1.push(point1);
j++;
}
var powerData = [
{ x: 1, y: 10 }, { x: 2, y: 50 }, { x: 3, y: 80 }, { x: 4, y: 110 },
{ x: 5, y: 180 }, { x: 6, y: 220 }, { x: 7, y: 300 }, { x: 8, y: 370 }, { x
: 9, y: 490 }, { x: 10, y: 500 }
];
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Trendlines
public ActionResult Trendlines()
443
{
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.lineStyle = new { width = 0.000001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.marker = new { visible = true };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
List<ChartTrendline> lines = new List<ChartTrendline>();
ChartTrendline line = new ChartTrendline();
line.Type = TrendlineTypes.Linear;
line.BackwardForecast= 5;
lines.Add(line);
ViewBag.trendLines = lines;
return View();
}
}
}
444
Data Markers
Data markers are used to provide information about the data points in the series. You can add a
shape to adorn each data point.
Marker
Markers can be added to the points by enabling the visible option of the marker property.
razor
marker.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
445
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.marker = new {
visible = true
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Shape
Markers can be assigned with different shapes such as Rectangle, Circle, Diamond etc using the
shape property.
razor
shape.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
446
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new {
visible = true;
shape = "Diamond";
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Note : To know more about the marker shape type refer the shape .
Images
Apart from the shapes, you can also add custom images to mark the data point using the
imageUrl property.
razor
images.cs
@ControlSecction {
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
447
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new {
visible = true;
imageUri = "./images/sun_annotation.png";
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Customization
Marker's color and border can be customized using fill and border properties.
razor
custom.cs
448
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Spline).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new {
visible = true;
height = 20;
width = 20;
}
return View();
}
public class ChartData
{
public string x;
public double yValue;
449
}
}
}
razor
custom-point.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").PointRender("point").Render()
<script>
function point(args) {
if(args.point.index === 1) {
args.shape = "Circle"
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
450
{
public IActionResult Column()
{
List<ChartData> chartData = new List<ChartData>
{
new ChartData { x= "USA", yValue= 46 },
new ChartData { x= "GBR", yValue= 27 },
new ChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.marker = new {
visible = true
}
return View();
}
public class ChartData
{
public string x;
public double yValue;
}
}
}
451
Data Labels
Data label can be added to a chart series by enabling the visible option in the dataLabel. By
default, the labels will arrange smartly without overlapping.
razor
datalabel.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
452
{
dataLabel = new
{
visible = true,
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Position
Using position property, you can place the label either on Top , Middle , Bottom or Outer
(outer is applicable for column and bar type series).
razor
position.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
453
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Note: The position Outer is applicable for column and bar type series.
Datalabel template
Label content can be formatted by using the template option. Inside the template, you can add
the placeholder text ${point.x} and ${point.y} to display corresponding data points x & y
value. Using template property, you can set data label template in chart.
razor
template.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
454
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
455
}
}
}
Text Mapping
Text from the data source can be mapped using name property.
razor
mapping.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46, name = "USA: 46" },
new ColumnChartData { x= "GBR", yValue= 27, name = "GBR: 27" },
new ColumnChartData { x= "CHN", yValue= 26, name = "CHN: 26 " }
};
456
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
name = "name",
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
public string name;
}
}
}
Margin
margin for data label can be applied to using left , right , bottom and top properties.
razor
margin.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
457
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
font = new { fontWeight = "600" },
margin = new { left = 13, right = 10, top= 0, bottom = 15}
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Customization
stroke and border of data label can be customized using fill and border properties.
Rounded corners can be customized using rx and ry properties.
razor
custom.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
458
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
rx = 10, ry = 20,
border = new { color = "yellow", width = 2},
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
459
{
public string x;
public double yValue;
}
}
}
razor
custom-point.cs
@ControlSection {
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").TextRender("text").Render()
<script>
function text(args) {
if(args.index = 2) {
args.cancel = true;
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
460
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.Marker = new
{
dataLabel = new
{
visible = true,
font = new { fontWeight = "600" }
}
};
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
461
Annotation
Annotations are used to mark the specific area of interest in the chart area with texts, shapes or
images.
You can add annotations to the chart by using the annotations option. By using the content
option of annotation object, you can specify the id of the element that needs to be displayed in
the chart area.
razor
annotation.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
Annotations(an => {
an.X("USA").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content).Add();
an.X("GBR").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content1).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
462
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.content = "<div>Gold</div>";
ViewBag.content1 ="<div>Silver</div>";
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Region
Annotations can be placed either with respect to Series or Chart . by default, it will placed with
respect to Chart .
razor
region.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
Annotations(an => {
an.X("USA").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content).Add();
an.X("GBR").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content1).Add();
463
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.content = "<div>Gold</div>";
ViewBag.content1 ="<div>Silver</div>";
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Co-ordinate Units
Specified the coordinates units of the annotation either Pixel or Point .
razor
co-ordinate.cs
@using Syncfusion.EJ2;
464
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
Annotations(an => {
an.X("USA").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content).Add();
an.X("GBR").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content1).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.content = "<div>Gold</div>";
ViewBag.content1 ="<div>Silver</div>";
return View();
}
public class ColumnChartData
465
{
public string x;
public double yValue;
}
}
}
Alignment
Annotation provides verticalAlignment and horizontalAlignment . The verticalAlignment
can be customized via Top , Bottom or Middle and the horizontalAlignment can be
customized via Near , Far or Center .
razor
alignment.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
Annotations(an => {
an.X("USA").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content).Add();
an.X("GBR").Y("50").CoordinateUnits(Syncfusion.EJ2.Charts.Units.Point).Verti
calAlignment(Syncfusion.EJ2.Charts.Position.Top).Content(ViewBag.content1).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
466
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.content = "<div>Gold</div>";
ViewBag.content1 ="<div>Silver</div>";
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
467
Legend
Legend provides information about the series rendered in the chart.
razor
default.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
468
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Custom position helps you to position the legend anywhere in the chart using x, y coordinates.
razor
position.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
469
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).LegendSettings(legend => legend.Position(Syncfusion.EJ2.Charts.LegendPosition.
Top)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
470
}
}
}
Legend Alignment
You can align the legend as center , far or near to the chart using alignment property.
razor
alignment.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
.LegendSettings(legend => legend.Alignment(Syncfusion.EJ2.Charts.Alignment.Far)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
471
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Customization
To change the legend icon shape, you can use legendShape property in the series . By default
legend icon shape is seriesType .
razor
custom.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
472
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).LegendSettings(legend => legend.shape(Syncfusion.EJ2.Charts.LegendShape.Square
)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
473
public double yValue1;
}
}
}
Legend Size
By default, legend takes 20% - 25% of the chart's height horizontally, when it is placed on top or
bottom position and 20% - 25% of the chart's width vertically, when placed on left or right position
of the chart. You can change this default legend size by using the width and height property
of the legendSettings .
razor
size.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).LegendSettings(legend => legend.Size("45%)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
474
{
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
You can customize the size of the legend items by using the shapeHeight and shapeWidth
property.
razor
item-size.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
475
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).LegendSettings(legend => legend.ShapeWidth("10")
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
476
public DateTime xValue;
public double yValue;
public double yValue1;
}
}
}
Paging will be enabled by default, when the legend items exceeds the legend bounds. You can
view each legend items by navigating between the pages using navigation buttons.
razor
paging.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
). .LegendSettings(legend => legend.Width(50)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
477
{
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
razor
selection.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("Germany").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("England").Add();
478
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("Russia").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).LegendSettings(legend => legend.ToggleVisibility("true")
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
479
{
public DateTime xValue;
public double yValue;
public double yValue1;
}
}
}
razor
collapse.cs
@using Syncfusion.EJ2;
@ControlSection{
@Html.EJS().Charts("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue").DataSource(ViewBag.dataSource).Name("").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").DataSource(ViewBag.dataSource).Name("").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).Width(2).XName("xV
alue").YName("yValue1").DataSource(ViewBag.dataSource).Name("").Add();
}).PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).Lab
elFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.Additional).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Load("load").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
480
public IActionResult Line()
{
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
481
Tooltip
Chart will display details about the points through tooltip, when the mouse is moved over the
point.
Default Tooltip
By default, tooltip is not visible. Enable the tooltip by setting enable property to true.
razor
default.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Tooltip(tt => tt.Enable(true)).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
482
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
format.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").
Tooltip(tt => tt.Enable(true).
Header("medal count").
Format("${series.name} ${point.x} : ${point.y}")).Render()
}
using System;
using System.Collections.Generic;
483
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Tooltip Template
Any HTML elements can be displayed in the tooltip by using the ‘template’ property of the tooltip.
You can use the ${x} and ${y} as place holders in the HTML element to display the x and y
values of the corresponding data point.
razor
template.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
484
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").
Tooltip(tt => tt.Enable(true).
header("medal count").
template=("#Medal")).Render()
}
<script id="Medal" type="text/x-template">
<div id='templateWrap'>
<table style="width:100%; border: 1px solid black;">
<tr><th colspan="2" bgcolor="#00FFFF">Medal</th></tr>
<tr><td bgcolor="#00FFFF">${x}:</td><td bgcolor="#00FFFF">${y}</td></tr>
</table>
</div>
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
485
Customize the Appearance of Tooltip
The fill and border properties are used to customize the background color and border of
the tooltip respectively. The textStyle property in the tooltip is used to customize the font of the
tooltip text.
razor
custom-tooltip.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Tooltip(tt => tt.Enable(true).
Format("<b>${point.x} : ${point.y}</b>").
Fill('#7bb4eb').Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
486
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
487
Zooming and Panning
Enable Zooming
Chart can be zoomed in three ways.
razor
default.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
PrimaryXAxis(px => px.Title("Years").
MajorGridLines(ViewBag.majorGridLines).
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
Skeleton("yMMM")).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Border(ViewBag.border).Animation(ViewBag.animation).
DataSource("series1").
Name("Product X").
XName("x").
YName("y").Add();
}
).ChartArea(area => area.Border(ViewBag.chartBorder)).
LegendSettings(legend => legend.Visible(false)).
PrimaryYAxis(py => py.Title("Profit ($)").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)).
ZoomSettings(z => z.EnableMouseWheelZooming(true).
EnablePinchZooming(true).EnableSelectionZooming(true).
Mode(Syncfusion.EJ2.Charts.ZoomMode.X)).
488
Title("Sales History of Product X").Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > 0.5) {
value += Math.random();
}
else {
value -= Math.random();
}
point1 = { x: new Date(1950, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Zooming()
{
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.border = new ChartBorder { Width = 0.5, Color = "#00bdae" };
ViewBag.animation=new { enable= false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
After zooming the chart, a zooming toolbar will appear with zoom , zoomin , zoomout , pan and
reset buttons. Selecting the Pan option will allow to pan the chart and selecting the Reset
option will reset the zoomed chart.
489
Modes
The mode property in zoomSettings specifies whether the chart is allowed to scale along the
horizontal axis or vertical axis. The default value of the mode is XY (both axis).
razor
mode.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
PrimaryXAxis(px => px.Title("Years").
MajorGridLines(ViewBag.majorGridLines).
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
Skeleton("yMMM")).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Border(ViewBag.border).Animation(ViewBag.animation).
DataSource("series1").
Name("Product X").
XName("x").
YName("y").Add();
}
).ChartArea(area => area.Border(ViewBag.chartBorder)).
LegendSettings(legend => legend.Visible(false)).
PrimaryYAxis(py => py.Title("Profit ($)").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)).
ZoomSettings(z => z.EnableMouseWheelZooming(true).
EnablePinchZooming(true).EnableSelectionZooming(true).
Mode(Syncfusion.EJ2.Charts.ZoomMode.X)).
Title("Sales History of Product X").Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > 0.5) {
value += Math.random();
490
}
else {
value -= Math.random();
}
point1 = { x: new Date(1950, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Zooming()
{
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.border = new ChartBorder { Width = 0.5, Color = "#00bdae" };
ViewBag.animation=new { enable= false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
Toolbar
By default, zoomin, zoomout, pan and reset buttons will be displayed for zoomed chart. You can
customize to show your desire tools in the toolbar using toolbarItems property.
razor
toolbar.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
PrimaryXAxis(px => px.Title("Years").
MajorGridLines(ViewBag.majorGridLines).
491
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
Skeleton("yMMM")).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Border(ViewBag.border).Animation(ViewBag.animation).
DataSource("series1").
Name("Product X").
XName("x").
YName("y").Add();
}
).ChartArea(area => area.Border(ViewBag.chartBorder)).
LegendSettings(legend => legend.Visible(false)).
PrimaryYAxis(py => py.Title("Profit ($)").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)).
ZoomSettings(z => z.EnableMouseWheelZooming(true).
ToolbarItems(ViewBag.toolbarItems).
Mode(Syncfusion.EJ2.Charts.ZoomMode.X)).
Title("Sales History of Product X").Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > 0.5) {
value += Math.random();
}
else {
value -= Math.random();
}
point1 = { x: new Date(1950, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
492
public partial class ChartController : Controller
{
public ActionResult Zooming()
{
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.border = new ChartBorder { Width = 0.5, Color = "#00bdae" };
ViewBag.animation=new { enable= false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.toolbarItems =new { "Zoom", "Pan", "Reset"};
return View();
}
}
}
Enable pan
Using enablePan property you can able to pan the zoomed chart without help of toolbar items.
razor
pan.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
PrimaryXAxis(px => px.Title("Years").
MajorGridLines(ViewBag.majorGridLines).
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
Skeleton("yMMM").ZoomFactor(0.2). ZoomPosition(0.6)).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Border(ViewBag.border).Animation(ViewBag.animation).
DataSource("series1").
Name("Product X").
XName("x").
YName("y").Add();
}
).ChartArea(area => area.Border(ViewBag.chartBorder)).
LegendSettings(legend => legend.Visible(false)).
PrimaryYAxis(py => py.Title("Profit ($)").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)).
ZoomSettings(z => z.EnableMouseWheelZooming(true).
EnablePinchZooming(true).EnableSelectionZooming(true).
Mode(Syncfusion.EJ2.Charts.ZoomMode.X).EnablePan(true)).
493
Title("Sales History of Product X").Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > 0.5) {
value += Math.random();
}
else {
value -= Math.random();
}
point1 = { x: new Date(1950, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Zooming()
{
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.border = new ChartBorder { Width = 0.5, Color = "#00bdae" };
ViewBag.animation=new { enable= false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
494
By using enableAutoIntervalOnZooming property, the axis interval will get calculated
automatically with respect to the zoomed range.
razor
auto-interval.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
PrimaryXAxis(px => px.Title("Years").
MajorGridLines(ViewBag.majorGridLines).
ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime).
Skeleton("yMMM")).Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Area).
Border(ViewBag.border).Animation(ViewBag.animation).
DataSource("series1").
Name("Product X").
XName("x").
YName("y").Add();
}
).ChartArea(area => area.Border(ViewBag.chartBorder)).
LegendSettings(legend => legend.Visible(false)).
enableAutoIntervalOnZooming(true).
PrimaryYAxis(py => py.Title("Profit ($)").
LineStyle(ViewBag.lineStyle).
MajorTickLines(ViewBag.majorTickLines).
RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)).
ZoomSettings(z =>z.EnableSelectionZooming(true).
Mode(Syncfusion.EJ2.Charts.ZoomMode.X)).
Title("Sales History of Product X").Render()
}
<script>
var series1 = [];
var point1;
var value = 80;
var i;
for (i = 1; i < 500; i++) {
if (Math.random() > 0.5) {
value += Math.random();
}
else {
value -= Math.random();
}
point1 = { x: new Date(1950, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
</script>
495
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Zooming()
{
ViewBag.majorGridLines= new { width= 0.00001 };
ViewBag.lineStyle = new { width = 0.00001 };
ViewBag.majorTickLines = new { width = 0.00001 };
ViewBag.border = new ChartBorder { Width = 0.5, Color = "#00bdae" };
ViewBag.animation=new { enable= false };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
}
}
496
Crosshair
Crosshair has a vertical and horizontal line to view the value of the axis at mouse or touch
position.
razor
crosshair.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
ChartArea(area => area.Border(ViewBag.ChartBorder))
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xValue"
).Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("Germany")
.Add();
})
.PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift).LabelFormat("
y"))
.PrimaryYAxis(py => py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.Interval(20).Minimum(0).Maximum(100))
.Title("Inflation - Consumer Price")
.Tooltip(tt => tt.Enable(true))
.Crosshair(cr=>cr.Enable(true)).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
497
public ActionResult Line()
{
List<LineChartData> chartData = new List<LineChartData>
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70 },
};
ViewBag.dataSource = chartData;
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.marker = new
{
visible = true,
width = 10,
height = 10
};
return View();
}
razor
axis-tooltip.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
ChartArea(area => area.Border(ViewBag.ChartBorder))
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xValue"
).Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("Germany")
498
.Add();
})
.PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift).LabelFormat("
y")
.CrosshairTooltip(ViewBag.cross))
.PrimaryYAxis(py => py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.Interval(20).Minimum(0).Maximum(100)
.CrosshairTooltip(ViewBag.cross))
.Title("Inflation - Consumer Price")
.Tooltip(tt => tt.Enable(true))
.Crosshair(cr=>cr.Enable(true)).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Line()
{
List<LineChartData> chartData = new List<LineChartData>
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70 },
};
ViewBag.dataSource = chartData;
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.marker = new
{
visible = true,
width = 10,
499
height = 10
};
ViewBag.Cross = new
{
enable = true
};
return View();
}
Customization
The fill and textStyle property of the crosshairTooltip is used to customize the
background color and font style of the crosshair label respectively. Color and width of the
crosshair line can be customized by using the line property in the crosshair.
razor
custom.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").
ChartArea(area => area.Border(ViewBag.ChartBorder))
.Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xValue"
).Marker(ViewBag.marker).YName("yValue").DataSource(ViewBag.dataSource).Name("Germany")
.Add();
})
.PrimaryXAxis(px => px.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.IntervalType(Syncfusion.EJ2.Charts.IntervalType.Years)
.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shift).LabelFormat("
y")
.CrosshairTooltip(ViewBag.cross))
.PrimaryYAxis(py => py.LabelFormat("{value}%")
.RangePadding(Syncfusion.EJ2.Charts.ChartRangePadding.None)
.Interval(20).Minimum(0).Maximum(100)
.CrosshairTooltip(ViewBag.cross))
.Title("Inflation - Consumer Price")
500
.Tooltip(tt => tt.Enable(true))
.Crosshair(ViewBag.CrossLine).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public ActionResult Line()
{
List<LineChartData> chartData = new List<LineChartData>
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70 },
};
ViewBag.dataSource = chartData;
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
ViewBag.marker = new
{
visible = true,
width = 10,
height = 10
};
ViewBag.Cross = new
{
enable = true,
fill= "green"
};
ViewBag.CrossLine = new
{
enable = true,
Line = new {
width= 2,
color= "green"
501
}
};
return View();
}
Trackball
Trackball is used to track a data point closest to the mouse or touch position. Trackball marker
indicates the closest point and trackball tooltip displays the information about the point.
Trackball can be enabled by setting the enable property of the crosshair to true and shared
property in tooltip to true in chart.
razor
trackball.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container-vertical").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).XName("x").YName("yV
alue").Marker(ViewBag.marker)
.DataSource(ViewBag.dataSource ).Name("John").Width(2).Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).XName("x").YName("yV
alue1").Marker(ViewBag.marker)
.DataSource(ViewBag.dataSource ).Name("Andrew").Width(2).Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).XName("x").YName("yV
alue2").Marker(ViewBag.marker)
.DataSource(ViewBag.dataSource).Name("Thomas").Width(2).Add();})\
.PrimaryXAxis(px => px.EdgeLabelPlacement(Syncfusion.EJ2.Charts.EdgeLabelPlacement.Shif
t)
.MajorGridLines(ViewBag.majorGridLines).LineStyle(ViewBag.lineStyle)
.ValueType(Syncfusion.EJ2.Charts.ValueType.DateTime)
.Skeleton("y"))
.PrimaryYAxis(py => py.Title("Revenue")
.MajorTickLines(ViewBag.majorTickLines)
.LineStyle(ViewBag.lineStyle)
.Minimum(10)
.Maximum(80)
502
.LabelFormat("{value}M"))
.ChartArea(area => area.Border(ViewBag.ChartBorder))
.Tooltip(tl =>tl.Enable(true).Shared(true))
.Crosshair(cr => cr.Enable(true).LineType(Syncfusion.EJ2.Charts.LineType.Vertical))
.Title("Average Sales per Person").Render()
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
503
, yValue1 = 60, yValue2 = 65 },
new TrackballChartData { xValue = new DateTime(2006, 2, 11), yValue = 24
, yValue1 = 60, yValue2 = 79 },
};
ViewBag.dataSource = chartData;
return View();
}
504
Selection
Chart provides selection support for the series and its data points on mouse click.
When Mouse is clicked on the data points, the corresponding series legend will also be
selected.
We have different type of selection mode for selecting the data. They are,
None
Point
Series
Cluster
DragXY
DragX
DragY
Point
You can select a point, by setting selectionMode to point.
razor
point-selection.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").Add();
505
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
Series
You can select a series, by setting selectionMode to series.
506
razor
series-selection.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
507
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
Cluster
You can select the points that corresponds to the same index in all the series, by setting
selectionMode to cluster.
razor
cluster-selection.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").Add();
508
SelectionMode(Syncfusion.EJ2.Charts.SelectionMode.Cluster).Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
Rectangular selection
509
DragXY, DragX and DragY
To fetch the collection of data under a particular region, you have to set selectionMode as
DragXY .
DragXY - Allows us to select data with respect to horizontal and vertical axis.
DragX - Allows us to select data with respect to horizontal axis.
DragY - Allows us to select data with respect to vertical axis.
The selected data’s are returned as an array collection in the dragComplete event.
razor
drag.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter).XName("xValue").Y
Name("yValue").DataSource(ViewBag.dataSource).Marker(ViewBag.marker).Name("Product A").
Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Scatter).XName("xValue").Y
Name("yValue1").DataSource(ViewBag.dataSource).Marker(ViewBag.marker1).Name("Product B"
).Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: RangeSelection
public ActionResult RangeSelection()
{
510
List<RangeSelectionChartData> chartData = new List<RangeSelectionChartData>
{
new RangeSelectionChartData { xValue = 1971, yValue = 50, yValue1 = 23
},
new RangeSelectionChartData { xValue = 1972, yValue = 20, yValue1 = 67
},
new RangeSelectionChartData { xValue = 1973, yValue = 63, yValue1 = 83
},
new RangeSelectionChartData { xValue = 1974, yValue = 81, yValue1 = 43
},
new RangeSelectionChartData { xValue = 1975, yValue = 64, yValue1 = 8
},
new RangeSelectionChartData { xValue = 1976, yValue = 36, yValue1 = 41
},
new RangeSelectionChartData { xValue = 1977, yValue = 22, yValue1 = 56
},
new RangeSelectionChartData { xValue = 1978, yValue = 78, yValue1 = 31
},
new RangeSelectionChartData { xValue = 1979, yValue = 60, yValue1 = 29
},
new RangeSelectionChartData { xValue = 1980, yValue = 41, yValue1 = 87
},
new RangeSelectionChartData { xValue = 1981, yValue = 62, yValue1 = 43
},
new RangeSelectionChartData { xValue = 1982, yValue = 56, yValue1 = 12
},
new RangeSelectionChartData { xValue = 1983, yValue = 96, yValue1 = 38
},
new RangeSelectionChartData { xValue = 1984, yValue = 48, yValue1 = 67
},
new RangeSelectionChartData { xValue = 1985, yValue = 23, yValue1 = 49
},
new RangeSelectionChartData { xValue = 1986, yValue = 54, yValue1 = 67
},
new RangeSelectionChartData { xValue = 1987, yValue = 73, yValue1 = 83
},
new RangeSelectionChartData { xValue = 1988, yValue = 56, yValue1 = 16
},
new RangeSelectionChartData { xValue = 1989, yValue = 67, yValue1 = 89
},
new RangeSelectionChartData { xValue = 1990, yValue = 79, yValue1 = 18
},
new RangeSelectionChartData { xValue = 1991, yValue = 18, yValue1 = 46
},
new RangeSelectionChartData { xValue = 1992, yValue = 78, yValue1 = 39
},
new RangeSelectionChartData { xValue = 1993, yValue = 92, yValue1 = 68
},
new RangeSelectionChartData { xValue = 1994, yValue = 43, yValue1 = 87
511
},
new RangeSelectionChartData { xValue = 1995, yValue = 29, yValue1 = 45
},
new RangeSelectionChartData { xValue = 1996, yValue = 14, yValue1 = 42
},
new RangeSelectionChartData { xValue = 1997, yValue = 85, yValue1 = 28
},
new RangeSelectionChartData { xValue = 1998, yValue = 24, yValue1 = 82
},
new RangeSelectionChartData { xValue = 1999, yValue = 61, yValue1 = 13
},
new RangeSelectionChartData { xValue = 2000, yValue = 80, yValue1 = 83
},
new RangeSelectionChartData { xValue = 2001, yValue = 14, yValue1 = 26
},
new RangeSelectionChartData { xValue = 2002, yValue = 34, yValue1 = 57
},
new RangeSelectionChartData { xValue = 2003, yValue = 81, yValue1 = 48
},
new RangeSelectionChartData { xValue = 2004, yValue = 70, yValue1 = 84
},
new RangeSelectionChartData { xValue = 2005, yValue = 21, yValue1 = 64
},
new RangeSelectionChartData { xValue = 2006, yValue = 70, yValue1 = 24
},
new RangeSelectionChartData { xValue = 2007, yValue = 32, yValue1 = 82
},
new RangeSelectionChartData { xValue = 2008, yValue = 43, yValue1 = 37
},
new RangeSelectionChartData { xValue = 2009, yValue = 21, yValue1 = 68
},
new RangeSelectionChartData { xValue = 2010, yValue = 63, yValue1 = 37
},
new RangeSelectionChartData { xValue = 2011, yValue = 9 , yValue1 = 35}
,
new RangeSelectionChartData { xValue = 2012, yValue = 51, yValue1 = 81
},
new RangeSelectionChartData { xValue = 2013, yValue = 25, yValue1 = 38
},
new RangeSelectionChartData { xValue = 2014, yValue = 96, yValue1 = 51
},
new RangeSelectionChartData { xValue = 2015, yValue = 32, yValue1 = 58
}
};
ViewBag.dataSource = chartData;
ViewBag.majorGridLines = new { width = 0.00001 };
ViewBag.marker1= new {
shape= "Pentagon",
width= 10, height= 10
512
};
ViewBag.marker = new
{
shape = "Triangle",
width = 10,
height = 10
};
ViewBag.data = new string[] { "DragXY", "DragyX", "DragY", "None" };
ViewBag.chartBorder = new ChartBorder { Color = "transparent" };
return View();
}
public class RangeSelectionChartData
{
public double xValue;
public double yValue;
public double yValue1;
}
}
}
Selection type
You can select multiple points or series, by enabling the isMultiSelect property.
razor
selection-type.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").Add();
513
IsMultiSelect("true"),.Render()
)
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
Selection on load
514
You can able to select a point or series programmatically on a chart using selectedDataIndexes
property.
razor
onload.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").SelectionStyle("chartSele
ction1")Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").SelectionStyle("chartSe
lection2")Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").SelectionStyle("ch
artSelection3")Add();
.chartSelection2 {
fill: green
.chartSelection3 {
fill: blue
}
using System;
using System.Collections.Generic;
515
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
razor
selection-legend.cs
@using Syncfusion.EJ2;
516
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
517
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
razor
custom-selection.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@(Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue").DataSource(ViewBag.dataSource).Name("Age 0-14").SelectionStyle("chartSele
ction1")Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue1").DataSource(ViewBag.dataSource).Name("Age 15-64").SelectionStyle("chartSe
lection2")Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).XName("xValue").YN
ame("yValue2").DataSource(ViewBag.dataSource).Name("Age 65 & Above").SelectionStyle("ch
artSelection3")Add();
518
SelectionMode(Syncfusion.EJ2.Charts.SelectionMode.Series).Render()
)
}
.chartSelection1 {
fill: red
}
.chartSelection2 {
fill: green
.chartSelection3 {
fill: blue
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2MVCSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
// GET: Selection
public ActionResult Selection()
{
List<SelectionChartData> chartData = new List<SelectionChartData>
{
new SelectionChartData { xValue = "CHN", yValue = 17, yValue1 = 54, yVa
lue2 = 9 },
new SelectionChartData { xValue = "USA", yValue = 19, yValue1 = 67, yVa
lue2 = 14 },
new SelectionChartData { xValue = "IDN", yValue = 29, yValue1 = 65, yVa
lue2 = 6 },
new SelectionChartData { xValue = "JAP", yValue = 13, yValue1 = 61, yVa
lue2 = 26 },
new SelectionChartData { xValue = "BRZ", yValue = 24, yValue1 = 68, yVa
lue2 = 8 }
};
ViewBag.dataSource = chartData;
ViewBag.data = new string[] { "Point", "Series", "Cluster", "None" };
return View();
519
}
public class SelectionChartData
{
public string xValue;
public double yValue;
public double yValue1;
public double yValue2;
}
}
}
520
Print and Export
Print
The rendered chart can be printed directly from the browser by calling the public method print.
You can pass array of ID of elements or element to this method. By default it take element of the
chart.
razor
print.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
521
public IActionResult Line()
{
List chartData = new List
{
new LineChartData { xValue = new DateTime(2005, 01, 01), yValue = 21, y
Value1 = 28 },
new LineChartData { xValue = new DateTime(2006, 01, 01), yValue = 24, y
Value1 = 44 },
new LineChartData { xValue = new DateTime(2007, 01, 01), yValue = 36, y
Value1 = 48 },
new LineChartData { xValue = new DateTime(2008, 01, 01), yValue = 38, y
Value1 = 50 },
new LineChartData { xValue = new DateTime(2009, 01, 01), yValue = 54, y
Value1 = 66 },
new LineChartData { xValue = new DateTime(2010, 01, 01), yValue = 57, y
Value1 = 78 },
new LineChartData { xValue = new DateTime(2011, 01, 01), yValue = 70, y
Value1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
Export
The rendered chart can be exported to JPEG , PNG , SVG or PDF format by using export
method in chart. Input parameters for this method are Export Type for format and fileName of
result.
razor
export.cs
522
y").Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Line).Width(2).XName("xVal
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
523
};
ViewBag.dataSource = chartData;
return View();
}
524
Appearance
razor
custom.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).Add();
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).Add();
}).
Palettes(ViewBag.palletes).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
525
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 },
new ColumnChartData { x= "AUS", yValue= 26 },
new ColumnChartData { x= "GER", yValue= 26 }
new ColumnChartData { x= "UK", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.palletes = ["#E94649", "#F6B53F", "#6FAAB0", "#C4C24A"];
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
razor
point.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
526
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").PointRender("point").Render()
}
<script>
function point(args) {
args.fill = colors[args.point.index];
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Using background and border properties, you can change the background color and border of
the chart.
527
razor
area.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.chartBorder = new { color = 'red', width = 2}
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
528
}
Chart Margin
You can set margin for chart from its container through margin property.
razor
margin.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Width(2).Add();
}).
Margin(ViewBag.margin)
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
ViewBag.margin = new { right = 10, left = 20, top = 30, bottom = 40}
return View();
529
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
The chart area background can be customized by using the [ background ] property in the
chartArea .
razor
background.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
530
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Animation
You can customize animation for a particular series using animation property. You can enable
or disable animation of the series using enable property, duration specifies the duration of an
animation and delay allows us to start the animation at desire time.
razor
animation.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
Title("Olympic Medal Counts - RIO").Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
531
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
Chart Title
Chart can be given a title using title property, to show the information about the data plotted.
razor
title.cs
@using Syncfusion.EJ2;
@section ControlsSection{
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
532
)).
Title("Olympic Medal Counts - RIO").TitleStyle(ViewBag.style).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.style = new { fontFamily = "Arial", fontStyle = "italic", fontWeigh
t = "regular",
color = "#E27F2D", size = "23px" };
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
533
Accessibility
Chart provides built-in compliance with the WAI-ARIA specifications. WAI-ARIA Accessibility
supports are achieved through the attributes like aria-label . It helps to provides information
about elements in a document for assistive technology.
Aria-label: Attribute provides the text label with some default description for below elements in
chart.
You can change this default description, using description property available in Datalabel ,
Legend , Axis Title and Chart object. It helps the screen reader to read for assistive
purpose.
534
Internationalization
Chart provide supports for internationalization for below chart elements.
Datalabel.
Axis label.
Tooltip.
For more information about number and date formatter you can refer internationalization .
Globalization
Globalization is the process of designing and developing an component that works in different
cultures/locales. Internationalization library is used to globalize number, date, time values in
Chart component using labelFormat property in axis.
Numeric Format
In the below example axis, point and tooltip labels are globalized to EUR.
razor
number-format.cs
@Html.EJS().Chart("container").Series(series =>
{
series.Type(Syncfusion.EJ2.Charts.ChartSeriesType.Column).
Marker(ViewBag.Marker).
XName("x").
YName("yValue").
DataSource(ViewBag.dataSource).
Name("Gold").
Width(2).Add();
}).
PrimaryXAxis(px => px.Interval(1).ValueType(Syncfusion.EJ2.Charts.ValueType.Category
)).
PrimaryYAxis(py => py.LabelFormat("n1")).
Title("Olympic Medal Counts - RIO").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers.Chart
535
{
public partial class ChartController : Controller
{
public IActionResult Column()
{
List<ColumnChartData> chartData = new List<ColumnChartData>
{
new ColumnChartData { x= "USA", yValue= 46 },
new ColumnChartData { x= "GBR", yValue= 27 },
new ColumnChartData { x= "CHN", yValue= 26 }
};
ViewBag.dataSource = chartData;
return View();
}
public class ColumnChartData
{
public string x;
public double yValue;
}
}
}
536
Localization
Localization library allows to localize the default text content of Chart. In Chart component, it has
the static text on some features(like zooming toolbars) and this can be changed to any other
culture(Arabic, Deutsch, French, etc) by defining the locale value and translation object.
Zoom Zoom
ZoomIn ZoomIn
ZoomOut ZoomOut
Reset Reset
Pan Pan
razor
legend.cs
537
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Charts;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class ChartController : Controller
{
538
Overview
The CheckBox is a graphical user interface element that allows you to select one or more options
from the choices. It contains checked, unchecked, and indeterminate states.
Key Features
Supports different states.
Supports label and its position.
Supports small size.
539
Getting Started
This section briefly explains about how to include a simple CheckBox in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
@Html.EJS().CheckBox("default").Label("Default").Render()
razor
default.cs
@Html.EJS().CheckBox("default").Label("Default").Render()
540
Change the CheckBox state
The Essential JS 2 CheckBox contains 3 different states visually, they are:
Checked
Unchecked
Indeterminate
The CheckBox checked property is used to handle the checked and unchecked state. In
checked state a tick mark will be added to the visualization of CheckBox.
Indeterminate
The CheckBox indeterminate state can be set through indeterminate property. CheckBox
indeterminate state masks the real value of CheckBox visually. The Checkbox cannot be
changed to indeterminate state through the user interface, this state can be achieved only
through the property.
razor
state.cs
@section ControlsSection{
@Html.EJS().CheckBox("checked").Label("Checked State").Checked(true).Render()
@Html.EJS().CheckBox("unchecked").Label("Unchecked State").Render()
@Html.EJS().CheckBox("indeterminate").Label("Intermediate State").Intermediate(true
).Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
541
Label and Size
This section explains the different sizes and labels.
Label
The CheckBox caption can be defined by using the label property. This reduces the manual
addition of label for CheckBox. You can customize the label position before or after the
CheckBox through the labelPosition property.
razor
label.cs
@section ControlsSection{
@Html.EJS().CheckBox('cbox1').Label('Left Side Label').LabelPosition('before').Re
nder()
@Html.EJS().CheckBox('cbox2').Label('Right Side Label').LabelPosition('after').Re
nder()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
Size
542
The different CheckBox sizes available are default and small. To reduce the size of default
CheckBox to small, set the cssClass property to e-small .
razor
size.cs
@section ControlsSection{
@Html.EJS().CheckBox('cbox1').Label('Small').CssClass('e-small').Render()
@Html.EJS().CheckBox('cbox2').Label('Default').Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
543
Accessibility
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. CheckBox provides
built-in compliance with WAI-ARIA specifications. WAI-ARIA support is achieved through the
attributes like aria-checked and aria-disabled . It helps the people with disabilities by
providing information about the widget for assistive technology in the screen readers. CheckBox
component contains the checkbox role.
Properties Functionality
aria- Indicates that the element is perceivable but disabled, so it is not editable or
disabled otherwise operable.
Keyboard interaction
Keyboard
Actions
shortcuts
When the checkbox has focus, pressing the Space key changes the
Space
state of the checkbox.
razor
interaction.cs
@section ControlsSection{
@Html.EJS().CheckBox("checked").Label("Checked State").Checked(true).Render()
@Html.EJS().CheckBox("unchecked").Label("Unchecked State").Render()
@Html.EJS().CheckBox("indeterminate").Label("Intermediate State").Intermediate(true
).Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
544
}
</style>
545
How To
The background and border color of the CheckBox is customized through the custom classes to
create primary, success, warning, and danger info type of checkbox.
razor
custom.cs
@section ControlsSection{
@Html.EJS().CheckBox("primary").Label("Primary").Checked(true).CssClass('e-primar
y').Render()
@Html.EJS().CheckBox("success").Label("Success").Checked(true).CssClass('e-succes
s').Render()
@Html.EJS().CheckBox("info").Label("Info").Checked(true).CssClass('e-info').Rende
r()
@Html.EJS().CheckBox("warning").Label("Warning").Checked(true).CssClass('e-warnin
g').Render()
@Html.EJS().CheckBox("danger").Label("Danger").Checked(true).CssClass('e-danger')
.Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
.e-checkbox-wrapper.e-success .e-frame.e-check,
.e-checkbox-wrapper.e-success .e-checkbox:focus + .e-frame.e-check { /* csslint allow:
546
adjoining-classes */
background-color: #689f38;
}
.e-checkbox-wrapper.e-info .e-frame.e-check,
.e-checkbox-wrapper.e-info .e-checkbox:focus + .e-frame.e-check { /* csslint allow: adj
oining-classes */
background-color: #2196f3;
}
.e-checkbox-wrapper.e-warning .e-frame.e-check,
.e-checkbox-wrapper.e-warning .e-checkbox:focus + .e-frame.e-check { /* csslint allow:
adjoining-classes */
background-color: #ef6c00;
}
.e-checkbox-wrapper.e-danger .e-frame.e-check,
.e-checkbox-wrapper.e-danger .e-checkbox:focus + .e-frame.e-check { /* csslint allow: a
djoining-classes */
background-color: #d84315;
}
</style>
547
{
return View();
}
The following section explains about how to customize the height and width of the CheckBox
component.
razor
customheight.cs
@section ControlsSection{
@Html.EJS().CheckBox("customsize").Label("Default").CssClass('e-customsize').Rende
r()
}
<style>
.e-checkbox-wrapper {
margin-top: 30px;
}
.e-customsize.e-checkbox-wrapper .e-frame {
height: 30px;
width: 30px;
padding: 8px 0;
}
.e-customsize.e-checkbox-wrapper .e-check {
font-size: 20px;
}
.e-customsize.e-checkbox-wrapper .e-ripple-container {
height: 52px;
top: -11px;
width: 47px;
}
.e-customsize.e-checkbox-wrapper .e-label {
line-height: 30px;
font-size: 20px;
}
548
</style>
In the following code snippet, Cricket and Hockey are in the checked state, Tennis is in disabled
state and Basketball is in unchecked state. Now, the value that is in checked state only be sent
on form submit.
razor
form.cs
@section ControlsSection{
@Html.EJS().CheckBox("cbox2").Name('Sport').Value('Cricket').Label("Cricket").Check
ed(true).Render()
@Html.EJS().CheckBox("cbox3").Name('Sport').Value('Hockey').Label("Hockey").Checked(
true).Render()
@Html.EJS().CheckBox("cbox4").Name('Sport').Value('Tennis').Label("Tennis").Render(
)
@Html.EJS().CheckBox("cbox1").Name('Sport').Value('Basketball').Label("Basketball")
.Render()
@Html.EJS().Button("primarybtn").Content("Submit").IsPrimary(true).Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
button {
margin: 20px 0 0 5px;
549
}
li {
list-style: none;
}
</style>
Customized CheckBox
Custom Frame
CheckBox frame can be customized as per the requirement by adding CSS rules.
In the following example, to-do list is displayed with round checkbox by changing border-radius
as 100% by adding e-custom class.
razor
customsize.cs
@section ControlsSection{
@Html.EJS().CheckBox("cbox2").Label("Buy Groceries").Checked(true).CssClass('e-cust
om').Render()
@Html.EJS().CheckBox("cbox3").Label("Pay Rent").Checked(true).CssClass('e-custom').
Render()
@Html.EJS().CheckBox("cbox4").Label("Make Dinner").CssClass('e-custom').Render()
@Html.EJS().CheckBox("cbox1").Label("Finish To-do List Article").CssClass('e-custom
').Render()
}
<style>
li {
list-style: none;
}
.e-checkbox-wrapper {
550
margin-top: 18px;
}
.e-custom .e-frame {
border-radius: 100%;
}
.e-checkicon.e-checkbox-wrapper .e-frame.e-check::before {
content: '\e77d';
}
.e-checkicon.e-checkbox-wrapper .e-check {
font-size: 8.5px;
}
.e-checkicon.e-checkbox-wrapper .e-frame.e-check {
background-color: white;
border-color: grey;
color: grey;
}
.e-checkicon.e-checkbox-wrapper:hover .e-frame.e-check {
background-color: white;
border-color: grey;
color: grey;
}
</style>
551
In the following example, the check icon can be customized by changing check icon content,
background and border color in focus and hovered states by adding e-checkicon class.
razor
customicon.cs
@section ControlsSection{
@Html.EJS().CheckBox("cbox2").Label("Buy Groceries").Checked(true).CssClass('e-chec
kicon').Render()
@Html.EJS().CheckBox("cbox3").Label("Pay Rent").Checked(true).CssClass('e-checkicon
').Render()
@Html.EJS().CheckBox("cbox4").Label("Make Dinner").CssClass('e-checkicon').Render()
@Html.EJS().CheckBox("cbox1").Label("Finish To-do List Article").CssClass('e-checki
con').Render()
}
<style>
li {
list-style: none;
}
.e-checkbox-wrapper {
margin-top: 18px;
}
.e-checkicon.e-checkbox-wrapper .e-frame.e-check::before {
content: '\e77d';
}
.e-checkicon.e-checkbox-wrapper .e-check {
font-size: 8px;
}
.e-checkicon.e-checkbox-wrapper .e-frame.e-check {
background-color: white;
border-color: grey;
color: grey;
}
.e-checkicon.e-checkbox-wrapper:hover .e-frame.e-check {
background-color: white;
border-color: grey;
color: grey;
}
552
background-color: white;
border-color: grey;
box-shadow: none;
color: grey;
}
.e-checkicon.e-checkbox-wrapper .e-ripple-element {
background: grey;
}
</style>
Right-To-Left
CheckBox component has RTL support. This can be achieved by setting enableRtl as true .
The following example illustrates how to enable right-to-left support in CheckBox component.
razor
rtl.cs
@section ControlsSection{
@Html.EJS().CheckBox("cbox2").Label("Default").EnableRtl(true).Render()
}
<style>
.e-checkbox-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
553
public ActionResult Rtl()
{
return View();
}
554
Overview
The ColorPicker is a user interface that lets user to pick a color either by selecting the color
values or by adjusting the hue and opacity. It supports various color specifications like RGB
(Red, Green, and Blue), HSV (Hue, Saturation, and Value), and Hex codes.
Key Features
Mode And Value
Custom Palette
Accessibility
555
Getting Started
This section briefly explains about how to include a default ColorPicker in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
// To render ColorPicker.
@Html.EJS().ColorPicker("element").Render()
razor
default.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
// To render ColorPicker.
@Html.EJS().ColorPicker("element").Render()
</div>
}
<style>
556
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
Inline Type
By default, the ColorPicker will be rendered using SplitButton and open the pop-up to access the
ColorPicker. To render the ColorPicker container alone and to access it directly, render it as
inline. It can be achieved by setting the inline property to true .
razor
inline.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
// To render component as inline.
@Html.EJS().ColorPicker("element").Inline(true).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
557
The showButtons property is disabled in this sample because the control buttons are
not needed for inline type. To know about the control buttons functionality, refer to the
showButtons sample.
558
Mode and Value
razor
palette.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
<div class='wrap'>
<h4>Select Color</h4>
//To render palette at initial load.
@Html.EJS().ColorPicker("element").Mode(ColorPickerMode.Palette).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
Color Value
The value property can be used to specify the color value to the ColorPicker. It supports either
three or six digit hex codes. To include opacity , set the color value as four or eight
digit hex code.
In the following sample, the color value sets as four digit hex code, the last digit represents the
opacity value.
559
razor
value.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
//To set color value.
@Html.EJS().ColorPicker("element").Value("035a").ModeSwitcher(false).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
560
Accessibility
ARIA attributes
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. It helps to provide
information about the widget for assistive technology to the disabled person in screen reader.
ColorPicker provides built-in compliance with the WAI-ARIA specifications. WAI-ARIA supports is
achieved through the attributes like aria-label and aria-selected applied to the color palette
tiles.
To know about the accessibility of SplitButton, refer to the SplitButton Accessibility section.
Properties Functionality
Keyboard interaction
To know about the keyboard interaction of SplitButton, refer to the SplitButton Keyboard
interaction section.
The following list of keys can be used to interact with the ColorPicker after the popup has
opened.
Press To do this
Upper Arrow Moves the handler/tile up from the current position.
Down Arrow Moves the handler/tile down from the current position.
Left Arrow Moves the handler/tile left from the current position.
Right Arrow Moves the handler/tile right from the current position.
razor
accessibility.cs
561
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
@Html.EJS().ColorPicker("element").Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
562
How To
The following section explains how to customize various aspects of the ColorPicker.
razor
show-buttons.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
//To hide control buttons.
@Html.EJS().ColorPicker("element").ShowButtons(false).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
In the following sample, the showButtons property is disabled to hide the control buttons and it
renders only the Palette area.
razor
563
palette-alone.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
//To render Palette alone.
@Html.EJS().ColorPicker("element").Mode(ColorPickerMode.Palette).ModeSwitcher(f
alse).ShowButtons(false).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
Custom Palette
By default, the Palette will be rendered with default colors. To load custom colors in the palette,
specify the colors in the presetColors property. To customize the color palette, add a custom
class to palette tiles using BeforeTileRender event.
razor
custom-palette.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
<div class='wrap'>
<div id="preview"></div>
<h4>Select Color</h4>
//To render custom palette.
564
@Html.EJS().ColorPicker("element").Mode(ColorPickerMode.Palette).Inline(true).M
odeSwitcher(false).ShowButtons(false).Columns(4).BeforeTileRender("tileRender").PresetC
olors(@ViewBag.customColors).Change("onChange").Render()
</div>
}
<style>
.e-container {
background-color: transparent;
border-color: transparent;
box-shadow: none;
}
.e-container .e-custom-palette.e-palette-group {
height: 182px;
}
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
#preview {
background-color: #ba68c8;
height: 50px;
width: 100%;
}
565
</style>
<script>
</script>
ViewBag.customColors = custom[0];
return View();
}
razor
hide-input.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
// To hide the input area.
@Html.EJS().ColorPicker("element").CssClass("e-hide-value").ModeSwitcher(false)
.Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
Disabled
To achieve disabled state in ColorPicker, set the disabled property to true . The ColorPicker
pop-up cannot be accessed in disabled state.
razor
disabled.cs
@section ControlsSection{
<div class='wrap'>
<h4>Disabled state</h4>
//To disable the ColorPicker.
@Html.EJS().ColorPicker("element").Disabled(true).Render()
</div>
567
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
RTL
ColorPicker component has RTL support. It helps to render the ColorPicker from right-to-left
direction. This can be achieved by setting the enableRtl property to true .
The following example illustrates how to enable right-to-left support in ColorPicker component.
razor
rtl.cs
@section ControlsSection{
<div class='wrap'>
<h4>Choose Color</h4>
//To render ColorPicker from right to left.
@Html.EJS().ColorPicker("element").EnableRtl(true).Render()
</div>
}
<style>
.wrap {
margin: 0 auto;
width: 300px;
text-align: center;
}
</style>
568
569
Overview
The ContextMenu is a graphical user interface that appears on the user right click/touch hold
action. It has the support to provide nested level menu items.
Key Features
Separator
Icons and Navigation
Template and Multilevel nesting
Accessibility
570
Getting Started
This section briefly explains about how to include a simple ContextMenu in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
ViewBag.menuItems variable is used for bounding the items property in view page.
Bind dataSource
Populate the menu items in ContextMenu by using the items property. Here, the JSON values
are passed to the ContextMenu component are generated in default.cs and assigned to
ViewBag variable.
571
menuItems.Add(new
{
text = "Cut"
});
menuItems.Add(new
{
text = "Copy"
});
menuItems.Add(new
{
text = "Paste"
});
ViewBag.menuItems = menuItems;
return View();
}
razor
default.cs
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
572
font-size: 14px;
}
</style>
razor
separator.cs
@section ControlsSection{
<style>
#contextmenutarget {
573
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Separator()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Cut"
});
menuItems.Add(new
{
text = "Copy"
});
menuItems.Add(new
{
text = "Paste"
});
menuItems.Add(new
{
separator = true
});
menuItems.Add(new
{
text = "Font"
});
menuItems.Add(new
{
574
text = "Paragraph"
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
The separator property should not be given along with the other fields in the MenuItem .
575
Icons and Navigation
Icons
The ContextMenu item have an icon/image in it to provide visual representation of the action. To
place the icon on a menu item, set the iconCss property to e-icons with the required icon CSS.
By default, the icon is positioned to the left side of the menu item. In the following sample, the
icons for Cut, Copy and Paste menu items are added using the iconCss property.
razor
icons.cs
@section ControlsSection{
<style>
#target {
border: 1px dashed;
height: 150px;
padding: 10px;
position: relative;
text-align: justify;
color: gray;
user-select: none;
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
</style>
576
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Icons()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut",
iconCss = "e-icons e-cut"
});
items.Add(new
{
text = "Copy",
iconCss = "e-icons e-copy"
});
items.Add(new
{
text = "Paste",
iconCss = "e-icons e-paste"
});
return View();
}
}
}
The Essential JS 2 provides a set of icons that can be loaded by applying e-icons class
name to the element. You can also use third party icons on the contextmenu menuItems
using the iconCss property.
Navigation
Navigation in ContextMenu is usage to navigate to the other web page when menu item is
clicked. This can be achieved by providing link to the menu item using the url property. In the
following sample, Navigation URL for Flipkart, Amazon, and Snapdeal menu items are added
using the url property.
razor
navigation.cs
577
@section ControlsSection{
<style>
#target {
border: 1px dashed;
height: 150px;
padding: 10px;
position: relative;
text-align: justify;
color: gray;
user-select: none;
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Navigation()
{
List<object> items = new List<object>();
578
items.Add(new
{
text = "Flipkart",
iconCss = "e-icons e-link",
url: 'https://www.google.co.in/search?q=flipkart'
});
items.Add(new
{
text = "Amazon",
iconCss = "e-icons e-link",
url: 'https://www.google.co.in/search?q=amazon'
});
items.Add(new
{
text = "Snapdeal",
iconCss = "e-icons e-link",
url: 'https://www.google.co.in/search?q=snapdeal'
});
return View();
}
}
}
579
Template and Multilevel nesting
Template
The ContextMenu items can be customized by using the Render event. The item render event
triggers while rendering each menu item. The event argument will be used to identify the menu
item and customize it based on the requirement. In the following sample, the menu item is
rendered with keycode for specified action in ContextMenu using the template. Here, the
keycode is specified for Save as, View page source, and Inspect in the right side corner of the
menu items by adding span element in the beforeItemRender event.
razor
template.cs
@section ControlsSection{
<script>
function beforeItemRender(args) {
var shortCutSpan = createElement('span');
var text = args.item.text;
var shortCutText = text === 'Save as...' ? 'Ctrl + S' : (text === 'View pag
e source' ?
'Ctrl + U' : 'Ctrl + Shift + I');
shortCutSpan.textContent = shortCutText;
args.element.appendChild(shortCutSpan);
shortCutSpan.setAttribute('class','shortcut');
}
</script>
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
580
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Template()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Save as..."
});
menuItems.Add(new
{
text = "View page source"
});
menuItems.Add(new
{
text = "Inspect"
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
Multilevel nesting
The Multiple level nesting supports in ContextMenu. It can be achieved by mapping the items
property inside the parent menuItems . In the below sample, three level nesting of ContextMenu
is provided.
razor
nesting.cs
581
@section ControlsSection{
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Nesting()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Show All Bookmarks"
});
menuItems.Add(new
{
text = "Bookmarks Toolbar",
items = new List<object>()
{
new {
text = "Most Visited",
582
items = new List<object>()
{
new {
text = "Google"
},
new {
text = "Gmail"
}
}
},
new {
text = "Recently Added"
}
}
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
583
Accessibility
ARIA attributes
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. ContextMenu provides
built-in compliance with WAI-ARIA specifications. WAI-ARIA support is achieved through the
attributes like aria-expanded and aria-haspopup applied for menu item in ContextMenu. It
helps the people with disabilities by providing information about the widget for assistive
technology in the screen readers. ContextMenu component contains the menu role and
menuItem role.
Properties Functionality
menu This role will be specified for an item which have sub menu.
menuItem This role will be specified for an item that do not have sub menus.
aria-
Indicates the availability and type of interactive popup element.
haspopup
Keyboard interaction
Left Close the current sub menu and navigates to the parent menu.
Right Navigates and open the next sub menu.
razor
accessibility.cs
@section ControlsSection{
@Html.EJS().ContextMenu("contextmenu").Items((IEnumerable<object>)ViewBag.items).Re
nder();
584
}
<script>
window.onload = function () {
document.getElementById("contextmenu").ej2_instances[0].open(40, 20);
}
</script>
<style>
/* csslint ignore:start */
@font-face {
font-family: 'e-dropdown-btn';
src:
url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMjjNRVMAAAEo
AAAAVmNtYXDicOK6AAABjAAAADhnbHlmGcEPFQAAAcwAAAMwaGVhZA69CA8AAADQAAAANmhoZWEH9AQEAAAArAA
AACRobXR4DAAAAAAAAYAAAAAMbG9jYQDYAZgAAAHEAAAACG1heHABEgDAAAABCAAAACBuYW1lxY1d1QAABPwAAA
KFcG9zdPJwcMoAAAeEAAAASAABAAAEAAAAAFwEAAAAAAADlwABAAAAAAAAAAAAAAAAAAAAAwABAAAAAQAAgmhm8
l8PPPUACwQAAAAAANYD4Y8AAAAA1gPhjwAAAAADlwP0AAAACAACAAAAAAAAAAEAAAADALQABQAAAAAAAgAAAAoA
CgAAAP8AAAAAAAAAAQQAAZAABQAAAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAUGZFZABA4mDiYQQAAAAAXAQAAAAAAAABAAAAAAAABAAAAAQAAAAEAAAAAAAAAgAAAAMAAAAUAAMAAQAAAB
QABAAkAAAABAAEAAEAAOJh//8AAOJg//8AAAABAAQAAAABAAIAAAAAANgBmAAFAAAAAAOXA/QABAAlAC0ATgCzA
AABIScHJzcVHwc/By8HDwYBFSE1MxEhESUHFQ8GLwc/Bx8GJysBDw4RHw4zITM/DhEvDisBLw4rAQ8NAUQBd1xA
fr0BAwQGBwgICgkJCAcGBAMBAQMEBgcICQkKCAgHBgQD/qYB1l79jQFoAQMEBgcHCQkJCQgGBgQDAQEDBAYGCAk
JCQkHBwYEA6y9CgkICQgHBwcGBQQEAwMBAQEBAwMDBQUGBwcHCAkICQoCeAoJCAkIBwcHBgUEBAMDAQEBAQMDAw
UFBgcHBwgJCAkKvQQEBgUHBwcICQkJCgoKCwsLCwoKCgkJCQgHBwcFBgQBBYVRuh0FBQkIBwUFAgEBAgUFBwgJC
gkJCAcGBAMBAQMEBgcICQEifX39LwLRMwQFCAgHBQUCAQECBQUHCAgJCQkIBwUEAwEBAwQFBwgJIgICAwQFBQYG
BwgICAkJCf0pCQkJCAgIBwYGBQUEAwICAgIDBAUFBgYHCAgICQkJAtcJCQkICAgHBgYFBQQDAgIKCQkICAgHBgY
FBAQDAgICAgMEBAUGBgcICAgJCQAFAAAAAAOXA/QABwAPABcAOACdAAABHwIjPwIDMzczFzMDIycVITUzESERJQ
cVDwYvBz8HHwYnKwEPDhEfDjMhMz8OES8OKwEvDisBDw0B/wQKK3MmBQ6dMyeHKDWCO90B1l79jQFoAQMEBgcHC
QkJCQgGBgQDAQEDBAYGCAkJCQkHBwYEA6y9CgkICQgHBwcGBQQEAwMBAQEBAwMDBQUGBwcHCAkICQoCeAoJCAkI
BwcHBgUEBAMDAQEBAQMDAwUFBgcHBwgJCAkKvQQEBgUHBwcICQkJCgoKCwsLCwoKCgkJCQgHBwcFBgQCFREigG4
SM/6wd3cBe/t9ff0vAtEzBAUICAcFBQIBAQIFBQcICAkJCQgHBQQDAQEDBAUHCAkiAgIDBAUFBgYHCAgICQkJ/S
kJCQkICAgHBgYFBQQDAgICAgMEBQUGBgcICAgJCQkC1wkJCQgICAcGBgUFBAMCAgoJCQgICAcGBgUEBAMCAgICA
wQEBQYGBwgICAkJAAAAABIA3gABAAAAAAAAAAEAAAABAAAAAAABAA8AAQABAAAAAAACAAcAEAABAAAAAAADAA8A
FwABAAAAAAAEAA8AJgABAAAAAAAFAAsANQABAAAAAAAGAA8AQAABAAAAAAAKACwATwABAAAAAAALABIAewADAAE
ECQAAAAIAjQADAAEECQABAB4AjwADAAEECQACAA4ArQADAAEECQADAB4AuwADAAEECQAEAB4A2QADAAEECQAFAB
YA9wADAAEECQAGAB4BDQADAAEECQAKAFgBKwADAAEECQALACQBgyBDb250ZXh0TWVudSAoMilSZWd1bGFyQ29ud
GV4dE1lbnUgKDIpQ29udGV4dE1lbnUgKDIpVmVyc2lvbiAxLjBDb250ZXh0TWVudSAoMilGb250IGdlbmVyYXRl
ZCB1c2luZyBTeW5jZnVzaW9uIE1ldHJvIFN0dWRpb3d3dy5zeW5jZnVzaW9uLmNvbQAgAEMAbwBuAHQAZQB4AHQ
ATQBlAG4AdQAgACgAMgApAFIAZQBnAHUAbABhAHIAQwBvAG4AdABlAHgAdABNAGUAbgB1ACAAKAAyACkAQwBvAG
4AdABlAHgAdABNAGUAbgB1ACAAKAAyACkAVgBlAHIAcwBpAG8AbgAgADEALgAwAEMAbwBuAHQAZQB4AHQATQBlA
G4AdQAgACgAMgApAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAHUAcwBpAG4AZwAgAFMAeQBuAGMAZgB1
AHMAaQBvAG4AIABNAGUAdAByAG8AIABTAHQAdQBkAGkAbwB3AHcAdwAuAHMAeQBuAGMAZgB1AHMAaQBvAG4ALgB
jAG8AbQAAAAACAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBAgEDAQQAD01UX1Bhc3RlU3BlY2lhbA
xNVF9QYXN0ZVRleHQAAA==) format('truetype');
585
font-weight: normal;
font-style: normal;
}
/* csslint ignore:stop */
.e-ddb-icons {
font-family: 'e-dropdown-btn';
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: 1;
text-transform: none;
}
.e-edit::before {
content: '\e80a';
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
.e-text::before {
content: '\e261';
}
.e-special::before {
content: '\e260';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
586
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Accessibility()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Cut",
iconCss = "e-cm-icons e-cut"
});
menuItems.Add(new
{
text = "Copy",
iconCss = "e-cm-icons e-copy"
});
menuItems.Add(new
{
text = "Paste",
iconCss = "e-cm-icons e-paste",
items = new List<object>()
{
new { text = "Paste Text", iconCss = "e-cm-icons e-pastetext" },
new { text = "Paste Special", iconCss = "e-cm-icons e-pastespecial"
}
}
});
}
}
}
587
How To
Data Binding
To bind local data source to the ContextMenu, menu items are populated from data source and
mapped to items property.
The below example demonstrates how to bind local data source to the ContextMenu and
separator is added using insertAfter method.
razor
@section ControlsSection{
<script>
function items() {
var data = [
{ id: 1, parentId: null, text: 'View' },
{ id: 2, parentId: null, text: 'Sort by' },
{ id: 3, parentId: null, text: '' },
{ id: 4, parentId: null, text: 'New' },
{ id: 5, parentId: null, text: '' },
{ id: 6, parentId: null, text: 'Display Settings' },
{ id: 7, parentId: null, text: 'Personalize' },
//first level child
{ id: 8, parentId: 1, text: 'Large Icons' },
{ id: 9, parentId: 1, text: 'Medium Icons' },
{ id: 10, parentId: 1, text: 'Small Icons' },
{ id: 11, parentId: 2, text: 'Name' },
{ id: 12, parentId: 2, text: 'Size' },
{ id: 13, parentId: 4, text: 'Folder' },
{ id: 14, parentId: 4, text: 'Shortcut' },
{ id: 15, parentId: 4, text: '' },
{ id: 16, parentId: 4, text: 'Contact' }];
var record;
var menuItems = [];
for (var i = 0; i < data.length; i++) {
record = data[i];
if (record.parentId) {
588
if (!menuItems[record.parentId - 1].items) {
menuItems[record.parentId - 1].items = []
}
menuItems[record.parentId - 1].items.push({ text: record.text });
} else {
menuItems.push({ text: record.text });
}
}
}
function beforeItemRender(args) {
if (!args.item.text) {
args.element.classList.add('e-separator');
}
}
</script>
<style>
button {
margin: 20px 0 0 5px;
}
#target {
border: 1px dashed;
height: 150px;
padding: 10px;
position: relative;
text-align: justify;
color: gray;
user-select: none;
}
</style>
razor
openclose.cs
@section ControlsSection{
589
<button class='e-btn' id="btnElement">Open ContextMenu</button>
@Html.EJS().ContextMenu("contextmenu").Items((IEnumerable<object>)ViewBag.items).Re
nder()
<script>
document.getElementById('btnElement').onclick=function() {
var contextMenuObj = document.getElementById("contextmenu").EJ2_instances[0];
contextMenuObj.open(60, 20);
}
</script>
<style>
button {
margin: 20px 0 0 5px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult OpenClose()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Cut"
});
menuItems.Add(new
{
text = "Copy"
});
menuItems.Add(new
{
590
text = "Paste"
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
razor
table.cs
@section ControlsSection{
<script>
function beforeItemRender(args) {
if (args.item.text === 'Insert') {
args.element.innerText = '';
args.element.appendChild(this.createTable());
args.element.style.height = '105px';
args.element.classList.add('e-hover-list');
}
if (args.item.text === 'Insert Table') {
args.element.classList.add('e-hover-list');
}
}
function createTable() {
var table = document.createElement('table');
for (let i: number = 0; i < 5; i++) {
let row: HTMLElement = document.createElement('tr');
table.appendChild(row);
for (let j: number = 0; j < 6; j++) {
591
let col: HTMLElement = document.createElement('td');
row.appendChild(col);
col.setAttribute('class', 'e-data');
}
}
return table;
}
</script>
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Table()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Cut",
iconCss = "e-icons e-cut"
});
menuItems.Add(new
{
text = "Copy",
iconCss = "e-icons e-copy"
592
});
menuItems.Add(new
{
text = "Paste",
iconCss = "e-icons e-paste"
});
menuItems.Add(new
{
separator = true
});
menuItems.Add(new
{
text = "Link",
iconCss = "e-icons e-link"
});
menuItems.Add(new
{
text = "Table",
items = new List<object>()
{
new {
text = "Insert Table",
},
new {
separator = true
},
new {
text = "Insert"
}
}
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
UI Components in ContextMenu
UI components can also be placed inside the each li element of ContextMenu.
In the following example, CheckBox component is placed inside each li element and this can
be achieved by creating CheckBox component in beforeItemRender event and appending it into
the li element.
razor
uicomponents.cs
593
@section ControlsSection{
<script>
function beforeClose(args) {
args.cancel = true;
}
function select(args) {
var selectedElem = args.element.parentElement.querySelectorAll('.e-selected');
for(var i=0; i < selectedElem.length; i++){
var ele = selectedElem[i];
ele.classList.remove('e-selected');
}
var checkbox = args.element.childNodes[0] as HTMLElement;
var frame = checkbox.querySelector('.e-frame'));
if (checkbox && frame.classList.contains('e-check')) {
frame.classList.remove('e-check');
} else if (checkbox) {
frame.classList.add('e-check');
}
}
var i = 1;
function beforeItemRender(args) {
var check = @Html.EJS().CheckBox("checkbox" + i).Label(args.element.text).Check
ed((args.item.text == 'Option 2') ? true : false).Render()
args.element.innerHTML = '';
args.element.appendChild(check);
i++;
}
</script>
<style>
.list {
display: none;
}
#contextmenutarget {
594
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult UIComponents()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Option 1"
});
menuItems.Add(new
{
text = "Option 2"
});
menuItems.Add(new
{
text = "Option 3"
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
595
This section explains about how to open a dialog on ContextMenu item click. This can be
achieved by handling dialog open in select event of the ContextMenu.
In the following sample, Dialog will open while clicking Save As... item:
razor
dialog.cs
@section ControlsSection{
<script>
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
function itemSelect(args) {
var dialog = document.getElementById("dialog").ej2_instances[0]
dialog.show();
}
</script>
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
596
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Dialog()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Back"
});
menuItems.Add(new
{
text = "Forward"
});
menuItems.Add(new
{
text = "Reload"
});
menuItems.Add(new
{
separator: true
});
menuItems.Add(new
{
text = "Save As..."
});
menuItems.Add(new
{
text = "Print"
});
menuItems.Add(new
{
text = "Cast"
});
ViewBag.menuItems = menuItems;
return View();
}
597
}
}
razor
underline.cs
@section ControlsSection{
<script>
function beforeItemRender(args) {
if (args.item.text === "Copy") {
args.element.innerHTML = '<u>C</u>opy';
}
}
</script>
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
598
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Underline()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
text = "Cut"
});
menuItems.Add(new
{
text = "Copy"
});
menuItems.Add(new
{
text = "Paste"
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
Effect Functionality
SlideDown Specifies the sub menu transform with slide down effect.
The following sample illustrates how to open ContextMenu with FadeIn effect with the
duration of 800ms .
razor
animation.cs
599
@section ControlsSection{
<script>
var animation = {
effect: 'FadeIn',
duration: 800
};
</script>
<style>
#contextmenutarget {
border: 1px dashed;
height: 250px;
padding: 10px;
position: relative;
text-align: center;
color: gray;
line-height: 17;
font-size: 14px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ContextMenuController : Controller
{
public IActionResult Animation()
{
List<object> menuItems = new List<object>();
menuItems.Add(new
{
600
text = "Show All Bookmarks"
});
menuItems.Add(new
{
text = "Bookmarks Toolbar",
items = new List<object>()
{
new {
text = "Most Visited",
items = new List<object>()
{
new {
text = "Google"
},
new {
text = "Gmail"
}
}
},
new {
text = "Recently Added"
}
}
});
ViewBag.menuItems = menuItems;
return View();
}
}
}
601
Overview
The DatePicker is a graphical user interface component that allows the user to select or enter a
date value.
Key Features
Date Range
Globalization
Strict Mode
Customization
Start and Depth View
Accessibility
602
Getting Started
This section briefly explains how to include simple DatePicker control in your ASP.NET MVC
application. You can refer to ASP.NET MVC Getting Started documentation page for system
requirements, and configure common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
razor
@Html.EJS().DatePicker("datepicker").Render();
Running the above code will display the basic DatePicker on the browser.
The below example demonstrates the DatePicker to select a date within a range from 5 to 27 in a
current month.
razor
daterange.cs
@Html.EJS().DatePicker("datepicker").Value(ViewBag.value).Min(ViewBag.minDate).Max(View
Bag.maxDate).Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
603
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.minDate= new DateTime(DateTime.Now.Year,DateTime.Now.Month,05);
ViewBag.maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 27);
return View();
}
}
}
604
Date Range
DatePicker provides an option to select a date value within a specified range by using the min
and max properties. Always the min value has to be lesser than the max value.
When the min and max properties are configured and the selected date value is out-of-range or
invalid, then the model value will be set to out of range date value or null respectively with
highlighted error class to indicates the date is out of range or invalid.
The value property depends on the min/max with respect to strictMode property.
The below example allows selecting a date within the range from 7th to 27th day in a month.
razor
daterange.cs
@Html.EJS().DatePicker("element").Value(ViewBag.value).Min(ViewBag.minDate).Max(ViewBag
.maxDate).Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
ViewBag.minDate= new DateTime(DateTime.Now.Year,DateTime.Now.Month,07);
ViewBag.maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 27);
return View();
}
}
}
605
If the value of min or max properties changed through code behind, then you have to
update the value property to set within the range.
606
Date Format
Date format is a way of representing the date value in different string format in textbox.
By default the DatePicker's format is based on the culture. You can also set the own custom
format by using the format property.
Once the date format property has been defined it will be common to all the cultures.
To know more about the date format standards, refer to the Internationalization Date Format
section.
The following example demonstrates the DatePicker with the custom format ( yyyy-MM-dd ).
razor
date-format.cs
@Html.EJS().DatePicker("element").Value(ViewBag.value).Format("yyyy-MM-dd").Placeholder(
"Enter date").Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
return View();
}
}
}
607
Globalization
Globalization is the combination of adapting the component to various languages by means of
parsing and formatting the date or number Internationalization , and also by adding cultural
specific customizations and translating the text localization .
By default, DatePicker date format, week and month names are specific to the American
English culture. It utilizes the Essential JavaScript 2 Internationalization package to parse
and format the date object based on the culture by using the official UNICODE CLDR JSON data. It
provides the loadCldr method to load culture specific CLDR JSON data.
To go with the different culture other than English , follow the below steps.
Install the CLDR-Data package by using the below command (it installs the CLDR JSON
data). To know more about CLDR-Data refer the CLDR-Data link.
Once the package installed, you can find the culture specific JSON data under the location
\node_modules\cldr-data .
Now use the loadCldr method to load the culture specific CLDR JSON data.
In ASP.NET MVC refer the culture files directly from \node_modules\cldr-data location. But in
ASP.NET Core, the static file contents are should present under wwwroot folder. For this,
manually copy the CLDR-Data from the node_modules folder and place inside the wwwroot
folder and refer from the \wwwroot\cldr-data location as like the below code examples
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../wwwroot/
cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
608
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node_mod
ules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
Before changing to a culture other than English , ensure that locale text for the concerned
culture is loaded through load method of L10n class.
razor
@Html.EJS().DatePicker("datepicker").Locale("de").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
609
datepicker = document.getElementById('datepicker').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
'de': {
'datepicker': { placeholder: 'Wählen Sie ein Datum',
today: 'heute' }
}
});
loadCultureFiles('de');
datepicker.locale = 'de';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
Right-To-Left
The DatePicker supports RTL (right-to-left) functionality for languages like Arabic and Hebrew to
displays the text in the right-to-left direction. Use enableRtl property to set the RTL direction.
610
The following code example initialize the DatePicker component in Arabic culture and also
explains how to set the localized text to the placeholder using load method of L10n class.
razor
@Html.EJS().DatePicker("datepicker").EnableRtl(true).Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
datepicker = document.getElementById('datepicker').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
'ar': {
'datepicker': { placeholder: ''اﺧﺘﺮ ﺗﺎرﻳﺨﺎ,
today: '} 'اﻟﯿﻮم
}
});
loadCultureFiles("ar");
datepicker.enableRtl = datepicker.locale === 'ar';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
611
</script>
612
Strict Mode
The strictMode is an act,that allows the user to enter only the valid date within the specified
min/max range in textbox. If the date is invalid, then the component will stay with the previous
value. Else, if the date is out of range, then the component will set the date to the min/max date.
The following example demonstrates the DatePicker in strictMode with min/max range of 5th to
25th in a month of May. Here, it allows to enter only the valid date within the specified range. If
you are trying to enter the out-of-range value as like 28th of May, then the value will set to the
max date of 25th May. Since the value 28th is greater than to max value of 25th. Or else if you
are trying to enter the invalid date, then the value will stay with the previous value.
razor
strict-true.cs
@Html.EJS().DatePicker("element").StrictMode(true).Format("dd/MM/yyyy").Value(ViewBag.v
alue).Min(ViewBag.minDate).Max(ViewBag.maxDate).Placeholder("Enter date").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult DefaultFunctionalities()
{
ViewBag.value = new DateTime(2018, 5, 28);
ViewBag.minDate= new DateTime(2018, 5, 5);
ViewBag.maxDate = new DateTime(2018, 5, 25);
return View();
}
}
}
613
By default, the DatePicker act in strictMode false state, that allows to enter the invalid or out-
of-range date in textbox.
If the date is out-of-range or invalid, then the model value will be set to out of range date value
or null respectively with highlighted error class to indicates the date is out of range or
invalid.
The following example demonstrates the strictMode as false . Here, it allows to enter the
valid or invalid value in textbox. If you are entering out-of-range or invalid date value, then the
model value will be set to out of range date value or null respectively with highlighted
error class to indicates the date is out of range or invalid.
razor
strict-false.cs
@Html.EJS().DatePicker("element").Format("dd/MM/yyyy").Value(ViewBag.value).Min(ViewBag
.minDate).Max(ViewBag.maxDate).Placeholder("Enter date").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult DefaultFunctionalities()
{
ViewBag.value = new DateTime(2018, 5, 28);
ViewBag.minDate= new DateTime(2018, 5, 5);
ViewBag.maxDate = new DateTime(2018, 5, 25);
return View();
}
}
}
If the value of min or max properties changed through code behind, then you have to
update the value property to set within the range.
614
Customization
You can customize the entire appearance of the input element and Calendar by using custom
cssClass property. and also you can use the calendar's renderDayCell event to customize the
appearance of the each day cell.
Below is the list of classes that provides flexible way to customize the DatePicker component.
The following example disables the weekends of every month using renderDayCell event. Here
we have used the e-disabled class to highlight the disabled date.
razor
@Html.EJS().DatePicker("element").RenderDayCell("onRenderCell").Placeholder("Choose a
Date").Render()
<script>
function onRenderCell(args) {
if (args.date.getDay() == 0 || args.date.getDay() == 6) {
//sets isDisabled to true to disable the date.
615
args.isDisabled = true;
//To know about the disabled date customization, you can refer in "styles.css".
}
}
</script>
616
Start and Depth View
The DatePicker has the following predefined views that provides a flexible way to navigate back
and forth to select the date.
View Description
Start view
You can use the start property to define the initial rendering view.
The following example demonstrates how to create a DatePicker with decade as initial
rendering view.
razor
@Html.EJS().DatePicker("element").Start(Syncfusion.EJ2.DatePicker.CalendarView.Decade).
Placeholder("Choose a Date").Render();
Depth view
Define the depth property to control the view navigation.
Always the depth view has to be smaller than the start view, otherwise the view restriction
will be not restricted.
The following example demonstrates how to create a DatePicker that allows users to select a
month.
razor
@Html.EJS().DatePicker("element").Depth(Syncfusion.EJ2.DatePicker.CalendarView.Year).St
art(Syncfusion.EJ2.DatePicker.CalendarView.Decade).Placeholder("Choose a Date").Render(
)
To know more about Calendar views refer the Calendar's Calendar Views section.
617
Accessibility
The Web accessibility defines a way to make web content and web applications more accessible
to disabled people. It especially helps the dynamic content change and advanced user interface
controls developed with Ajax, HTML, JavaScript, and related technologies.
DatePicker provides built-in compliance with the WAI-ARIA specifications. WAI-ARIA supports is
achieved through the attributes like aria-expanded , aria-disabled , aria-activedescendant
applied to the input element.
To know about the accessibility of Calendar refer to the Calendar's Accessibility section.
It helps to provide information about the widget for assistive technology to the disabled person in
screen reader.
Keyboard Interaction
You can use the following keys to interact with the DatePicker. The component implements the
keyboard navigation support by following the WAI-ARIA practices.
Input Navigation
Before opening the popup, use the below list of keys to control the popup element.
Press To do this
Alt + Down Arrow Opens the popup.
Calendar Navigation
Use the below list of keys to navigate the Calendar after the popup has opened.
Press To do this
618
Left Arrow Focus the previous date.
Control + Upper Moves into the inner level of view like month-year, year-
Arrow decade
Control + Down Moves out from the depth level view like decade-year, year-
Arrow month
razor
@Html.EJS().DatePicker("element").Placeholder("Choose a Date").Render();
<script>
document.addEventListener('keyup', function (e) {
if (e.altKey && e.keyCode === 84) {
// press alt+t to focus the control.
var datepickerObject = document.getElementById("element").ej2_instances[0];
datepickerObject.element.focus();
}
})
</script>
619
How To
The following section explains how the DatePicker can be easily customizable in various aspects.
Disabled State
To disable the DatePicker, use its enable property.
razor
@Html.EJS().DatePicker("datepicker").Enabled("false").Render()
Using placeholder you can display a short hint in the input element.
razor
@Html.EJS().DatePicker("datepicker").Placeholder("Enter date").Render()
razor
read.cs
@Html.EJS().DatePicker("datepicker").Readonly("true").Value(ViewBag.value).Placeholder(
"Choose a Date").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
620
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
return View();
}
}
}
The following example demonstrates how to prevent the popup from closing.
razor
popupclose.cs
@Html.EJS().DatePicker("datepicker").close("onClose").Placeholder("Choose a Date").Ren
der()
<script>
document.addEventListener('DOMContentLoaded', function () {
var datepickerObject = document.getElementById("datepicker").ej2_instances[0];
datepickerObject.show();
});
function onClose (args) {
// prevent the popup close
args.preventDefault();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
621
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
return View();
}
}
}
razor
@Html.EJS().DatePicker("datepicker").Placeholder("Choose a Date").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
var datepickerObject = document.getElementById("datepicker").ej2_instances[0];
document.getElementsByTagName('button')[0].onclick = function () {
datepickerObject.focusIn();
}
</script>
razor
@Html.EJS().DatePicker("datepicker").Placeholder("Choose a Date").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
var datepickerObject = document.getElementById("datepicker").ej2_instances[0];
622
datepickerObject.focusIn();
document.getElementsByTagName('button')[0].onclick = function () {
datepickerObject.focusOut();
}
}
</script>
In this below example, the required field validation is implemented by mapping the name attribute
value to the rules property. It will validate the DatePicker component and display the validation
message when the textbox value is empty during form post back or focus out.
razor
validation.cs
<script>
document.addEventListener('DOMContentLoaded', function () {
var options = {
rules: {
//must specify the name attribute value in rules section
'datevalue': { required: true }
},
customPlacement: (inputElement, errorElement) => {
//to place the error message in custom position
//inputElement - target element where the error text will be ap
pended
//errorElement - error text which will be displayed.
inputElement.parentElement.parentElement.appendChild(errorEleme
nt);
}
};
var formObject = new ej.inputs.FormValidator('#form-element', options);
});
623
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
return View();
}
}
}
624
Overview
The DateRangePicker is a graphical user interface control that allows to select a date range.
Key Features
Range Restriction
Globalization
Strict Mode
Customization
Accessibility
625
Getting Started
This section briefly explains how to include simple DateRangePicker control in your ASP.NET
MVC application. You can refer to ASP.NET MVC Getting Started documentation page for
system requirements, and configure common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
626
razor
getting-started.cs
@Html.EJS().DateRangePicker("daterangepicker").Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DateRangePickerController: Controller
{
// GET: /<controller>/
public IActionResult sample()
{
return View();
}
}
}
razor
daterange.cs
@Html.EJS().DateRangePicker("daterangepicker").StartDate(ViewBag.startDate).EndDate(Vi
ewBag.endDate).Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
627
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DateRangePickerController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.startDate = new DateTime(2017, 11, 09);
ViewBag.endDate = new DateTime(2017, 11, 21);
return View();
}
}
}
628
Range Restriction
Range selection in a DateRangePicker can be made-to-order with desire restrictions based on
the application needs.
In the following sample, you can select a range from 15th day of this month to 15th day of next
month.
razor
daterange.cs
@Html.EJS().DateRangePicker("element").Min(ViewBag.minDate).Max(ViewBag.maxDate).Placeh
older("Choose a Date").Render();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DateRangePickerController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
ViewBag.minDate= new DateTime(DateTime.Now.Year,DateTime.Now.Month,15);
ViewBag.maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month+1, 15)
;
return View();
}
}
629
}
If strictMode is enabled, and both the start, end date is lesser than the min date
then start and end date will be updated with min date. If both the start and end date
is higher than the max date then start and end date will be updated with max date. Or
else, if startDate is less than min date, startDate will be updated with min date or if
endDate is greater than max date, endDate will be updated with the max date.
Range span
Span between ranges can be limited to avoid excess or less days selection towards the required
days in a range. In this, minimum and maximum span allowed within the date range can be
customized by minDays and maxDays properties.
minDays - Sets the minimum number of days between start and end date.
maxDays - Sets the maximum number of days between start and end date.
In the following sample, the range selection should be greater than 3 days and less than 8 days
else it will not set.
razor
rangespan.cs
@Html.EJS().DateRangePicker("daterangepicker").Placeholder("Select a Range").MinDays(4
).MaxDays(10).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DateRangePickerController : Controller
{
// GET: /<controller>/
public IActionResult DateRange()
{
return View();
630
}
}
}
Strict mode
DateRangePicker provides an option to limit the user towards entering the valid date. With strict
mode, you can set only the valid date. If any invalid range is specified, the date range value
resets to previous value. This restriction can be availed by enabling strictMode property as
true.
razor
@Html.EJS().DateRangePicker("element").StrictMode(true).Placeholder("Select a Range").R
ender()
631
Globalization
Globalization is the combination of adapting the component to various languages by means of
parsing and formatting the date or number (Internationalization) and also by adding cultural
specific customizations and translating the text (Localization).
By default, DateRangePicker date format, week, and month names are specific to the American
English culture. It utilizes the Essential JavaScript 2 Internationalization package to parse
and format the date object based on the culture by using the official UNICODE CLDR JSON data. It
provides the loadCldr method to load culture specific CLDR JSON data.
To go with the different culture other than English , follow the below steps.
Install the CLDR-Data package by using the below command (it installs the CLDR JSON
data). To know more about CLDR-Data refer the CLDR-Data link.
Once the package installed, you can find the culture specific JSON data under the location
\node_modules\cldr-data .
Now use the loadCldr method to load the culture specific CLDR JSON data.
In ASP.NET MVC refer the culture files directly from \node_modules\cldr-data location. But in
ASP.NET Core, the static file contents are should present under wwwroot folder. For this,
manually copy the CLDR-Data from the node_modules folder and place inside the wwwroot
folder and refer from the \wwwroot\cldr-data location as like the below code examples
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../wwwroot/
cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
632
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node_mod
ules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
Before changing to a culture other than English , ensure that locale text for the concerned
culture is loaded through load method of L10n class.
633
The following example demonstrates the DateRangePicker in German culture.
razor
globalization.cs
@Html.EJS().DateRangePicker("daterangepicker").Locale("de").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
daterangepicker = document.getElementById('daterangepicker').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
'de': {
'daterangepicker': { placeholder: 'Wählen Sie einen Bereich',
today: 'heute' }
}
});
loadCultureFiles('de');
daterangepicker.locale = 'de';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
634
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DatePickerController: Controller
{
Right-To-Left
The DateRangePicker supports RTL (right-to-left) functionality for languages like Arabic and
Hebrew. To display the text in the right-to-left direction, use enableRtl property.
The code example demonstrates the DateRangePicker component in Arabic culture. It also
explains how to set localized text to the placeholder using L10n.load method.
razor
rtl.cs
@Html.EJS().DatePicker("datepicker").EnableRtl(true).Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
datepicker = document.getElementById('datepicker').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
'ar': {
'datepicker': { placeholder: ''اﺧﺘﺮ ﺗﺎرﻳﺨﺎ,
635
today: '} 'اﻟﯿﻮم
}
});
loadCultureFiles("ar");
datepicker.enableRtl = datepicker.locale === 'ar';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DatePickerController: Controller
{
636
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
637
Customization
The DateRangePicker is available for UI customization that can be achieved by using available
properties and events in the component.
The following example disables the weekends of every month by using renderDayCell event.
638
Accessibility
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. DateRangePicker
provides built-in compliance with WAI-ARIA specifications. WAI-ARIA support is achieved
through the attributes like aria-expanded , aria-disabled , and aria-activedescendant
applied as an input element.
To know about the accessibility of Calendar, refer to the Calendar's Accessibility section.
It helps people with disabilities by providing information about the widget for assistive technology
in the screen readers. DateRangePicker component contains grid role and grid cell for each day
cell.
Keyboard Interaction
Use the below keys to interact with the DateRangePicker. This component implements the
keyboard navigation support by following the WAI-ARIA practices.
Input Navigation
Before opening the popup, use the following list of keys to control the popup element.
Press To do this
Calendar Navigation
Use the following list of keys to navigate the currently focused Calendar after the popup has
opened.
Press To do this
Upper Arrow Focuses the same day of the previous week.
639
Left Arrow Focuses the day before.
Right Arrow Focuses the next day.
Home Focuses the first day of the month.
Shift + Page Up Focuses the same date for the previous year.
Shift + Page Down Focuses the same date for the next year.
Control +Home Focuses the first date of the current year.
640
How To
The following section explains how to customize various aspects of DateRangePicker.
razor
@Html.EJS().DateRangePicker("daterangepicker").Enabled("false").Render()
Using placeholder you can display a short hint in the input element.
razor
@Html.EJS().DateRangePicker("daterangepicker").Placeholder("Choose a range").Render()
Following is the list of classes that provides flexible way to customize the DateRangePicker
component.
641
e-start-label Applied to start label in a popup.
razor
@Html.EJS().DateRangePicker("daterangepicker").CssClass("customCSS").Placeholder("Selec
t Range").Render()
642
Overview
The Dialog is a window that displays information to the user, and used to get the user input.
Modal - The user should be working with Dialog before interacting with the parent
application.
Modeless - It allows to interact with parent application even the Dialog opened on the page.
Key Features
Modal: - Prevents the interaction to the parent application.
Buttons: - Provided the built-in support to render the buttons at Dialog footer.
Animation: - Provided built-in animation support on open & close the Dialog with
customization.
Localization: - Supports to localize the default close icon title text to different cultures.
643
Getting Started
This section briefly explains about how to include a simple Dialog in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include the license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP.NET MVC application to
use our components.
@Html.EJS().Dialog("dialog").Content("This is a dialog").Target("#container").Width("25
0px").Render()
Modal Dialog
A modal shows an overlay behind the Dialog. So, the user should interact the Dialog compulsory
before interacting with the remaining content in an application.
While the user clicks the overlay, the action can be handled through the overlayClick event. In
the below sample, the Dialog close action is performed while clicking on the overlay.
When the modal dialog is opened, the Dialog's target scrolling will be disabled. The
scrolling will be enabled again once close the Dialog.
644
razor
Modal.cs
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Modal Dialog").Render()
@Html.EJS().Dialog("dialog").IsModal(true).OverlayClick("onOverlayClick").Content("
This is a modal dialog").Target("#container").Render()
</div>
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
function onOverlayClick() {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.hide();
}
</script>
Enable header
The Dialog header can be enabled by adding the header content as text or HTML content
through the header property.
razor
EnableHeader.cs
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog").ShowCloseIcon(true).Content("This is
a dialog with header").Target("#container").Width("250px").Render()
645
</div>
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
</script>
Enable footer
The Dialog provides built-in support to render the buttons on the footer (for ex: ‘OK’ or ‘Cancel’
buttons). Each Dialog button allows the user to perform any action while clicking on it.
The primary button will be focused automatically on open the Dialog, and add the click event
to handle the actions
When the Dialog initialize with more than one primary buttons, the first primary button gets
focus on open the Dialog.
The below sample render with button and its click event.
razor
EnableFooter.cs
@section ControlsSection{
<div id="container">
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog").Content("This is a Dialog with bu
tton and primary button").Target("#container").Width("250px").Buttons(ViewBag.DialogBut
tons).Render()
</div>
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
646
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
Draggable
The Dialog supports to drag within its target container by grabbing the Dialog header, which
allows the user to reposition the Dialog dynamically.
The Dialog can be draggable only when the Dialog header is enabled and working only for
non-modal dialog. (isModal:false)
razor
Draggable.cs
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog").Content("This is a Dialog with drag e
nabled").AllowDragging(true).Target("#container").Width("250px").AllowDragging(true).Bu
ttons(ViewBag.DialogButtons)Render()
</div>
647
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
Positioning
The Dialog position can be set through the position property by providing X and Y coordinates.
The Dialog can be positioned inside the target container based on the given X and Y values.
razor
Positioning.cs
648
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog Positions").FooterTemplate("<span i
d='posvalue' style='float:left; padding-left:10px;font-weight: bold;'>Position: {X: 'le
ft', Y: 'top'}</span>").Content(ViewBag.content).Target("#container").Width("250px").Cl
oseOnEscape(false).Buttons(ViewBag.DialogButtons).Render()
</div>
}
<script>
function changePosition(event) {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.position = { X: event.currentTarget.value.split(" ")[0], Y: event.curren
tTarget.value.split(" ")[1] };
document.getElementById("posvalue").innerHTML = 'Position: {X: "' + event.curre
ntTarget.value.split(" ")[0] + '", Y: "' + event.currentTarget.value.split(" ")[1] + '"
}';
};
</script>
649
Template
In Dialog the template support is provided to the header and footer sections. So any text or
HTML content can be appending in these sections.
Header
The Dialog header content can be provided through the header property, and it will allow both
text and any HTML content as a string. Also in header, close button is provided as built-in
support, and this can be enabled through the showCloseIcon property.
Footer
The Dialog footer can be enabled by adding built-in buttons or providing any HTML string
through the footerTemplate .
The buttons and footerTemplate properties can't be used at the same time.
The below example demonstrates the usage of header and footer template in the Dialog
razor
Footer.cs
@section ControlsSection{
<script>
var validText;
function onLoad() {
document.getElementById('targetButton').onclick = function () {
650
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.show();
};
(document.getElementById('inVal')).onkeydown = function (e) {
if (e.keyCode === 13 && validText != "") {
updateTextValue();
}
};
(document.getElementById('sendButton')).onkeydown = function (e) {
if (e.keyCode === 13 && validText != "") {
updateTextValue();
}
};
document.getElementById('sendButton').onclick = function (e) {
updateTextValue();
}
}
function updateTextValue() {
var enteredVal = document.getElementById('inVal');
var dialogTextElement = document.getElementsByClassName('dialogText')[0];
var dialogTextWrap = document.getElementsByClassName('dialogContent')[0];
if (enteredVal.value !== '') {
dialogTextElement.innerHTML = enteredVal.value;
enteredVal.value = '';
}
}
</script>
651
Animation
The Dialog can be animated during the open and close actions. Also, user can customize
animation's delay , duration and effect .
delay The Dialog animation will start with the mentioned delay
duration Specifies the animation duration to complete with one animation cycle
Specifies the animation effects of Dialog open and close actions effect.
If the user sets ‘Fade’ effect, then the Dialog will open with ‘FadeIn’ effect and
close with ‘FadeOut’ effect
In the below sample, Zoom effect is enabled. So, The Dialog will open with ZoomIn and close
with ZoomOut effects.
razor
Animation.cs
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog Positions").AnimationSettings(new Dialo
gAnimationSettings { Effect = DialogEffect.Zoom, Duration = 400, Delay = 0 }).Content("
Dialog enabled with Zoom effect").Width("250px").Buttons(ViewBag.DialogButtons).Render(
)
</div>
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
652
public ActionResult Animation()
{
ViewBag.DialogButtons = new
{
isPrimary = true,
cssClass = "e-flat",
content = "OK"
};
ViewBag.DialogButton1 = new
{
content = "Cancel",
cssClass = "e-flat"
};
return View();
}
653
Localization
Localization library allows to localize the default text content of Dialog. In Dialog, The close
button's tooltip text alone will be localize based on culture.
close close
Loading translations
To load translation object in an application use load function of L10n class.
In the below sample, French culture is set to Dialog and change the close button's tooltip text.
razor
Localization.cs
@section ControlsSection{
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog Positions").FooterTemplate("<span id='p
osvalue' style='float:left; padding-left:10px;font-weight: bold;'>Position: {X: 'left',
Y: 'top'}</span>").Content(ViewBag.content).Target("#container").Width("250px").CloseO
nEscape(false).Buttons(ViewBag.DialogButtons).Render()
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
ej.base.L10n.load({
'fr-BE': {
'dialog': { 'close': "Fermer" }
}
});
}
</script>
654
{
return View();
}
655
Accessibility
The Dialog characterized with complete ARIA Accessibility support which helps to accessible by
on-screen readers and other assistive technology devices. This component designed with the
reference of the guidelines document given in WAI ARAI Accessibility Practices.
The Dialog component uses the Dialog role and following ARIA properties to its element based
on its state.
Property Functionalities
aria- It indicates the Dialog content description is notified to the user through
describedby assistive technologies.
aria-
The Dialog title is notified to the user through assistive technologies.
labelledby
aria-modal For modal dialog it's value is true and non-modal dialog its value is false
aria- Enable the draggable Dialog and starts dragging it is value is true and
grabbed stopping the drag its value is false
Keyboard interaction
Keyboard interaction of Dialog component has designed based on WAI-ARIA Practices
described for Dialog. User can use the following shortcut keys to interact with the Dialog.
Keyboard
Actions
shortcuts
When the Dialog button or any input (except text area) is in focus state, when
Enter pressing the Enter key, the click event associated with the primary button or
button will trigger. Enter key is not working when the Dialog content contains
any text area with initial focus
Ctrl + When the Dialog content contains text area and it is in focus state, and press
Enter the Ctrl + Enter key to call the click event function associated with primary
button
Shift + The Focus will be changed previous focusable element within the Dialog
Tab elements. When focusing a first focusable element in the Dialog, then press
the shift + tab key, it will change the focus to last focusable element
razor
Accessibility.cs
656
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Feedback").ShowCloseIcon(true).Target("#contai
ner").Width("400px").Buttons(ViewBag.DialogButtons).Height("300px").Content(@ViewBag.co
ntent).Render()
</div>
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
657
How to
Step 1:
Step 2:
Step 3:
razor
NestedDialog.cs
@section ControlsSection{
<div id='container'>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Outer Dialog").ShowCloseIcon(true).Target("#co
ntainer").Height("300px").CloseOnEscape(false).Width("400px").AnimationSettings(new Dia
logAnimationSettings { Effect = DialogEffect.None }).Render()
@Html.EJS().Dialog("innerDialog").ShowCloseIcon(true).Header("Inner Dialog").CloseO
nEscape(false).Content("This is a Nested Dialog").Target("#dialog").Height("150px").Ani
mationSettings(new DialogAnimationSettings { Effect=DialogEffect.None }).Width("250px")
.Render()
</div>
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
var innerDialog = document.getElementById("innerDialog").ej2_instances[0];
dialog.show();
innerDialog.show();
}
}
</script>
658
public ActionResult NestedDialog()
{
return View();
}
razor
Scrolling.cs
@section ControlsSection{
<div id='container'>
<div>
<b>JavaScript:</b><br />
JavaScript is a high-level, dynamic, untyped, and interpreted programming l
anguage. It has been standardized in the ECMAScript
language specification. Alongside HTML and CSS, it is one of the three esse
ntial technologies of World Wide Web
content production; the majority of websites employ it and it is supported
by all modern Web browsers without
plug-ins. JavaScript is prototype-based with first-class functions, making
it a multi-paradigm language, supporting
object - oriented , imperative, and functional programming styles.
<br /><br /><br />
<b>MVC:</b><br />
Model–view–controller (MVC) is a software architecture pattern which separa
tes the representation of information from the user's interaction with it. The model co
nsists of application data, business rules, logic, and functions. A view can be any out
put representation of data, such as a chart or a diagram. Multiple views of the same da
ta are possible, such as a bar chart for management and a tabular view for accountants.
The controller mediates input, converting it to commands for the model or view.The cen
tral ideas behind MVC are code reusability and in addition to dividing the application
into three kinds of components, the MVC design defines the interactions between them.
A controller can send commands to its associated view to change the view's
presentation of the model (e.g., by scrolling through a document). It can also send com
mands to the model to update the model's state (e.g., editing a document).
A model notifies its associated views and controllers when there has been a
change in its state. This notification allows the views to produce updated output, and
the controllers to change the available set of commands. A passive implementation of M
659
VC omits these notifications, because the application does not require them or the soft
ware platform does not support them.
A view requests from the model the information that it needs to generate an
output representation to the user.
</div>
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog").CloseOnEscape(false).Target("#con
tainer").Width("250px").Content(ViewBag.content).Render()
</div>
}
<script>
window.onload = function () {
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.cssClass = 'e-fixed';
}
}
</script>
AJAX Content
razor
header.cs
@section ControlsSection{
660
<div id="container">
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Content("This is a dialog without header.").Target(
"#container").Width("250px").Buttons(ViewBag.DialogButtons).Render()
</div>
<script>
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string cssClass { get; set; }
public string Click { get; set; }
// GET: RTL
public ActionResult Footer()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", isPrimary = true, cssClass = "e-flat", content = "OK" } });
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", content = "Cancel", cssClass = "e-flat" } });
661
ViewBag.DialogButtons = button;
return View();
}
return View();
}
}
razor
fullscreen.cs
@section ControlsSection{
<div id="container">
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Dialog").Content("This is a Dialog with fu
ll screen display.").Target("#container").Width("250px").Buttons(ViewBag.DialogButtons)
.Render()
</div>
<script>
document.getElementById('targetButton').onclick = function () {
var dialog = document.getElementById("dialog").ej2_instances[0];
dialog.show();
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
662
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string cssClass { get; set; }
public string Click { get; set; }
// GET: RTL
public ActionResult Footer()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", isPrimary = true, cssClass = "e-flat", content = "OK" } });
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", content = "Cancel", cssClass = "e-flat" } });
ViewBag.DialogButtons = button;
return View();
}
return View();
}
}
razor
position.cs
@section ControlsSection{
<div id="container">
@Html.EJS().Dialog("firstDialog").Header("Position-01").Content("The dialog is
positioned at {X: 160, Y: 14} co-ordinates.").Position(new Syncfusion.EJ2.Popups.Dialog
PositionData { X="160", Y ="12" }).Target("#container").Width("360px").Height("120px").
Render()
@Html.EJS().Dialog("secondDialog").Header("Position-02").Content("The dialog is
positioned at {X: 160, Y: 240} co-ordinates.").Position(new Syncfusion.EJ2.Popups.Dial
ogPositionData { X="160", Y ="240" }).Target("#container").Width("360px").Height("120px"
).Render()
</div>
663
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
return View();
}
}
razor
@section ControlsSection{
<div id="container">
@Html.EJS().Button("targetButton").Content("Open Dialog").Render()
@Html.EJS().Dialog("dialog").Header("Sign In").BeforeClose("validation").Conten
t("<div class='wrap'><div id='input-container'>
<div class='e-float-input'><input id='textvalue' type='text' required/><span class=
'e-float-line'></span>
<label class='e-float-text'>Username </label>
</div>
</div><div class='form-group'>
<div class='e-float-input'>
<input id='textvalue2' type='Password' required/>
<span class='e-float-line'></span>
<label class='e-float-text'>Password</label>
</div></div>").Target("#container").Width("300px").Buttons(ViewBag.DialogButton
s).Render()
</div>
<script>
664
// To get the all input fields and its container.
// Add 'e-input-focus' class to the input for achive ripple effect when focus on th
e input field.
// Add 'e-input-btn-ripple' class to the icon element for achive ripple effect when
click on the icon.
665
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
function validation(args) {
let text = document.getElementById('textvalue');
if (text.value ==="") {
args.cancel= true;
alert("Enter the username and password")
} else if (text.value.length < 4) {
args.cancel= true;
alert("Username must be minimum 4 characters");
} else {
args.cancel= false;
}
document.getElementById("textvalue").value = "";
document.getElementById("textvalue2").value = "";
}
</script>
razor
check.cs
@section ControlsSection{
<div id="container">
<div class="login-form">
<div class='wrap'>
<div id="heading">Sign in</div>
<div id="input-container">
<div class="e-float-input e-input-group">
<input id="textvalue" type="text" required/>
<span class="e-float-line"></span>
<label class="e-float-text">Username</label>
</div>
<div class="e-float-input e-input-group">
<input id="textvalue2" type="password" required/>
<span class="e-float-line"></span>
<label class="e-float-text">Password</label>
</div>
666
</div>
<div class="button-contain">
<button class="e-control e-btn e-info" id="targetButton" role="button"
e-ripple="true" >Log in</button>
</div>
</div>
</div>
@Html.EJS().Dialog("dialog").Header("Dialog").Content("This is a Dialog with fu
ll screen display.").Target("#container").Width("250px").Buttons(ViewBag.DialogButtons)
.Render()
</div>
<script>
// To get the all input fields and its container.
// Add 'e-input-focus' class to the input for achive ripple effect when focus on th
e input field.
// Add 'e-input-btn-ripple' class to the icon element for achive ripple effect when
click on the icon.
667
});
inputIcon[i].addEventListener('mouseup', function () {
let element = this;
setTimeout(function () {
element.classList.remove('e-input-btn-ripple');
}, 500);
});
}
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
function validation(args) {
let text = document.getElementById('textvalue');
if (text.value ==="") {
args.cancel= true;
alert("Enter the username and password")
} else if (text.value.length < 4) {
args.cancel= true;
alert("Username must be minimum 4 characters");
} else {
args.cancel= false;
}
document.getElementById("textvalue").value = "";
document.getElementById("textvalue2").value = "";
}
</script>
<style>
html,
body,
#container {
height: 100%;
overflow: hidden;
width: 100%;
}
#container {
visibility: hidden;
}
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
668
width: 30%;
}
.text-center {
text-align: center;
}
.e-footer-content {
padding: 20px 0 0;
width: 100%;
}
#heading {
color: #333;
font-weight: bold;
margin: 0 0 15px;
text-align: center;
font-size: 20px;
}
.wrap {
box-sizing: border-box;
margin: 0 auto;
width: 260px;
}
#dialog.e-dialog .e-footer-content {
padding: 0 18px 18px;
}
669
margin-left: 0;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string Click { get; set; }
// GET: RTL
public ActionResult Footer()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", isPrimary = true, content = "Dismiss" } });
ViewBag.DialogButtons = button;
return View();
}
return View();
}
}
razor
check.cs
670
@section ControlsSection{
<div id="target" class="col-lg-12 control-section">
@Html.EJS().Button("normalbtn").Content("Open").Render()
@Html.EJS().Dialog("dialog").AnimationSettings(new DialogAnimationSettings() {
Effect = DialogEffect.Zoom }).Header("User Details").Content("<form><div class='form-gr
oup'><label for='name'>Name:</label><input type='name' value='' class='form-control' id
='name'></div><div class='form-group'><label for='email'>Email Id:</label><input type='
email' value='[email protected]' class='form-control' id='email'></div><div class='fo
rm-group'><label for='contact'>Contact:</label><input type='contact' class='form-contro
l' id='contact'></div><div class='form-group'><label for='address'>Address:</label><tex
tarea class='form-control' rows='5' id='address'></textarea></div></form>").ShowCloseIc
on(true).Width("400px").Target("#target").Buttons(ViewBag.DialogButtons).Render()
@Html.EJS().Dialog("model_dialog").AnimationSettings(new DialogAnimationSetting
s() { Effect = DialogEffect.Zoom }).Header("User Details").Visible(false).ShowCloseIcon(
true).IsModal(true).Target("#target").Buttons(ViewBag.DialogButtons).Render()
</div>
}
@section PreScripts {
<script>
document.getElementById('normalbtn').onclick = function() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.show();
};
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
function returnClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
var dialogObj1 = document.getElementById('model_dialog').ej2_instances[0];
dialogObj1.show();
}
function submitButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
var dialogObj1 = document.getElementById('model_dialog').ej2_instances[0];
dialogObj1.content = this.getDynamicContent();
dialogObj1.show();
}
function getDynamicContent() {
var input = document.getElementById('dialog').querySelector('#name');
var email = document.getElementById('dialog').querySelector('#email');
671
var contact = document.getElementById('dialog').querySelector('#contact');
var address = document.getElementById('dialog').querySelector('#address');
var template = "<div class='row'><div class='col-xs-6 col-sm-6 col-lg-6 col
-md-6'><b>Confirm your details</b></div>" +
"</div><div class='row'><div class='col-xs-6 col-sm-6 col-lg-6 col-md-6
'><span id='name'> Name: </span>" +
"</div><div class='col-xs-6 col-sm-6 col-lg-6 col-md-6'><span id='nameV
alue'>"+ input.value + "</span> </div></div>" +
"<div class='row'><div class='col-xs-6 col-sm-6 col-lg-6 col-md-6'><spa
n id='email'> Email: </span>" +
"</div><div class='col-xs-6 col-sm-6 col-lg-6 col-md-6'><span id='email
Value'>" + email.value +
"</span></div></div><div class='row'><div class='col-xs-6 col-sm-6 col-
lg-6 col-md-6'>"+
"<span id='Contact'> Contact number: </span></div><div class='col-xs-6
col-sm-6 col-lg-6 col-md-6'>"+
"<span id='contactValue'>"+ contact.value +" </span></div></div><div cl
ass='row'><div class='col-xs-6 col-sm-6 col-lg-6 col-md-6'>"+
"<span id='Address'> Address: </span> </div><div class='col-xs-6 col-sm
-6 col-lg-6 col-md-6'><span id='AddressValue'>" + address.value +"</span></div></div>"
return template;
}
</script>
}
<style>
.control-section {
padding-left: 10px;
}
#target {
height: 100%;
min-height: 350px;
}
#model_dialog {
margin: 20px;
}
.row {
padding: 10px 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
672
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string Click { get; set; }
// GET: RTL
public ActionResult DefaultDialog()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
List<DialogDialogButton> buttons = new List<DialogDialogButton>();
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "submitButtonClick", isPrimary = true, content = "Submit" } });
ViewBag.DialogButtons = button;
buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonMode
l = new DefaultButtonModel() { content = "YES", isPrimary = true, iconCss = "e-icons e-
ok-icon" } });
buttons.Add(new DialogDialogButton() { Click = "returnClick", ButtonModel =
new DefaultButtonModel() { content = "NO", iconCss = "e-icons e-close-icon" } });
ViewBag.SubmitButtons = buttons;
return View();
}
return View();
}
}
razor
check.cs
@section ControlsSection{
<div id="target" class="col-lg-12 control-section">
@Html.EJS().Button("normalbtn").Content("Open").Render()
@Html.EJS().Dialog("dialog").AnimationSettings(new DialogAnimationSettings() {
673
Effect = DialogEffect.Zoom }).Header("File and Folder Rename").Content("<div class = 'd
ialog-content'><div class='msg-wrapper col-lg-12'><span class='e-icons close-icon col-
lg-2'></span> <span class='error-msg col-lg-10'>Can not rename 'pictures' because a fi
le or folder with that name already exists </span> </div><div class='error-detail col-l
g-8'><span>Specify a different name</span> </div></div>").ShowCloseIcon(true).Width("40
0px").Target("#target").Buttons(ViewBag.DialogButtons).Render()
</div>
}
@section PreScripts {
<script>
document.getElementById('normalbtn').onclick = function() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.show();
};
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
}
<style>
.control-section {
padding-left: 10px;
}
#target {
height: 100%;
min-height: 350px;
}
span.close-icon {
width: 24px;
height: 24px;
position: relative;
display: inline-block;
}
span.error-msg {
color: #66afe9;
display: inline-block;
position: relative;
}
.error-detail.col-lg-8 {
position: relative;
left: 45px;
margin: 20px 0px 21px;
}
.e-icons.close-icon.col-lg-2:before {
content: '\e7e9';
font-size: 26px;
674
color:#d9534f;
position: relative;
left: -12px;
}
.e-dialog .e-footer-content {
background-color: #f8f8f8;
}
.e-dialog.e-control .e-dlg-content {
padding: 15px 0px 0px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string Click { get; set; }
// GET: RTL
675
public ActionResult Footer()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
button.Add(new DialogDialogButton() { ButtonModel = new ButtonModel() { Cli
ck = "dlgButtonClick", isPrimary = true, content = "Close" } });
ViewBag.DialogButtons = button;
return View();
}
return View();
}
}
In the following sample, dialog is closed when clicking outside the dialog area using hide method.
razor
check.cs
@section ControlsSection{
<div id="target" class="col-lg-12 control-section">
@Html.EJS().Button("normalbtn").Content("Open").Render()
@Html.EJS().Dialog("dialog").AnimationSettings(new DialogAnimationSettings() {
Effect = DialogEffect.Zoom }).Header("Delete Multiple Items").Content("Are you sure you
want to permanently delete all of these items?").ShowCloseIcon(true).CloseOnEscape(true
).Width("500px").Target("#target").Buttons(ViewBag.DialogButtons).Render()
</div>
}
@section PreScripts {
<script>
document.getElementById('normalbtn').onclick = function () {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.show();
};
document.getElementById('target').onclick = function (args) {
if (args.target.tagName != "BUTTON") {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
};
function dlgButtonClick() {
676
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
}
<style>
.control-section {
padding-left: 10px;
}
#target {
height: 100%;
min-height: 350px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string Click { get; set; }
// GET: RTL
public ActionResult Footer()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonMod
el = new DefaultButtonModel() { content = "YES", isPrimary = true } });
buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonMode
l = new DefaultButtonModel() { content = "NO" } });
ViewBag.DialogButtons = buttons;
return View();
}
return View();
}
677
}
In the following sample, dialog footer buttons are customized with icons.
razor
check.cs
@section ControlsSection{
<div id="target" class="col-lg-12 control-section">
@Html.EJS().Button("normalbtn").Content("Open").Render()
@Html.EJS().Dialog("dialog").AnimationSettings(new DialogAnimationSettings() {
Effect = DialogEffect.Zoom }).Header("Delete Multiple Items").Content("Are you sure you
want to permanently delete all of these items?").ShowCloseIcon(true).CloseOnEscape(tru
e).Width("500px").Target("#target").Buttons(ViewBag.DialogButtons).Render()
</div>
}
@section PreScripts {
<script>
document.getElementById('normalbtn').onclick = function () {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.show();
};
function dlgButtonClick() {
var dialogObj = document.getElementById('dialog').ej2_instances[0];
dialogObj.hide();
}
</script>
}
<style>
.control-section {
padding-left: 10px;
}
#target {
height: 100%;
min-height: 350px;
}
.e-ok-icon::before {
content: '\e7ff';
}
678
.e-close-icon::before {
content: '\e825';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class DialogController : Controller
{
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
public string iconCss { get; set; }
// GET: RTL
public ActionResult Footer()
{
List<DialogDialogButton> buttons = new List<DialogDialogButton>() { };
buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonMode
l = new DefaultButtonModel() { content = "YES", isPrimary = true, iconCss = "e-icons e-
ok-icon" } });
buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonMode
l = new DefaultButtonModel() { content = "NO", iconCss = "e-icons e-close-icon" } });
ViewBag.DefaultButtons = buttons;
return View();
}
return View();
}
}
679
Overview
The Document Editor component is used to create, edit, view, and print Word documents in web
applications. All the user interactions and editing operations that run purely in the client-side
provides much faster editing experience to the users.
Key Features
Opens the native Syncfusion Document Text (*.sfdt) format documents in the client-side.
Saves the documents in the client-side as Syncfusion Document Text (*.sfdt) and Word
document (*.docx) .
Supports document elements like text, inline image, table, fields, bookmark, section, header,
and footer.
Supports the commonly used fields like hyperlink, page number, page count, and table of
contents.
Supports formats like text, paragraph, bullets and numbering, table, page settings, etc.
Provides support to create, edit, and apply paragraph and character styles.
Provides support to find and replace text within the document.
Supports all the common editing and formatting operations along with undo and redo.
Provides support to cut, copy, and paste rich text contents within the component. Also allows
pasting simple text to and from other applications.
Allows user interactions like zoom, scroll, select contents through touch, mouse, and
keyboard.
Provides intuitive UI options like context menu, dialogs, and navigation pane.
Localizes all the static text to any desired language.
Allows to create a lightweight Word viewer using module injection to view and prints Word
documents.
Provides a server-side helper assembly to open the Word documents like DOCX, DOC,
WordML, RTF, and Text, by converting it to SFDT file format.
680
Getting Started with ASP.NET MVC
Starting with v16.2.0.41, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
Prerequisites
To get start with ASP.NET MVC application, need to ensure the following software to be installed
on the machine.
Step 1: Create ASP.NET MVC Application with default template project in Visual Studio.
681
Step 2: Once your project created. We need to add Syncfusion EJ2 package into your
application by using NuGet Package Manager .
682
After installation complete, this will be included in the project. You can refer it from the Project
Assembly Reference.
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>
<system.web>
<compilation>
<assemblies>
<add assembly="Syncfusion.EJ2" Version=15.3400.0.27, Culture=neutral, PublicKey
Token=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>
Step 4: Add client side resource through CDN or local package in the layout page
_Layout.cshtml .
683
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
684
@* Syncfusion Essential JS2 Styles *@
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css" />
@Html.EJS().ScriptManager()
Step 6: Add the below code to your Index.cshtml view page which is present under Views/Home
folder, to initialize the document editor.
Module injection
To create DocumentEditor with additional features, inject the required modules. The following
modules are used to extend DocumentEditor�s basic functionality.
685
PageSetupDialog - Inject this module to modify page set up via page set up dialog.
ListDialog - Inject this module to modify list format option via list dialog feature.
StyleDialog - Inject this module to create or modify style via style dialog feature.
StylesDialog - Inject this module to create or modify styles via style dialog feature.
BulletsAndNumberingDialog - Inject this module to apply or modify list paragraph style via
bullet and numbering dialog feature.
TablePropertiesDialog - Inject this module to modify table, row and cell properties via
Table Properties dialog feature.
BordersAndShadingDialog - Inject this module to modify borders and shading of table or cell
via Borders And Shading Dialog.
TableOptionsDialog - Inject this module to modify table margin and spacing value via Table
Options dialog
CellOptionsDialog - Inject this module to modify cell margin values via Cell Options dialog .
BookmarkDialog - Inject this module to add, navigate or delete bookmarks via Bookmark
dialog .
These modules should be injected into the DocumentEditor using the DocumentEditor.Inject
method.
Enable Print
The print feature enables users to print the document. It can be enabled by setting the
enablePrint property to true. Inject the Print module as follows. If the Print module is not injected,
the Print will not be enabled in the documenteditor.
Enable Selection
The Selection feature enables users to select the content in document. It can be enabled by
setting the enableSelection property to true. Inject the Selection module as follows. If the
Selection module is not injected, the Selection will not be enabled in the documenteditor.
Enable Search
The search feature enables users to search the content in document. It can be enabled by setting
the enableSearch property to true and also enableOptionsPane property to true. Inject the
Search module as follows. If the Search module is not injected, the search functionality will not
be enabled in the documenteditor.
Enable Editor
686
The Editing feature enables users to edit the content in document. It can be enabled by setting
the isReadOnly property to true and also enableEditor property to true. Inject the Editor module
as follows. If the Editor module is not injected, the editing feature will not be enabled in the
documenteditor.
687
Overview
DropDownButton component is used to toggle contextual overlays for displaying list of action
items. It can contain both text and images.
Key Features
Icons
Popup Items
Accessibility
How To
688
Getting Started
This section briefly explains about how to include a simple DropDownButton in your ASP.NET
MVC application. You can refer ASP.NET MVC Getting Started documentation page for
introduction part of the system requirements and configure the common specifications.
razor
@Html.EJS().DropDownButton("element").Content("Edit").Items((IEnumerable<object>)ViewBa
g.items).Render()
ViewBag.items variable is used for bounding the items property in view page.
Bind dataSource
Populate the action items in SplitButton by using the items property. Here, the JSON values
are passed to the DropDownButton component are generated in default.cs and assigned to
ViewBag variable.
689
Run the application
After successful compilation of your application, simply press F5 to run the application.
razor
default.cs
@Html.EJS().DropDownButton("element").Content("Edit").Items((IEnumerable<object>)ViewBa
g.items).Render()
690
Icons and Styles
DropDownButton icons
DropDownButton can have an icon to provide the visual representation of the action. To place
the icon on a DropDownButton, set the iconCss property to e-icons with the required icon
CSS. By default, the icon is positioned to the left side of the DropDownButton. You can
customize the icon's position using the iconPosition property.
In the following example, the DropDownButton with default iconPosition and iconPosition as
Top is showcased:
razor
iconbutton.cs
@section ControlsSection{
@Html.EJS().DropDownButton("left-icon").Content("Message").Items((IEnumerable<objec
t>)ViewBag.items).IconCss("e-icons e-message").Render()
@Html.EJS().DropDownButton("top-icon").Content("Message").Items((IEnumerable<object
>)ViewBag.items).IconCss("e-icons e-message").IconPosition("Top").Render()
}
<style>
.e-message::before {
content: '\e80f';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
691
public IActionResult IconButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Edit"
});
items.Add(new
{
text = "Delete"
});
items.Add(new
{
text = "Mark as Read"
});
items.Add(new
{
text = "Like Message"
});
ViewBag.items = items;
return View();
}
}
}
The Essential JS 2 provides a set of icons that can be loaded by applying e-icons class
name to the element. You can also use third party icons on the DropDownButton using the
iconCss property.
Vertical button
Vertical button in DropDownButton can be achieved by adding e-vertical class using
cssClass property.
razor
verticalbutton.cs
@section ControlsSection{
@Html.EJS().DropDownButton("vertical-btn").Content("Message").Items((IEnumerable<ob
ject>)ViewBag.items).IconCss("e-icons e-message").Render()
}
<style>
.e-message::before {
content: '\e80f';
}
692
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult VerticalButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Edit"
});
items.Add(new
{
text = "Delete"
});
items.Add(new
{
text = "Mark as Read"
});
items.Add(new
{
text = "Like Message"
});
ViewBag.items = items;
return View();
}
}
}
693
Popup items
Icons
The popup action item have an icon or image to provide visual representation of the action. To
place the icon on a popup item, set the iconCss property to e-icons with the required icon
CSS. By default, the icon is positioned to the left side of the popup action item.
In the following sample, the icons for edit, delete, mark as read and like message menu items are
added using the iconCss property.
razor
popupicons.cs
@section ControlsSection{
@Html.EJS().DropDownButton("left-icon").Content("Message").Items((IEnumerable<object
>)ViewBag.items).IconCss("e-icons e-message").Render()
<style>
.e-message::before {
content: '\e80f';
}
.e-edit::before {
content: '\e7ae';
}
.e-delete::before {
content: '\e835';
}
.e-read::before {
content: '\e7e0';
}
.e-like::before {
content: '\e81a';
}
button {
margin: 25px 5px 20px 20px;
}
694
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult PopupIcons()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Edit",
iconCss = 'e-icons e-edit'
});
items.Add(new
{
text = "Delete",
iconCss = 'e-icons e-delete'
});
items.Add(new
{
text = "Mark as Read",
iconCss = 'e-icons e-read'
});
items.Add(new
{
text = "Like Message",
iconCss = 'e-icons e-like'
});
ViewBag.items = items;
return View();
}
}
}
Navigations
Actions in DropDownButton can be used to navigate to the other web page when action item is
clicked. This can be achieved by Popup items can be customized using the beforeItemRender
event. The item render event providing link to the action item using url property.
695
In the following sample, navigation URL for Flipkart, Amazon, and Snapdeal action items are
added using the url property:
razor
navigation.cs
@section ControlsSection{
@Html.EJS().DropDownButton("navigation").Content("Shop By").Items((IEnumerable<objec
t>)ViewBag.items).IconCss("e-icons e-link").BeforeItemRender("beforeItemRender").Render
()
<script>
function beforeItemRender(args) {
args.element.getElementsByTagName('a')[0].setAttribute('target', '_blank');
}
</script>
<style>
.e-link::before {
content: '\e7e8';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult Navigation()
{
List<object> items = new List<object>();
696
items.Add(new
{
text = 'Flipkart',
iconCss = 'e-icons e-link',
url = 'https://www.google.co.in/search?q=flipkart'
});
items.Add(new
{
text = 'Amazon',
iconCss = 'e-icons e-link',
url = 'https://www.google.co.in/search?q=amazon'
});
items.Add(new
{
text = 'Snapdeal',
iconCss = 'e-icons e-link',
url = 'https://www.google.co.in/search?q=snapdeal'
});
ViewBag.items = items;
return View();
}
}
}
Template
Item templating
Popup items can be customized using the beforeItemRender event. The item render event
triggers while rendering each popup action item. The event argument will be used to identify the
action item and customize based on the requirement.
In the following example, the icons in each li items is right aligned by appending span element in
li rendering:
razor
itemtemplate.cs
@section ControlsSection{
@Html.EJS().DropDownButton("item-template").Items((IEnumerable<object>)ViewBag.items
).IconCss("e-icons e-align").BeforeItemRender("beforeItemRender").Render()
<script>
697
function beforeItemRender(args) {
var alignSpan = createElement('span');
var text = args.item.text;
args.element.appendChild(alignSpan);
alignSpan.setAttribute('class','alignSpan');
alignSpan.classList.add('e-icons');
(text === 'Align Left') ? alignSpan.classList.add('e-left') : (text === 'Align
Center') ? alignSpan.classList.add('e-center') :
alignSpan.classList.add('e-right');
}
</script>
<style>
.e-align::before {
content: '\e756';
}
.e-left::before {
content: '\e75e';
}
.e-center::before {
content: "\e749";
}
.e-right::before {
content: '\e713';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
698
{
public IActionResult ItemTemplate()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Align Left"
});
items.Add(new
{
text = "Align Center"
});
items.Add(new
{
text = "Align Right"
});
ViewBag.items = items;
}
}
}
Popup Templating
The whole popup can be customized as per the requirement. In the following example, the popup
can be customized by handling it in target property.
razor
popuptemplate.cs
@section ControlsSection{
<div id="target" style='border: 1px solid black;'>
<table>
<caption style='height: 18px; background-color: #e0e0e0;'><b>Insert Table</
b></caption>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
699
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
<tr class='e-row'>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
<td class='e-data'></td>
</tr>
</table>
</div>
@Html.EJS().DropDownButton("element").Content("Table").Target("#target").IconCss("e
-icons e-table").Render()
<style>
.shortcut {
float: right;
margin-top: 9px;
700
padding-left: 30px;
height: 100px;
}
.e-data {
border: 1px solid rgba(0, 0, 0, 0.87);
padding: 8px;
}
.e-border {
border: black;
border-radius: 2px;
background-color: #fafafa;
}
.e-table::before {
content: '\e705';
}
.e-row {
padding-left: 3px;
padding-right: 3px;
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult PopupTemplate()
{
return View();
}
}
}
701
Accessibility
ARIA attributes
The web accessibility makes web content and web applications more accessible for people with
disabilities. Mostly it helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. DropDownButton
provides built-in compliance with WAI-ARIA specifications. WAI-ARIA support is achieved
through the attributes like aria-expanded , aria-owns and aria-haspopup applied for action
item in DropDownButton. It helps by providing information about the widget for assistive
technology in the screen readers. DropDownButton component contains the menu role and
menuItem role.
Properties Functionality
aria-
Indicates the availability and type of interactive dropdown popup element.
haspopup
aria- Indicates whether the current state of the dropdown popup can be expanded
expanded or collapsed.
Keyboard interaction
Keyboard
Actions
shortcuts
Enter Opens the popup, or activates the highlighted item and closes the
popup.
Space Opens the popup.
702
razor
accessibility.cs
@section ControlsSection{
@Html.EJS().DropDownButton("element").Content("Edit").Items((IEnumerable<object>)Vie
wBag.items).IconCss("e-icons e-edit").Render()
<style>
/* csslint ignore:start */
@font-face {
font-family: 'e-dropdown-btn';
src:
url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMjjNRVMAAAEo
AAAAVmNtYXDicOK6AAABjAAAADhnbHlmGcEPFQAAAcwAAAMwaGVhZA69CA8AAADQAAAANmhoZWEH9AQEAAAArAA
AACRobXR4DAAAAAAAAYAAAAAMbG9jYQDYAZgAAAHEAAAACG1heHABEgDAAAABCAAAACBuYW1lxY1d1QAABPwAAA
KFcG9zdPJwcMoAAAeEAAAASAABAAAEAAAAAFwEAAAAAAADlwABAAAAAAAAAAAAAAAAAAAAAwABAAAAAQAAgmhm8
l8PPPUACwQAAAAAANYD4Y8AAAAA1gPhjwAAAAADlwP0AAAACAACAAAAAAAAAAEAAAADALQABQAAAAAAAgAAAAoA
CgAAAP8AAAAAAAAAAQQAAZAABQAAAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAUGZFZABA4mDiYQQAAAAAXAQAAAAAAAABAAAAAAAABAAAAAQAAAAEAAAAAAAAAgAAAAMAAAAUAAMAAQAAAB
QABAAkAAAABAAEAAEAAOJh//8AAOJg//8AAAABAAQAAAABAAIAAAAAANgBmAAFAAAAAAOXA/QABAAlAC0ATgCzA
AABIScHJzcVHwc/By8HDwYBFSE1MxEhESUHFQ8GLwc/Bx8GJysBDw4RHw4zITM/DhEvDisBLw4rAQ8NAUQBd1xA
fr0BAwQGBwgICgkJCAcGBAMBAQMEBgcICQkKCAgHBgQD/qYB1l79jQFoAQMEBgcHCQkJCQgGBgQDAQEDBAYGCAk
JCQkHBwYEA6y9CgkICQgHBwcGBQQEAwMBAQEBAwMDBQUGBwcHCAkICQoCeAoJCAkIBwcHBgUEBAMDAQEBAQMDAw
UFBgcHBwgJCAkKvQQEBgUHBwcICQkJCgoKCwsLCwoKCgkJCQgHBwcFBgQBBYVRuh0FBQkIBwUFAgEBAgUFBwgJC
gkJCAcGBAMBAQMEBgcICQEifX39LwLRMwQFCAgHBQUCAQECBQUHCAgJCQkIBwUEAwEBAwQFBwgJIgICAwQFBQYG
BwgICAkJCf0pCQkJCAgIBwYGBQUEAwICAgIDBAUFBgYHCAgICQkJAtcJCQkICAgHBgYFBQQDAgIKCQkICAgHBgY
FBAQDAgICAgMEBAUGBgcICAgJCQAFAAAAAAOXA/QABwAPABcAOACdAAABHwIjPwIDMzczFzMDIycVITUzESERJQ
cVDwYvBz8HHwYnKwEPDhEfDjMhMz8OES8OKwEvDisBDw0B/wQKK3MmBQ6dMyeHKDWCO90B1l79jQFoAQMEBgcHC
QkJCQgGBgQDAQEDBAYGCAkJCQkHBwYEA6y9CgkICQgHBwcGBQQEAwMBAQEBAwMDBQUGBwcHCAkICQoCeAoJCAkI
BwcHBgUEBAMDAQEBAQMDAwUFBgcHBwgJCAkKvQQEBgUHBwcICQkJCgoKCwsLCwoKCgkJCQgHBwcFBgQCFREigG4
SM/6wd3cBe/t9ff0vAtEzBAUICAcFBQIBAQIFBQcICAkJCQgHBQQDAQEDBAUHCAkiAgIDBAUFBgYHCAgICQkJ/S
kJCQkICAgHBgYFBQQDAgICAgMEBQUGBgcICAgJCQkC1wkJCQgICAcGBgUFBAMCAgoJCQgICAcGBgUEBAMCAgICA
wQEBQYGBwgICAkJAAAAABIA3gABAAAAAAAAAAEAAAABAAAAAAABAA8AAQABAAAAAAACAAcAEAABAAAAAAADAA8A
FwABAAAAAAAEAA8AJgABAAAAAAAFAAsANQABAAAAAAAGAA8AQAABAAAAAAAKACwATwABAAAAAAALABIAewADAAE
ECQAAAAIAjQADAAEECQABAB4AjwADAAEECQACAA4ArQADAAEECQADAB4AuwADAAEECQAEAB4A2QADAAEECQAFAB
YA9wADAAEECQAGAB4BDQADAAEECQAKAFgBKwADAAEECQALACQBgyBDb250ZXh0TWVudSAoMilSZWd1bGFyQ29ud
GV4dE1lbnUgKDIpQ29udGV4dE1lbnUgKDIpVmVyc2lvbiAxLjBDb250ZXh0TWVudSAoMilGb250IGdlbmVyYXRl
ZCB1c2luZyBTeW5jZnVzaW9uIE1ldHJvIFN0dWRpb3d3dy5zeW5jZnVzaW9uLmNvbQAgAEMAbwBuAHQAZQB4AHQ
ATQBlAG4AdQAgACgAMgApAFIAZQBnAHUAbABhAHIAQwBvAG4AdABlAHgAdABNAGUAbgB1ACAAKAAyACkAQwBvAG
4AdABlAHgAdABNAGUAbgB1ACAAKAAyACkAVgBlAHIAcwBpAG8AbgAgADEALgAwAEMAbwBuAHQAZQB4AHQATQBlA
G4AdQAgACgAMgApAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAHUAcwBpAG4AZwAgAFMAeQBuAGMAZgB1
AHMAaQBvAG4AIABNAGUAdAByAG8AIABTAHQAdQBkAGkAbwB3AHcAdwAuAHMAeQBuAGMAZgB1AHMAaQBvAG4ALgB
jAG8AbQAAAAACAAAAAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMBAgEDAQQAD01UX1Bhc3RlU3BlY2lhbA
xNVF9QYXN0ZVRleHQAAA==) format('truetype');
703
font-weight: normal;
font-style: normal;
}
/* csslint ignore:stop */
.e-ddb-icons {
font-family: 'e-dropdown-btn';
font-style: normal;
font-variant: normal;
font-weight: normal;
line-height: 1;
text-transform: none;
}
.e-edit::before {
content: '\e80a';
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
.e-text::before {
content: '\e261';
}
.e-special::before {
content: '\e260';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
704
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult Accessibility()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut",
iconCss = "e-icons e-cut"
});
items.Add(new
{
text = "Copy",
iconCss = "e-icons e-copy"
});
items.Add(new
{
text = "Paste",
iconCss = "e-icons e-paste"
});
items.Add(new
{
separator = "True"
});
items.Add(new
{
text = "Paste Text",
iconCss = "e-ddb-icons e-text"
});
items.Add(new
{
text = "Paste Special",
iconCss = "e-ddb-icons e-special"
});
ViewBag.items = items;
return View();
}
}
}
705
How To
The following section explains how to customize various aspects of the DropDownButton.
razor
hidearrow.cs
@section ControlsSection{
@Html.EJS().DropDownButton("hide-arrow").Content("Edit").Items((IEnumerable<object>)
ViewBag.items).CssClass("e-caret-hide").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult HideArrow()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
706
});
ViewBag.items = items;
return View();
}
}
}
In the following example, the up arrow is updated on popup close and down arrow is updated on
popup open using beforeOpen and beforeClose event by adding and removing e-caret-up
class.
razor
updown.cs
@section ControlsSection{
@Html.EJS().DropDownButton("ddbtn").Content("Clipboard").Items((IEnumerable<object>)
ViewBag.items)
.BeforeOpen("beforeOpen").BeforeClose("beforeClose").Render()
<style>
.e-caret-up .e-caret {
transform: rotate(180deg);
}
button {
margin: 25px 5px 20px 20px;
}
</style>
<script>
// Removing 'e-caret-up' class.
function beforeClose (args) {
this.cssClass = '';
}
// Adding 'e-caret-up' class.
function beforeOpen (args) {
this.cssClass = 'e-caret-up';
}
</script>
707
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult HideArrow()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
In the following example, ListView element is given as target to DropDownButton and header
can be achieved by groupBy property.
razor
listview.cs
@using Syncfusion.EJ2.Lists;
@section ControlsSection{
<div>
708
@Html.EJS().ListView("listview").Enable(true).DataSource((IEnumerable<object>)ViewBa
g.listdata).ShowCheckBox(true).Fields(new ListViewFieldSettings { GroupBy = "category",
Text = "text" }).Render()
@Html.EJS().DropDownButton("ddbtn").CssClass("e-caret-hide").IconCss("e-icons e-down
").target("#listview").Render()
</div>
}
<style>
.e-down::before {
content: '\e7d6';
}
#listview {
display: block;
max-width: 600px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
button {
margin: 30% 5px 20px 30%;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Print",
id = "data1",
category = "Customize Quick Access Toolbar"
});
listdata.Add(new
709
{
text = "Save As",
id = "data2",
category = "Customize Quick Access Toolbar"
});
listdata.Add(new
{
text = "Update Folder",
id = "data3",
category = "Customize Quick Access Toolbar"
});
listdata.Add(new
{
text = "Reply",
id = "data4",
category = "Customize Quick Access Toolbar"
});
ViewBag.listdata = listdata;
return View();
}
}
}
In the following example, the top position of the popup element is changed in open event.
razor
position.cs
@section ControlsSection{
@Html.EJS().DropDownButton("ddbtn").Content("Clipboard").Items((IEnumerable<object>)
ViewBag.items).CssClass("e-caret-up")
.Open("onOpen").Render()
<style>
.e-caret-up .e-caret::before {
content: '\e918';
}
button {
margin: 30% 5px 20px 30%;
710
}
</style>
<script>
function onOpen(args){
args.element.parentElement.style.top = document.getElementById('ddbtn').ej2_ins
tances[0].element.getBoundingClientRect().top - args.element.parentElement.offsetHeight
+'px';
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Buttons;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
711
In the following example, Dialog will open while selecting Other Folder... item.
razor
dialog.cs
@section ControlsSection{
<div>
@Html.EJS().Dialog("dialog").Header("Move Items").Content("Move Items To 'Web Team'"
).Width("250px").Visible(false).Position(obj => obj.X("100").Y("100")).Buttons(ViewBag.
button).Render()
@Html.EJS().DropDownButton("ddbtn").Content("Move").Items((IEnumerable<object>)ViewB
ag.items).CssClass("e-vertical")
.IconCss("e-icons e-folder").IconPosition("Top").Select("onSelect").Render()
</div>
}
<style>
.e-folder::before {
content: '\e883';
}
button {
margin: 25px 5px 20px 20px;
}
</style>
<script>
function onSelect(args){
if (args.item.text === 'Other Folder...') {
document.getElementById('dialog').ej2_instances[0].show();
}
}
function btnClick () {
document.getElementById('dialog').ej2_instances[0].hide();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Buttons;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
712
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Archive"
});
items.Add(new
{
text = "Inbox"
});
items.Add(new
{
text = "HR Portal"
});
items.Add(new
{
separator = true
});
items.Add(new
{
text = "Other Folder..."
});
items.Add(new
{
text = "Copy to Folder"
});
ViewBag.button = new
{
content="OK", cssClass="e-flat", isPrimary = true
};
ViewBag.items = items;
return View();
}
}
}
713
razor
underline.cs
@section ControlsSection{
@Html.EJS().DropDownButton("ddbtn").Content("Clipboard").Items((IEnumerable<object>)
ViewBag.items).BeforeItemRender("itemRender").Render()
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
<script>
function itemRender(args){
if (args.item.text === 'Copy') {
//To underline a particular text.
args.element.innerHTML = '<u>C</u>opy';
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Buttons;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
714
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
The following UI can be achieved by setting iconPosition as Top , width as 85px and size of
the font icon as 40px by adding e-custom class.
razor
underline.cs
@section ControlsSection{
@Html.EJS().DropDownButton("ddbtn").Content("Clipboard").Items((IEnumerable<object>)
ViewBag.items).BeforeItemRender("itemRender").Render()
<style>
button {
margin: 25px 5px 20px 20px;
}
</style>
<script>
function itemRender(args){
if (args.item.text === 'Copy') {
//To underline a particular text.
args.element.innerHTML = '<u>C</u>opy';
}
}
</script>
using System;
using System.Collections.Generic;
715
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Buttons;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
In the following example, e-round-corner class is defined with 5px border-radius property
and added that class to button element using cssClass property.
razor
round.cs
@section ControlsSection{
@Html.EJS().DropDownButton("ddbtn").Content("Clipboard").Items((IEnumerable<object>)
ViewBag.items).CssClass("e-round-corner").Render()
716
<style>
.e-round-corner {
border-radius: 5px;
}
button {
margin: 25px 5px 20px 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Buttons;
namespace EJ2CoreSampleBrowser.Controllers.Button
{
public partial class ButtonController : Controller
{
public IActionResult DropDownButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
Disable a DropDownButton
DropdownButton component can be enabled/disabled by giving disabled property. To disable
DropdownButton component, the disabled property can be set as true .
717
razor
disabled.cs
@section ControlsSection{
@Html.EJS().DropDownButton("disabled").Content("Message").Items((IEnumerable<object
>)ViewBag.items).IconCss("e-icons e-message").Disabled(true).Render()
<styles>
.e-message::before {
content: '\e80f';
}
button {
margin: 25px 5px 20px 20px;
}
</styles>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult DEisabled()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Edit"
});
items.Add(new
{
text = "Delete"
});
items.Add(new
{
text = "Mark as Read"
});
718
items.Add(new
{
text = "Like Message"
});
ViewBag.items = items;
return View();
}
}
}
razor
rtl.cs
@section ControlsSection{
@Html.EJS().DropDownButton("rtl").Content("Message").Items("ViewBag.items").IconCss
("e-icons e-message").EnableRtl(true).Render()
<styles>
.e-message::before {
content: '\e80f';
}
button {
margin: 25px 5px 20px 20px;
}
</styles>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
719
namespace WebApplication1.Controllers
{
public class DropDownButtonController : Controller
{
public IActionResult Rtl()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Edit"
});
items.Add(new
{
text = "Delete"
});
items.Add(new
{
text = "Mark as Read"
});
items.Add(new
{
text = "Like Message"
});
ViewBag.items = items;
return View();
}
}
}
720
Overview
The Grid component is used to display and manipulate tabular data with configuration options to
control the way the data is presented. It can pull data from data sources such as array of
JavaScript objects, OData web services , or DataManager and binding data fields to columns. It
also displays the column header to identify the field with support for grouped records.
The most important features available in the grid component are paging, sorting, filtering,
searching, and grouping.
Key Features
Data sources: Binds the grid component with an array of JavaScript objects or
DataManager.
Sorting and grouping: Supports n level of sorting and grouping.
Filtering: Offers filter bar in each column to filter data.
Paging: Allows easy switching between pages using the pager bar.
Editing:provides the options for create, read, update, and delete operations.
Columns:The column definitions are used as the dataSource schema in the Grid. This plays
a vital role in rendering column values in the required format.
Reordering: Allows drag and drop of any column anywhere in the grid’s column header
row, thus allowing repositioning of columns.
Column Chooser:The column chooser provides a list of column names paired with
check boxes that allow the visibility to be toggled on the fly.
Resizing:Resizing allows changing column width on the fly by simply dragging the right
corner of the column header.
Freeze:Columns and rows can be frozen to allow scrolling and comparing cell values.
Cell Spanning:Grid cells can be spanned based on the preferred criteria.
Foreign data source:This provides the option to show values from external or lookup
data sources in a column based on foreign key/value mapping.
Cell Styling:Grid cell styles can be customized either by using CSS or
programmatically.
Selection:Rows or cells can be selected in the grid. One or more rows or cells can also be
selected by holding Ctrl or Command, or programmatically.
Templates - Templates can be used to create custom user experiences in the grid.
Aggregation - Provides the option to easily visualized the Aggregates for column values.
Context menu -The context menu provides a list of actions to be performed in the grid. It
appears when a cell, header, or the pager is right-clicked.
Clipboard - Selected rows and cells can be copied from the grid
Export - Provides the options to Export the grid data to Excel, PDF, and CSV formats.
RTL support: Provides right-to-left mode that aligns the grid content from right to left.
721
Localization: Provides an inherent support to localize the UI.
722
Getting Started with ASP.NET MVC
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET Core application to use
our components.
Prerequisites
To get start with ASP.NET MVC application, need to ensure the following software to be installed
on the machine.
Step 1: Create ASP.NET MVC Application with default template project in Visual Studio.
723
Step 2: Once your project created. We need to add Syncfusion EJ2 package into your
application by using NuGet Package Manager .
724
After installation complete, this will be included in the project. You can refer it from the Project
Assembly Reference.
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>
<system.web>
<compilation>
<assemblies>
<add assembly="Syncfusion.EJ2" Version=15.3400.0.27, Culture=neutral, PublicKey
Token=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>
Step 4: Add client side resource through CDN or local package in the layout page
_Layout.cshtml .
725
ue").YName("yValue1").Marker(ViewBag.marker).DataSource(ViewBag.dataSource).Name("Engla
nd").Add();
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
726
orGridLines(ViewBag.majorGridLines).MajorGridLines(ViewBag.majorGridLines).IntervalType
(Syncfusion.EJ2.Charts.IntervalType.Years).EdgeLabelPlacement(Syncfusion.EJ2.Charts.Edg
eLabelPlacement.Shift).LabelFormat("y")
).PrimaryYAxis(py => py.LabelFormat("{value}%").RangePadding(Syncfusion.EJ2.Char
ts.ChartRangePadding.None).MajorTickLines(ViewBag.majorTickLines).MinorTickLines(ViewBa
g.minorTickLines).LineStyle(ViewBag.lineStyle).Interval(20).Minimum(0).Maximum(100)
).Title("Inflation - Consumer Price").Tooltip(tt => tt.Enable(true)).Load("load"
).Render()
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
@Html.EJS().ScriptManager()
Step 6: Add the below code to your Index.cshtml view page which is present under Views/Home
folder, to initialize the grid.
razor
grid.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Column
727
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).Render()
Enable paging
The paging feature enables users to view the grid record in a paged view. It can be enabled by
setting the AllowPaging property to true. Pager can be customized using the PageSettings
property.
razor
page.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().Render()
728
Enable sorting
The sorting feature enables you to order the records. It can be enabled by setting the
AllowSorting property as true. Sorting feature can be customized using the SortSettings
property.
razor
sorting.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns
(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().AllowSorting().Render()
Enable filtering
The filtering feature enables you to view reduced amount of records based on filter criteria. It can
be enabled by setting the AllowFiltering property as true. Filtering feature can be customized
using the FilterSettings property.
razor
filtering.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
729
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().AllowSorting().AllowFiltering().Render()
Enable grouping
The grouping feature enables users to view the grid record in a grouped view. It can be enabled
by setting the AllowGrouping property to true. Grouping feature can be customized using the
GroupSettings property.
razor
grouping.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().AllowSorting().AllowFiltering().AllowGrouping().Render()
730
731
Data Binding
The Grid uses DataManager , which supports both RESTful JSON data services binding and local
JavaScript object array binding. The DataSource property can be assigned either with the
instance of DataManager or JavaScript object array collection. It supports two kinds of data
binding method:
List binding
Remote data
List binding
To bind list binding to the grid, you can assign a JavaScript object array to the DataSource
property. The list data source can also be provided as an instance of the DataManager .
razor
local.cs
@Html.EJS().Grid("LocalData").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlig
n.Right).Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.Text
Align.Right).Width("130").Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
.Right).Width("120").Format("C2").Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").Add(
);
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().Render()
732
Remote data
To bind remote data to grid component, assign service data as an instance of DataManager to
the DataSource property. To interact with remote data source, provide the endpoint url .
razor
remotedata.cs
@Html.EJS().Grid("RemoteData").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").Cro
ssDomain(true).Adaptor("ODataV4Adaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging().Render()
razor
odata.cs
@Html.EJS().Grid("OData").DataSource(dataManger =>
733
{
dataManger.Url("http://js.syncfusion.com/ejServices/Wcf/Northwind.svc/Orders/?$top=
7").CrossDomain(true).Adaptor("ODataAdaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).Render()
razor
odataV4.cs
@Html.EJS().Grid("OdataV4").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").
CrossDomain(true).Adaptor("ODataV4Adaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(
734
Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syn
cfusion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging().Render()
return View();
}
Web API
You can use WebApiAdaptor to bind grid with Web API created using OData endpoint.
razor
webapi.cs
@Html.EJS().Grid("WebApi").DataSource(dataManger =>
{
dataManger.Url("/api/Orders").CrossDomain(true).Adaptor("WebApiAdaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).Render()
return View();
}
735
The response object should contain properties, Items and Count , whose values are a
collection of entities and total count of the entities, respectively.
{
Items: [{..}, {..}, {..}, ...],
Count: 830
}
WebMethod Adaptor
The WebMethodAdaptor is used to bind data source from remote services and code behind
methods. It can be enabled in Grid using Adaptor property of DataManager as
WebMethodAdaptor .
For every operations, an AJAX post will be send to the specified data service.
razor
webapi.cs
@Html.EJS().Grid("WebApi").DataSource(dataManger =>
{
dataManger.Url("Default.aspx/DataSource").CrossDomain(true).Adaptor("WebMethodAdapt
or");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).Render()
return View();
}
736
WebMethodAdaptor expects JSON response from the server and the response object should
contain properties result and count whose values are collection of entities and total count of
the entities respectively.
{
result: [{..}, {..}, {..}, ...],
count: 830
}
Offline mode
On remote data binding, all grid actions such as paging, sorting, editing, grouping, filtering, etc,
will be processed on server-side. To avoid post back for every action, set the grid to load all data
on initialization and make the actions process in client-side. To enable this behavior, use the
Offline property of DataManager .
razor
offline.cs
@Html.EJS().Grid("Offline").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").
CrossDomain(true).Offline(true).Adaptor("ODataV4Adaptor");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(
Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syn
cfusion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging().Render()
737
Sending additional parameters to the server
To add a custom parameter to the data request, use the addParams method of Query class.
Assign the Query object with additional parameters to the grid Query property.
razor
params.cs
@Html.EJS().Grid("Params").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").
CrossDomain(true).Adaptor("ODataV4Adaptor");
}).Query("new ej.data.Query().addParams('ej2Grid', 'true')")
.Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(
Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syn
cfusion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging().Render()
return View();
}
The parameters added using the Query property will be sent along with the data request
for every grid action.
738
The argument passed to the ActionFailure event contains the error details returned from the
server.
razor
httperror.cs
@Html.EJS().Grid("check").DataSource(dataManger =>
{
dataManger.Url("http://some.com/invalidUrl");
}).Columns(col =>
{
col.Field("ProductID").HeaderText("Product ID").Width("120").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("ProductName").HeaderText("Product Name").Width("150").Add();
col.Field("UnitPrice").HeaderText("Supplier ID").Width("130").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("UnitsInStock").HeaderText("QuantityPerUnit").Width("120").TextAlign(
Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").Width("140").TextAlign(Syn
cfusion.EJ2.Grids.TextAlign.Center).Type("boolean").DisplayAsCheckBox(true).Add();
}).ActionFailure("actionFailure").Render()
<script>
function actionFailure(args) {
var span = document.createElement('span');
this.element.parentNode.insertBefore(span, this.element);
span.style.color = '#FF0000'
span.innerHTML = 'Server exception: 404 Not found';
}
</script>
return View();
}
The ActionFailure event will be triggered not only for the server errors, but also when
there is an exception while processing the grid actions.
739
On-Demand grid actions helps you to improve performance for large data application. To achieve
On-Demand in grid, you would have to use UrlAdaptor . To define UrlAdaptor in grid, you have
to specify data service in url and the AdaptorType as UrlAdaptor like below.
razor
Once you have defined DataManager , grid will request an AJAX POST for data. It will be send to
the specified data service for every grid actions with the needed parameters. This query
parameters will help you to perform server-side operations for grid. These are available
parameters and its uses.
Parameters Description
RequiresCounts If it is true then the total count of records will included in response.
Where It contains details of current filter column name and its constraints.
These parameters of DataManager will bound to DataManagerRequest in server. You can use
Dataoperations and DataManagerRequest to process grid actions such as Paging , Sorting ,
Searching and Filtering using following methods.
PerformSkip
Bypasses a specified Skip value and returns the remaining
collections of records.
PerformTake
Bypasses a specified Take value and returns the remaining
collections of records.
740
PerformSorting Sorts the collections of records based on its direction.
dataoperation.cs
741
Columns
The column definitions are used as the DataSource schema in the Grid. This plays a vital role in
rendering column values in the required format. The grid operations such as sorting, filtering and
grouping etc. are performed based on column definitions. The Field property of the Columns
is necessary to map the data source values in Grid columns.
1. If the column Field is not specified in the dataSource, the column values will be
empty.
2. If the Field name contains “dot” operator, it is considered as complex binding.
Auto generation
The Columns are automatically generated when Columns declaration is empty or undefined
while initializing the grid. All the columns in the DataSource are bound as grid columns.
razor
auto.cs
@Html.EJS().Grid("Auto").DataSource((IEnumerable<object>)ViewBag.dataSource).Render()
When columns are auto-generated, the column Type will be determined from the first
record of the DataSource .
Header Template
You can customize the header element by using the HeaderTemplate property. In this demo, the
custom element is rendered for both EmployeeID and BirthDate column headers.
razor
headertemplate.cs
@Html.EJS().Grid("HeaderTemplate").DataSource((IEnumerable<object>)ViewBag.dataSource).
Columns(col =>
742
{
col.Field("EmployeeID").HeaderTemplate("#employeetemplate").Width("120").TextAlign(
Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").Width("140").Add();
col.Field("BirthDate").HeaderTemplate("#datetemplate").Width("130").TextAlign(Syncf
usion.EJ2.Grids.TextAlign.Right).Add();
col.Field("City").Width("120").Add();
col.Field("Country").Width("140").Add();
}).AllowPaging().Render()
<style>
.e-grid .e-icon-userlogin::before {
width: 15px !important;
content: '\e7d4';
}
.e-grid .e-icon-calender::before {
width: 15px !important;
content: '\e7b5';
}
</style>
Header text
By default, column header title is displayed from column Field value. To override the default
header title, you have to define the HeaderText value.
743
razor
headertext.cs
@Html.EJS().Grid("HeaderText").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").Width("120").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("First Name").Width("140").Add();
col.Field("BirthDate").HeaderText("Birth Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("City").Width("120").Add();
col.Field("Country").HeaderText("Country").Width("140").Add();
}).AllowPaging().Render()
If both the Field and HeaderText are not defined in the column, the column renders
with “empty” header text.
Format
To format cell values based on specific culture, use the Columns.Format property. The grid uses
Internalization library to format number and date values.
razor
format.cs
@Html.EJS().Grid("Format").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(
col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlig
n.Right).Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.Text
Align.Right).Width("130").Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
744
.Right).Width("120").Format("C2").Add();
}).AllowPaging().Render()
By default, the number and date values are formatted in en-US locale.
razor
autofit.cs
@Html.EJS().Grid("AutoFit").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns
(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
.Right).Width("120").Format("C2").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().DataBound("dataBind").Render()
<script>
function dataBind(args) {
this.autoFitColumns(['OrderDate', 'ShipCountry']);
}
</script>
745
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
You can autofit all the columns by invoking the AutoFitColumns method without column
names.
Reorder
Reordering can be done by drag and drop of a particular column header from one index to
another index within the grid. To enable reordering, set the AllowReordering to true.
razor
reorder.cs
@Html.EJS().Grid("Reorder").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowR
eordering().Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").Width("125").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("Name").Width("125").Add();
col.Field("Title").HeaderText("Title").Width("190").TextAlign(Syncfusion.EJ2.Grid
s.TextAlign.Right).Add();
col.Field("HireDate").HeaderText("Hire Date").Width("135").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
}).Render()
Column resizing
Column width can be resized by clicking and dragging the right edge of the column header. While
dragging, the width of the respective column will be resized immediately. Each column can be
auto resized by double-clicking the right edge of the column header to fit the width of that column
746
based on the widest cell content. To enable column resize, set the AllowResizing property to
true.
razor
resize.cs
@Html.EJS().Grid("ColumnResize").DataSource((IEnumerable<object>)ViewBag.dataSource).Al
lowResizing(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("200").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("200").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("150").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Country").Width("300").Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("200").Format("yMd").A
llowResizing(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Country").Width("200").Add();
col.Field("ShipName").HeaderText("Ship Country").Width("200").Add();
}).AllowPaging().Render()
You can disable resizing for a particular column by setting the Columns.AllowResizing
to false.
In RTL mode, you can click and drag the left edge of the header cell to resize the
column.
In the following sample, minimum and maximum width are defined for OrderID , Ship Name ,
and Ship Country columns.
razor
747
min.cs
@Html.EJS().Grid("ColumnResizeMinMax").DataSource((IEnumerable<object>)ViewBag.dataSou
rce).AllowResizing(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").MinWidth("120").Width("200").MaxWidt
h("300").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("200").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("150").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("200").Format("yMd").A
llowResizing(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Country").MinWidth("30").Width("100").Max
Width("200").Add();
col.Field("ShipCountry").HeaderText("Ship Country").MinWidth("50").Width("200").
MaxWidth("300").Add();
}).AllowPaging().Render()
Touch interaction
When the right edge of the header cell is tapped, a floating handler will be visible over the right
border of the column. To resize the column, tap and drag the floating handler as needed.
748
Column template
The column Template has options to display custom element instead of a field value in the
column.
razor
template.cs
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).Width(
"auto").Height("359").Columns(col =>
{
col.HeaderText("Employee Image").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center
).Template("#template").Width("150").Add();
col.Field("EmployeeID").HeaderText("Employee ID").Width("120").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("Name").Width("125").Add();
col.Field("Title").HeaderText("Title").Width("170").Add();
col.Field("HireDate").HeaderText("Hire Date").Width("135").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Format("yMd").Add();
}).Render()
<style>
.image img {
height: 55px;
749
width: 55px;
border-radius: 50px;
box-shadow: inset 0 0 1px #e0e0e0, inset 0 0 14px rgba(0, 0, 0, 0.2);
}
</style>
Grid actions such as editing, grouping, filtering and sorting etc. will depend upon the column
Field . If the Field is not specified in the template column, the grid actions cannot be
performed.
Column type
Column type can be specified using the Columns.Type property. It specifies the type of data the
column binds.
If the Format is defined for a column, the column uses Type to select the appropriate format
option ( number or date )).
string
number
boolean
date
datetime
If the Type is not defined, it will be determined from the first record of the DataSource .
Column chooser
750
The column chooser has options to show or hide columns dynamically. It can be enabled by
defining the ShowColumnChooser as true.
razor
columnchooser.cs
@Html.EJS().Grid("ColumnChooser").DataSource((IEnumerable<object>)ViewBag.DataSource).S
howColumnChooser(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ShowInColumnChoose
r(false).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCity").Visible(false).HeaderText("Ship Country").Width("150").Visibl
e(false).Add();
col.Field("ShipCountry").Visible(false).HeaderText("Ship Country").Width("150").Add
();
You can hide the column names in column chooser by defining the
Columns.ShowInColumnChooser as false.
razor
externalbutton.cs
751
@Html.EJS().Grid("ColumnChooserGrid").DataSource((IEnumerable<object>)ViewBag.DataSourc
e).ShowColumnChooser(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ShowInColumnChoose
r(false).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCity").Visible(false).HeaderText("Ship Country").Width("150").Add();
col.Field("ShipCountry").Visible(false).HeaderText("Ship Country").Visible(false).W
idth("150").Add();
}).AllowPaging().Render()
<script>
document.getElementById('opencolumnchooser').addEventListener("click", () => {
var grid = document.getElementById('ColumnChooserGrid').ej2_instances[0];
grid.columnChooserModule.openColumnChooser(200, 50); // give X and Y axis
});
</script>
Column menu
The column menu has options to integrate features like sorting, grouping, filtering, column
chooser, and autofit. It will show a menu with the integrated feature when users click on multiple
icon of the column. To enable column menu, you need to define the ShowColumnMenu property as
true.
Item Description
752
SortDescending Sort the current column in descending order.
You can disable column menu for a particular column by defining the
Columns.ShowColumnMenu as false.
You can customize the default items by defining the ColumnMenuItems with required
items.
razor
customcolumnmenu.cs
@{
List<object> columnMenuitems = new List<object>();
columnMenuitems.Add(new { text = "Clear Sorting", id = "gridclearsorting" });
List<object> cols = new List<object>();
cols.Add(new { field = "CustomerID", direction = "Ascending" });
}
@Html.EJS().Grid("CustomColumnMenu").DataSource((IEnumerable<object>)ViewBag.dataSource
).ShowColumnMenu(true).AllowSorting().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();
<script>
function columnMenuClick(args) {
753
if (args.item.id === 'gridclearsorting') {
this.clearSorting();
}
}
</script>
The following sample, Filter item was hidden in column menu when opens for the OrderID
column.
razor
customizecolumnmenu.cs
@Html.EJS().Grid("CustomizeColumnMenu").DataSource((IEnumerable<object>)ViewBag.dataSou
rce).ShowColumnMenu(true).AllowSorting().AllowFiltering(true).AllowGrouping().ColumnMen
uOpen("columnMenuOpen").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("150").Add();
}).FilterSettings(filter=> { filter.Type(Syncfusion.EJ2.Grids.FilterType.CheckBox);
}).GroupSettings(group=>group.ShowGroupedColumn(true)).AllowPaging().Render()
<script>
function columnMenuOpen(args) {
for (let item of args.items) {
if (item.text === 'Filter' && args.column.field === 'OrderID') {
item.hide = true;
754
} else {
item.hide = false;
}
}
}
</script>
Column spanning
The grid has option to span the adjacent cells. You need to define the colSpan attribute to span
cells in the QueryCellInfo event.
In the following demo, employee Davolio is doing testing from 9.00 A.M. to 10.00 A.M. so that
the cells have been spanned.
razor
columnspanning.cs
@Html.EJS().Grid("CellMerging").DataSource((IEnumerable<object>)ViewBag.Datasource).Que
ryCellInfo("QueryCellEvent").GridLines(Syncfusion.EJ2.Grids.GridLine.Both).Columns(col
=>
{
col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Width("150").Add();
col.Field("EmployeeName").HeaderText("Employee Name").Width("200").Add();
col.Field("Time900").HeaderText("9.00 AM").Width("120").Add();
col.Field("Time930").HeaderText("9.30 AM").Width("120").Add();
col.Field("Time1000").HeaderText("10.00 AM").Width("120").Add();
col.Field("Time1030").HeaderText("10.30 AM").Width("120").Add();
col.Field("Time1100").HeaderText("11.00 AM").Width("120").Add();
col.Field("Time1130").HeaderText("11.30 AM").Width("120").Add();
col.Field("Time1200").HeaderText("12.00 PM").Width("120").Add();
col.Field("Time1230").HeaderText("12.30 PM").Width("120").Add();
col.Field("Time100").HeaderText("1.00 PM").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Center).Add();
col.Field("Time200").HeaderText("2.00 PM").Width("120").Add();
col.Field("Time230").HeaderText("2.30 PM").Width("120").Add();
col.Field("Time300").HeaderText("3.00 PM").Width("120").Add();
col.Field("Time330").HeaderText("3.30 PM").Width("120").Add();
755
col.Field("Time400").HeaderText("4.00 PM").Width("120").Add();
col.Field("Time430").HeaderText("4.30 PM").Width("120").Add();
col.Field("Time500").HeaderText("5.00 PM").Width("120").Add();
}).Render()
<script>
function QueryCellEvent(args)
{
var data = args.data;
switch (data.EmployeeID) {
case 10001:
if (args.column.field === 'Time900' || args.column.field === 'Time230' || a
rgs.column.field === 'Time430') {
args.colSpan = 2;
} else if (args.column.field === 'Time1100') {
args.colSpan = 3;
}
break;
case 10002:
if (args.column.field === 'Time930' || args.column.field === 'Time230' ||
args.column.field === 'Time430') {
args.colSpan = 3;
} else if (args.column.field === 'Time1100') {
args.colSpan = 4;
}
break;
case 10003:
if (args.column.field === 'Time900' || args.column.field === 'Time1130') {
args.colSpan = 3;
} else if (args.column.field === 'Time1030' || args.column.field === 'Time3
30' ||
args.column.field === 'Time430' || args.column.field === 'Time230') {
args.colSpan = 2;
}
break;
case 10004:
if (args.column.field === 'Time900') {
args.colSpan = 3;
} else if (args.column.field === 'Time1100') {
args.colSpan = 4;
} else if (args.column.field === 'Time400' || args.column.field === 'Time23
0') {
args.colSpan = 2;
}
break;
case 10005:
if (args.column.field === 'Time900') {
args.colSpan = 4;
} else if (args.column.field === 'Time1130') {
756
args.colSpan = 3;
} else if (args.column.field === 'Time330' || args.column.field === 'Time43
0' || args.column.field === 'Time230') {
args.colSpan = 2;
}
break;
case 10006:
if (args.column.field === 'Time900' || args.column.field === 'Time430' ||
args.column.field === 'Time230' || args.column.field === 'Time330') {
args.colSpan = 2;
} else if (args.column.field === 'Time1000' || args.column.field === 'Time1
130') {
args.colSpan = 3;
}
break;
case 10007:
if (args.column.field === 'Time900' || args.column.field === 'Time300' || a
rgs.column.field === 'Time1030') {
args.colSpan = 2;
} else if (args.column.field === 'Time1130' || args.column.field === 'Time4
00') {
args.colSpan = 3;
}
break;
}
}
</script>
Responsive columns
You can toggle column visibility based on media queries which are defined at the HideAtMedia .
The HideAtMedia accepts valid Media Queries.
razor
responsivecolumns.cs
@Html.EJS().Grid("ResponsiveColumn").DataSource((IEnumerable<object>)ViewBag.DataSource
).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlig
757
n.Right).HideAtMedia("min-width: 700px").Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").HideAtMedia("max-w
idth: 500px").Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.Text
Align.Right).HideAtMedia("min-width: 500px").Width("130").Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
.Right).Width("120").Format("C2").Add();
}).AllowPaging().Render()
razor
controllingactions.cs
@Html.EJS().Grid("ControlGridAction").DataSource((IEnumerable<object>)ViewBag.DataSourc
e).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlig
n.Right).AllowGrouping(false).Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").AllowFiltering(fal
se).Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.Text
Align.Right).Width("130").Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
.Right).Width("120").AllowSorting(false).Format("C2").Add();
}).AllowPaging().AllowGrouping().AllowFiltering().AllowSorting().Render()
758
Show/hide columns by external button
You can show or hide grid columns dynamically using external buttons by invoking the
showColumns or hideColumns method.
razor
showhide.cs
@Html.EJS().Button("Show").Content("Sow").IsPrimary(true).Render()
@Html.EJS().Button("Hide").Content("Hide").IsPrimary(true).Render()
@Html.EJS().Grid("ShowHide").DataSource((IEnumerable<object>)ViewBag.DataSource).Co
lumns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.Text
Align.Right).Width("120").Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.
TextAlign.Right).Width("130").Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextA
lign.Right).Width("120").Format("C2").Add();
}).AllowPaging().Render()
<script>
document.getElementById("Show").addEventListener("click", () => {
var grid = document.getElementById("ShowHide").ej2_instances[0];
grid.showColumns(['Customer Name', 'Order Date']); //show by HeaderText
});
document.getElementById("Hide").addEventListener("click", () => {
var grid = document.getElementById("ShowHide").ej2_instances[0];
grid.hideColumns(['Customer Name', 'Order Date']); //hide by HeaderText
})
</script>
759
Complex data binding
You can achieve complex data binding in the grid by using the dot(.) operator in the
Column.Field .
razor
complexbinding.cs
@Html.EJS().Grid("Complex").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns
(col =>
{
col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right
).Add();
col.Field("Name.FirstName").HeaderText("FirstName").Width("140").Add();
col.Field("Name.LastName").HeaderText("LastName").Width("130").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("City").Width("120").Add();
col.Field("Country").Width("140").Add();
}).AllowPaging().Render()
In the following example, Employee Name is a foreign column which shows FirstName column
from foreign data.
razor
foreign.cs
@Html.EJ().Grid("ForeignKey").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
760
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign("Right").Add(
);
col.Field("EmployeeID").ForeignKeyValue("FirstName").DataSource((IEnumerable<obj
ect>)ViewBag.foreign).HeaderText("Employee Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign("
Right").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
}).Render()
For remote data, the sorting and grouping is done based on Column.ForeignKeyField
instead of Column.ForeignKeyValue .
If Column.ForeignKeyField is not defined, then the column uses Column.Field .
See Also
How to Change Column Header Text Dynamically
Customize Column Styles
Custom Tooltip for Columns
How to Render Other Component in a Column
How to change the Orientation of Header Text
Group Column by Format
How to Use Edit Template in Foreign Key Column
How to Create and use custom Filter UI in Foreign Key Column
How to Use Filter Bar Template in Foreign Key Column
How to Perform aggregation in Foreign Key Column
761
Row
The row represents record details fetched from data source.
Row template
The RowTemplate has an option to customise the look and behavior of the grid rows. The
RowTemplate property accepts either the template string or HTML element ID.
razor
row-template.cs
@Html.EJS().Grid("RowTemplate").DataSource((IEnumerable<object>)ViewBag.dataSource).Hei
ght("335").Width("auto").RowTemplate("#rowtemplate").Columns(col =>
{
col.HeaderText("Employee Image").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center
).Width("150").Add();
col.HeaderText("Employee Details").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Left
).Width("300").Field("EmployeeID").Add();
}).Render()
.photo,
.details {
border-color: #e0e0e0;
border-style: solid;
}
.photo {
border-width: 1px 0px 0px 0px;
text-align: center;
}
.details {
border-width: 1px 0px 0px 0px;
padding-left: 18px;
762
}
.e-bigger .details {
padding-left: 25px;
}
.e-device .details {
padding-left: 8px;
}
.CardHeader {
font-weight: 600;
}
td {
padding: 2px 2px 3px 4px;
}
</style>
<script id="rowtemplate" type="text/x-template">
<tr>
<td class="photo">
<img src="/Content/images/Employees/${EmployeeID}.png" alt="${EmployeeID}"
/>
</td>
<td class="details">
<table class="CardTable" cellpadding="3" cellspacing="2">
<colgroup>
<col width="50%">
<col width="50%">
</colgroup>
<tbody>
<tr>
<td class="CardHeader">First Name </td>
<td>${FirstName} </td>
</tr>
<tr>
<td class="CardHeader">Last Name</td>
<td>${LastName} </td>
</tr>
<tr>
<td class="CardHeader">
Title
</td>
<td>
763
${Title}
</td>
</tr>
<tr>
<td class="CardHeader">
Birth Date
</td>
<td>
${BirthDate.toLocaleDateString()}
</td>
</tr>
<tr>
<td class="CardHeader">
Hire Date
</td>
<td>
${HireDate.toLocaleDateString()}
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</script>
Detail template
The detail template provides additional information about a particular row by expanding or
collapsing detail content. The DetailTemplate property accepts either the template string or
HTML element ID.
razor
detail-temp.cs
@Html.EJS().Grid("DetailTemplate").DataSource((IEnumerable<object>)ViewBag.dataSource).
DetailTemplate("#detailtemplate").Width("auto").Columns(col =>
{
764
col.Field("EmployeeID").HeaderText("Employee ID").Width("110").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("Name").Width("110").Add();
col.Field("Title").HeaderText("Title").Width("150").Add();
col.Field("Country").HeaderText("Country").Width("110").Add();
}).Render()
.photo {
width: 100px;
height: 100px;
border-radius: 50px;
box-shadow: inset 0 0 1px #e0e0e0, inset 0 0 14px rgba(0, 0, 0, 0.2);
}
</style> <script type="text/x-template" id="detailtemplate">
<table class="detailtable" width="100%">
<colgroup>
<col width="35%" />
<col width="35%" />
<col width="30%" />
</colgroup>
<tbody>
<tr>
<td rowspan="4" style="text-align: center;">
<img class="photo" src="/scripts/Images/Employees/${EmployeeID}.png"
alt="${EmployeeID}" />
</td>
<td>
<span style="font-weight: 500;">First Name: </span> ${FirstName}
</td>
<td>
<span style="font-weight: 500;">Postal Code: </span> ${PostalCode}
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Last Name: </span> ${LastName}
</td>
<td>
<span style="font-weight: 500;">City: </span> ${City}
765
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Title: </span> ${Title}
</td>
<td>
<span style="font-weight: 500;">Phone: </span> ${HomePhone}
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Address: </span> ${Address}
</td>
<td>
<span style="font-weight: 500;">HireDate: </span> ${HireDate.toLoca
leDateString()}
</td>
</tr>
</tbody>
</table>
</script>
For example, to render grid inside the detail row, place an HTML div element as the
DetailTemplate and render the DIV element as grid component in the DetailDataBound event.
razor
custom-component.cs
@Html.EJS().Grid("DetailTemplate").DataSource((IEnumerable<object>)ViewBag.dataSource).
DetailTemplate("#detailtemplate").Width("auto").Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").Width("110").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
766
col.Field("FirstName").HeaderText("Name").Width("110").Add();
col.Field("Title").HeaderText("Title").Width("150").Add();
col.Field("Country").HeaderText("Country").Width("110").Add();
}).DetailDataBound("detailDataBound").Render()
<script>
function detailDataBound (e) {
var detail = new ej.grids.Grid({
dataSource: data.filter(function (item) {item['EmployeeID'] === e.data['Employe
eID']}).slice(0, 3),
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 110 },
{ field: 'CustomerID', headerText: 'Customer Name', width: 140 },
{ field: 'ShipCountry', headerText: 'Ship Country', width: 150 }
]
});
detail.appendTo(e.detailElement.querySelector('.custom-grid'));
}
</script>
razor
expand-external.cs
@Html.EJS().Grid("DetailTemplate").DataSource((IEnumerable<object>)ViewBag.dataSource)
.DetailTemplate("#detailtemplate").Width("auto").Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").Width("110").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("FirstName").HeaderText("Name").Width("110").Add();
col.Field("Title").HeaderText("Title").Width("150").Add();
col.Field("Country").HeaderText("Country").Width("110").Add();
}).Render()
<script>
document.getElementById('expand').addEventListener('click', () => {
767
var grid = document.getElementById('DetailTemplate').ej2_instances[0];
let inputElem = document.getElementsByClassName('rowindex')[0];
let rowIndex = parseInt(inputElem.value, 10);
grid.detailRowModule.expand(rowIndex);
});
</script>
.photo {
width: 100px;
height: 100px;
border-radius: 50px;
box-shadow: inset 0 0 1px #e0e0e0, inset 0 0 14px rgba(0, 0, 0, 0.2);
}
</style>
<script type="text/x-template" id="detailtemplate">
<table class="detailtable" width="100%">
<colgroup>
<col width="35%" />
<col width="35%" />
<col width="30%" />
</colgroup>
<tbody>
<tr>
<td rowspan="4" style="text-align: center;">
<img class="photo" src="/scripts/Images/Employees/${EmployeeID}.png"
alt="${EmployeeID}" />
</td>
<td>
<span style="font-weight: 500;">First Name: </span> ${FirstName}
</td>
<td>
<span style="font-weight: 500;">Postal Code: </span> ${PostalCode}
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Last Name: </span> ${LastName}
</td>
<td>
768
<span style="font-weight: 500;">City: </span> ${City}
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Title: </span> ${Title}
</td>
<td>
<span style="font-weight: 500;">Phone: </span> ${HomePhone}
</td>
</tr>
<tr>
<td>
<span style="font-weight: 500;">Address: </span> ${Address}
</td>
<td>
<span style="font-weight: 500;">HireDate: </span> ${HireDate.toLoca
leDateString()}
</td>
</tr>
</tbody>
</table>
</script>
razor
drag-drop.cs
@Html.EJS().Grid("RowDragDrop").DataSource((IEnumerable<object>)ViewBag.dataSource).All
owSelection().AllowRowDragAndDrop(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ShowInColumnChoose
769
r(false).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).AllowPaging().SelectionSettings(select=>select.Type( Syncfusion.EJ2.Grids.SelectionT
ype.Multiple)).PageSettings(page => page.PageCount(1).PageSize(10)).RowDropSettings(new
Syncfusion.EJ2.Grids.GridRowDropSettings() { TargetID = "DestGrid" }).Render()
</div>
<div class="col-lg-6">
@Html.EJS().Grid("DestGrid").AllowSelection().AllowRowDragAndDrop(true).Columns
(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ShowInColumnChoose
r(false).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).AllowPaging().SelectionSettings(select=>select.Type( Syncfusion.EJ2.Grids.SelectionT
ype.Multiple)).PageSettings(page => page.PageCount(1).PageSize(5)).RowDropSettings(new
Syncfusion.EJ2.Grids.GridRowDropSettings() { TargetID = "RowDragDrop" }).Render()
Customize rows
You can customize the appearance of a row by using the RowDataBound event. The
RowDataBound event triggers for every row. In the event handler, you can get the
RowDataBoundEventArgs that contains details of the row.
razor
custom-rows.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Column
770
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function rowBound(args) {
if (args.data['Freight'] < 30) {
args.row.classList.add('below-30');
} else if (args.data['Freight'] < 80) {
args.row.classList.add('below-80');
} else {
args.row.classList.add('above-80');
}
}
</script>
.e-grid .e-altrow {
background-color: #fafafa;
}
razor
style-alt-row.cs
771
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).Render()
<style>
.e-grid .e-altrow {
background-color: #fafafa;
}
</style>
Row height
You can customize the row height of grid rows through the RowHeight property. The RowHeight
property is used to change the row height of entire grid rows.
razor
row-height.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
772
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).RowHeight(60).Render()
In the below example, the row height for the row with OrderID as '10249' is set as '90px' using
the RowDataBound event.
razor
rowheight-particular.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).RowDataBound("rowDataBound").Render()
<script>
function rowDataBound(args) {
if (args.data.OrderID === 10249) {
args.rowHeight = 90;
}
}
</script>
773
{
ViewBag.DataSource = OrderDetails.GetAllRecords();
return View();
}
In virtual scrolling mode, it is not applicable to set the RowHeight using the
RowDataBound event.
774
Cell
razor
html.cs
@Html.EJS().Grid("HTMLEncode").DataSource((IEnumerable<object>)ViewBag.dataSource).Co
lumns(col =>
{
razor
customize.cs
@Html.EJS().Grid("CellCustomize").DataSource((IEnumerable<object>)ViewBag.DataSource).
775
Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().QueryCellInfo("customiseCell").Render()
<style>
.below-5 {
background-color: orangered;
}
.below-8 {
background-color: yellow;
}
.above-8 {
background-color: greenyellow
}
</style>
<script>
function customiseCell(args) {
if(args.column.field === 'Freight') {
if (args.data['Freight'] < 5){
args.cell.classList.add('below-5');
} else if(args.data['Freight'] < 8 ) {
args.cell.classList.add('below-8');
} else {
args.cell.classList.add('above-8');
}
}
}
</script>
776
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
Auto wrap
The auto wrap allows the cell content of the grid to wrap to the next line when it exceeds the
boundary of the cell width. To enable auto wrap, set the AllowTextWrap property to true . You
can configure the auto wrap mode by setting the TextWrapSettings.WrapMode property.
Both : Both value is set by default. Auto wrap will be enabled for both the content and the
header.
Header : Auto wrap will be enabled only for the header.
Content : Auto wrap will be enabled only for the content.
razor
autowrap.cs
@Html.EJS().Grid("AutoWrap").DataSource((IEnumerable<object>)ViewBag.dataSource).Allow
TextWrap().Columns(col =>
{
col.Field("NumberofPatentFamilies").HeaderText("NumberofPatentFamilies").Width("120"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Inventor").HeaderText("Inventor").Width("150").Add();
col.Field("NumberofINPADOCpatents").HeaderText("NumberofINPADOCpatents").Width("120"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Mainfieldsofinvention").HeaderText("Mainfieldsofinvention").Width("150")
.Add();
col.Field("Active").HeaderText("Active").Width("150").Add();
777
}
Grid Lines
The GridLines have option to display cell border and it can be defined by the GridLines
property.
Modes Actions
razor
gridlines.cs
@Html.EJS().Grid("GridLine").DataSource((IEnumerable<object>)ViewBag.dataSource).GridL
ines(Syncfusion.EJ2.Grids.GridLine.Both).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Format("C2").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
778
Clip Mode
The clip mode provides options to display its overflow cell content and it can be defined by the
Columns.ClipMode property.
razor
clipmode.cs
@Html.EJS().Grid("ClipMode").DataSource((IEnumerable<object>)ViewBag.dataSource).Colum
ns(col =>
{
col.Field("NumberofPatentFamilies").HeaderText("NumberofPatentFamilies").Width("
120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Inventor").HeaderText("Inventor").ClipMode(Syncfusion.EJ2.Grids.ClipM
ode.Clip).Width("150").Add();
col.Field("NumberofINPADOCpatents").ClipMode(Syncfusion.EJ2.Grids.ClipMode.Ellip
sis).HeaderText("NumberofINPADOCpatents").Width("120").TextAlign(Syncfusion.EJ2.Grids.T
extAlign.Right).Add();
col.Field("Mainfieldsofinvention").ClipMode(Syncfusion.EJ2.Grids.ClipMode.Ellips
isWithTooltip).HeaderText("Mainfieldsofinvention").Width("150").Add();
col.Field("Active").HeaderText("Active").Width("150").Add();
}).AllowPaging().Render()
779
Editing
The Grid component has options to dynamically insert, delete and update records. Editing feature
requires a primary key column for CRUD operations. To define the primary key, set
Columns.IsPrimaryKey to true in particular column.
You can start the edit action either by double clicking the particular row or by selecting the
required row and click on Edit button in the toolbar. Similarly, you can add a new record to grid
either by clicking on Add button in the toolbar or on an external button which is bound to invoke
the addRecord method of the grid, Save and Cancel while in edit mode is possible using
respective toolbar icon in grid.
Deletion of the record is possible by selecting the required row and click on Delete button in the
toolbar.
razor
edit.cs
@Html.EJS().Grid("NormalEdit").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
780
If Columns.IsIdentity is enabled, then it will be considered as a read-only column
when editing and adding a record.
You can disable editing for a particular column, by specifying Columns.AllowEditing to
false .
razor
edittoolbar.cs
@Html.EJS().Grid("EditToolbar").DataSource((IEnumerable<object>)ViewBag.dataSource).Co
lumns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = "true"}).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
781
TextBox component for string data type.
Also, you can customize model of the Columns.EditType through the Columns.Edit.Params .
The following table describes cell edit type and their corresponding edit params of the column.
Component Example
NumericTextBox params: { decimals: 2, value: 5 }
TextBox -
razor
celleditparams.cs
@Html.EJS().Grid("EditParam").DataSource((IEnumerable<object>)ViewBag.dataSource).Colum
ns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true" }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add
();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Edit(n
ew { @params = new { value = "Germany" } }).Width("150").Add();
If edit type is not defined in the column, then it will be considered as the stringedit type
(Textbox component) .
782
Edit Modes
Grid supports the following types of edit modes, they are:
Normal
Dialog
Batch
Normal
In Normal edit mode, when you start editing the currently selected record is changed to edit state.
You can change the cell values and save edited data to the data source. To enable Normal edit,
set the EditSettings.Mode as Normal .
razor
inline.cs
@Html.EJS().Grid("InlineEdit").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
783
Dialog
In dialog edit mode, when you start editing the currently selected row data will be shown on a
dialog. You can change the cell values and save edited data to the data source. To enable Dialog
edit, set the EditSettings.Mode as Dialog .
razor
dialog.cs
@Html.EJS().Grid("DialogEdit").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
Batch
In batch edit mode, when you double-click on the grid cell, then the target cell changed to edit
state. You can bulk save (added, changed and deleted data in the single request) to data source
by click on the toolbar's Update button or by externally calling the batchSave method. To
enable Batch edit, set the EditSettings.Mode as Batch .
razor
batch.cs
784
@Html.EJS().Grid("BatchEdit").DataSource((IEnumerable<object>)ViewBag.dataSource).Colum
ns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
Command column
The command column provides an option to add CRUD action buttons in a column. This can be
defined by the Column.Commands property.
razor
commandcolumn.cs
@{
785
List<object> commands = new List<object>();
commands.Add(new { type = "Edit", buttonOption = new { iconCss = "e-icons e-edi
t", cssClass = "e-flat" } });
commands.Add(new { type = "Delete", buttonOption = new { iconCss = "e-icons e-d
elete", cssClass = "e-flat" } });
commands.Add(new { type = "Save", buttonOption = new { iconCss = "e-icons e-upd
ate", cssClass = "e-flat" } });
commands.Add(new { type = "Cancel", buttonOption = new { iconCss = "e-icons e-c
ancel-icon", cssClass = "e-flat" } });
}
@Html.EJS().Grid("CommandColumn").DataSource((IEnumerable<object>)ViewBag.dataSourc
e).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
col.HeaderText("Manage Records").Width("160").Commands(commands).Add();
Confirmation messages
Delete confirmation
The delete confirm dialog can be shown when deleting a record by defining the
ShowDeleteConfirmDialog as true
razor
786
deleteconfirm.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = "true"}).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
Batch confirmation
By default, grid will show the confirm dialog when saving or cancelling or performing any actions
like filtering, sorting, etc.
razor
batchconfirm.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
787
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
Column validation
Column validation allows you to validate the edited or added row data and it display errors for
invalid fields before saving data. Grid uses Form Validator component for column validation.
You can set validation rules by defining the Columns.ValidationRules .
razor
columnvalid.cs
@Html.EJS().Grid("Validation").DataSource((IEnumerable<object>)ViewBag.dataSource).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
788
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
All the CRUD operations in the grid are done through DataManager . The DataManager has an
option to bind all the CRUD related data in server-side.
For your information, the ODataAdaptor persists data in the server as per OData protocol.
In the below section, we have explained how to get the edited data details on the server-side
using the UrlAdaptor .
URL adaptor
You can use the UrlAdaptor of DataManager when binding data source from remote data. In
the initial load of grid, data are fetched from remote data and bound to the grid using url
property of DataManager . You can map The CRUD operation in grid can be mapped to server-
side Controller actions using the properties InsertUrl , RemoveUrl , UpdateUrl , CrudUrl and
BatchUrl .
razor
urladaptor.cs
789
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add()
;
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = true, minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
Also, when using the UrlAdaptor , you need to return the data as JSON from the controller
action and the JSON object must contain a property as result with dataSource as its value and
one more property count with the dataSource total records count as its value.
razor
data.cs
790
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
Insert record
Using the InsertUrl property, you can specify the controller action mapping URL to perform
insert operation on the server-side.
razor
insert.cs
791
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
The newly added record details are bound to the value parameter. Please refer to the following
screenshot.
Update record
Using the UpdateUrl property, the controller action mapping URL can be specified to perform
save/update operation on the server-side.
razor
update.cs
792
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
The updated record details are bound to the value parameter. Please refer to the following
screenshot.
Delete record
Using the RemoveUrl property, the controller action mapping URL can be specified to perform
delete operation on the server-side.
razor
delete.cs
793
ionRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add()
;
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = true, minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
The deleted record primary key value is bound to the key parameter. Please refer to the
following screenshot.
CRUD URL
Using the CrudUrl property, the controller action mapping URL can be specified to perform all
the CRUD operation at server-side using a single method instead of specifying separate
controller action method for CRUD (insert, update and delete) operations.
The action parameter of CrudUrl is used to get the corresponding CRUD action.
razor
crudurl.cs
794
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add()
;
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = true, minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
795
//Delete record in database
}
}
Please refer to the following screenshot to know about the action parameter.
If you specify InsertUrl along with CrudUrl , then while adding InsertUrl only will be
invoked.
Batch URL
The BatchUrl property supports only for batch editing mode. You can specify the controller
action mapping URL to perform batch operation on the server-side.
razor
batchurl.cs
@Html.EJS().Grid("Grid").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc/Products").
CrossDomain(true).Adaptor("ODataV4Adaptor");
}).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
ionRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength=3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
796
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
razor
defaultcolumnvalue.cs
@Html.EJS().Grid("DefaultValue").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Validat
797
ionRules(new { required = "true" }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add
();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = "true", minLength = 3 }).DefaultValue("HANAR").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
Custom validation
You can define your own custom validation rules for the specific columns by using Form
Validator custom rules .
razor
customvalidation.cs
@Html.EJS().Grid("CustomValid").DataSource((IEnumerable<object>)ViewBag.dataSource).Co
lumns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new
{ required = true, minLength = ["customFn", 'Need atleast 5 letters'] }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width(
"150").Add();
798
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).Allow
Deleting(true); }).Render()
<script>
</script>
799
Disable editing for particular column
You can disable editing for particular columns by using the Columns.AllowEditing .
razor
disableeditforcolumn.cs
@Html.EJS().Grid("InlineEditing").DataSource((IEnumerable<object>)ViewBag.dataSource).C
olumns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).ValidationRules(new { required = "true"}).Add(
);
col.Field("CustomerID").HeaderText("Customer Name").AllowEditing(false).Width("150"
).ValidationRules(new { required = "true", minLength = 3 }).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
See also
Editing with template column
Customize dialog when editing
800
Cascading DropDownList with Grid Editing
Access Editor components
801
Sorting
Sorting enables you to sort data in the Ascending or Descending order. To sort a column, click
the column header.
To sort multiple columns, press and hold the CTRL key and click the column header. You can
clear sorting of any one of the multi-sorted columns by pressing and holding the SHIFT key and
clicking the specific column header.
To enable sorting in the Grid, set the AllowSorting to true. Sorting options can be configured
through the SortSettings .
razor
sorting.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSort
ing().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
Grid columns are sorted in the Ascending order. If you click the already sorted
column, the sort direction toggles.
You can apply and clear sorting by invoking sortColumn and clearSorting methods.
To disable sorting for a particular column, set the Columns.AllowSorting to false.
802
Initial sort
To sort at initial rendering, set the Field and Direction in the SortSettings.Columns .
razor
initial-sort.cs
@{
List<object> cols = new List<object>();
cols.Add(new { field = "OrderDate", direction = "Ascending" });
cols.Add(new { field = "Freight", direction = "Descending" });
}
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowS
orting().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
Sorting events
During the sort action, the grid component triggers two events. The ActionBegin event triggers
before the sort action starts, and the ActionComplete event triggers after the sort action is
completed. Using these events you can perform the needed actions.
razor
sort-event.cs
803
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowSorti
ng(true).ActionComplete("sortEvent").ActionBegin("sortEvent").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
<script>
function sortEvent(args){
alert(args.requestType + ' ' + args.type); //custom Action
}
</script>
804
, 12, 3), "1029 - 12th Ave. S."));
code += 5;
}
}
The args.requestType is the current action name. For example, in sorting the
args.requestType is 'sorting'.
Touch interaction
When you tap the grid header on touchscreen devices, the selected column header is sorted. A
popup is displayed for multi-column sorting. To sort multiple columns, tap the popup
805
Grouping
The Grid has options to group records by dragging and dropping the column header to the group
drop area. When grouping is applied, grid records are organized into a hierarchical structure to
facilitate easier expansion and collapse of records.
To enable grouping in the grid, set the AllowGrouping as true. Grouping options can be
configured through the GroupSettings .
razor
group.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowGrouping().Render()
You can group and ungroup columns by using the groupColumn and ungroupColumn
methods.
To disable grouping for a particular column, set the Columns.AllowGrouping to false.
Initial group
To apply group at initial rendering, set the column field name in the GroupSettings.Columns .
razor
initial-group.cs
806
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(
col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
Caption template
You can customize the group caption by using the GroupSettings.CaptionTemplate property.
razor
caption-temp.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
807
</script>
razor
hide-drop-area.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
808
On grouping columns with paging feature, the aggregated information and total items are
displayed based on the current page. The grid does not consider aggregated information and
total items from other pages. To get additional details (aggregated information and total items)
from other pages, set the GroupSettings.DisablePageWiseAggregates to false.
If remote data is bound to grid dataSource, two requests will be sent when performing
grouping action; one for getting the grouped data and another for getting aggregate details
and total items count.
Group by format
By default, a column will be grouped by the data or value present for the particular row. To group
the numeric or datetime column based on the mentioned format, you have to enable the
EnableGroupByFormat property of the corresponding grid columns.
razor
group-format.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").EnableGroupByFormat(true).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).EnableGroupByFormat(true).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
Grouping events
809
During the group action, the grid component triggers two events. The ActionBegin event
triggers before the group action starts and the ActionComplete event triggers after the group
action is completed. Using these events you can perform any action.
razor
grouping-events.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().AllowGrouping().ActionBegin("actionHandler").ActionComplete("action
Handler").Render()
<script>
function actionHandler(args) {
alert(args.requestType + ' ' + args.type); //Custom Action
}
</script>
The args.requestType is based on the current action name. For example, when grouping,
the args.requestType value will be 'grouping'.
razor
collapse.cs
810
@Html.EJS().Button("collapse").Content("Collapse").IsPrimary(true).Render()
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
document.getElementById('collapse').addEventListener('click', () => {
var grid = document.getElementById('Grid').ej2_instances[0];
if (grid.getSelectedRowIndexes().length) {
var currentTr = grid.getRows()[grid.getSelectedRowIndexes()[0]];
while (currentTr.classList && currentTr.classList.length) {
currentTr = currentTr.previousSibling;
}
let collapseElement = currentTr.querySelector('.e-recordplusexpand');
grid.groupModule.expandCollapseRows(collapseElement); //Pass the collapse row e
lement.
}
});
</script>
811
Filtering
Filtering allows you to view particular records based on filter criteria. To enable filtering in the
Grid, set the AllowFiltering to true. Filtering options can be configured through
FilterSettings .
razor
filter.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowFil
tering(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().Render()
You can apply and clear filtering by using filterByColumn and clearFiltering
methods.
To disable filtering for a particular column, set Columns.AllowFiltering to false.
Initial filter
To apply the filter at initial rendering, set the filter Predicate object in FilterSettings.Columns .
razor
initialfilter.cs
@{
List<object> filterColumns = new List<object>();
812
filterColumns.Add(new { field= "EmployeeID", matchCase= false, @operator= "equa
l", predicate= "and", value= 1 });
filterColumns.Add(new { field= "ShipCountry", matchCase= false, @operator= "sta
rtswith", predicate= "and", value= "Denmark" });
}
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowF
iltering(true).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("EmployeeID").HeaderText("Employee ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).FilterSettings(filter => filter.Columns(filterColumns)).AllowPaging().Render()
Filter operators
The filter operator for a column can be defined in the FilterSettings.Columns.Operator
property.
813
greaterthan the specified value. Number | Date
Filter bar
By setting the AllowFiltering to true, the filter bar row will render next to the header, which
allows you to filter data. You can filter the records with different expressions depending upon the
column type.
You can enter the following filter expressions (operators) manually in the filter bar.
Column
Expression Example Description
Type
razor
filter-bar.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowFilt
ering().Columns(col =>
{
814
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().Render()
razor
filterbartemplate.cs
@{
Object filterTemplate = new Object();
filterTemplate = (new { read = "read", write = "write" });
}
@Html.EJS().Grid("check").DataSource((IEnumerable<object>)ViewBag.dataSource).Colum
ns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("EmployeeID").HeaderText("Employee ID").FilterBarTemplate(filterTempl
ate).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("170").TextAlign(Syncfu
sion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").TextAlign(Syncfusion.EJ
815
col.Field("Freight").HeaderText("Freight").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
}).AllowPaging().AllowFiltering().Render()
<script type="text/javascript">
function write(args) {
var data = [{ text: "clear", value: "clear" }, { text: "1", value: 1 }, { t
ext: "2", value: 2 }, { text: "3", value: 3 }, { text: "4", value: 4 },
{ text: "5", value: 5 }, { text: "6", value: 6 }, { text: "7", value: 7 },
{ text: "8", value: 8 }, { text: "9", value: 9 }
]
var listObj = new ej.dropdowns.DropDownList({
dataSource: data,
placeholder: 'Select EmployeeID',
change: function () { read(args) }
});
listObj.appendTo(args.element);
}
function read(args) {
var grid = document.getElementById("check").ej2_instances[0]
if (args.element.value == "clear") {
grid.clearFiltering(args.column.field);
args.element.value = ""
} else {
grid.filterByColumn(args.column.field, "equal", parseInt(args.element.v
alue))
}
}
</script>
Filter menu
You can enable filter menu by setting the FilterSettings.Type as Menu . The filter menu UI will
be rendered based on its column type, which allows you to filter data. You can filter the records
with different operators.
razor
filtermenu.cs
816
iltering().Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("EmployeeID").HeaderText("Employee ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).FilterSettings(filter => {filter.Type(Syncfusion.EJ2.Grids.FilterType.Menu)}).All
owPaging().Render()
In the following sample menu filter is enabled by default and checkbox filter is enabled for the
CustomerID column using the Column.Filter.Type .
razor
diffcolumnfilter.cs
@Html.EJS().Grid("DifferentFilter").DataSource((IEnumerable<object>)ViewBag.dataSource)
.AllowFiltering().FilterSettings(filter => filter.Type(Syncfusion.EJ2.Grids.FilterType.
Menu)).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Filter(new { type="CheckBox" }).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Filter(new { type = "CheckBox" }).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
817
J2.Grids.TextAlign.Right).Filter(new { type = "CheckBox" }).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().Render()
818
Customizing filter menu operators list
819
Search
You can search records in a Grid, by using the Search method with search key as a parameter.
This also provides an option to integrate search text box in grid's toolbar by adding Search item
to the Toolbar .
razor
search.cs
@Html.EJS().Grid("Search").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("160").Add();
col.Field("Customer ID").HeaderText("Customer ID").Width("170").Add();
col.Field("Freight").HeaderText("Freight").Width("170").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Format("C2").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("170").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
Initial search
To apply search at initial rendering, set the fields, operator, key, and ignoreCase in the
SearchSettings .
razor
initial-search.cs
@Html.EJS().Grid("Search").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns
(col =>
{
col.Field("CategoryName").HeaderText("Category Name").Width("160").Add();
820
col.Field("ProductName").HeaderText("Product Name").Width("170").Add();
col.Field("UnitsInStock").HeaderText("Units In Stock").Width("170").TextAlign(Syncf
usion.EJ2.Grids.TextAlign.Right).Add();
col.Field("QuantityPerUnit").HeaderText("Quantity Per Unit").Width("170").TextAlign
(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").TextAlign(Syncfusion.EJ2.Grids
.TextAlign.Center).Width("140").Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging().SearchSettings(search => { search.Fields(new string[] { "CustomerID" }
).Key("Ha").Operator("contains").IgnoreCase(true); }).PageSettings(page => page.PageCou
nt(2)).Toolbar(new List<string>() { "Search" }).Render()
By default, grid searches all the bound column values. To customize this behavior define
the SearchSettings.Fields property.
Search operators
The search operator can be defined in the SearchSettings.Operator property to configure
specific searching.
Operator Description
821
razor
@Html.EJS().Button("search").Content("Search").Render()
@Html.EJS().Grid("Search").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(
col =>
{
col.Field("CategoryName").HeaderText("Category Name").Width("160").Add();
col.Field("ProductName").HeaderText("Product Name").Width("170").Add();
col.Field("UnitsInStock").HeaderText("Units In Stock").Width("170").TextAlign(Syncf
usion.EJ2.Grids.TextAlign.Right).Add();
col.Field("QuantityPerUnit").HeaderText("Quantity Per Unit").Width("170").TextAlign
(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Discontinued").HeaderText("Discontinued").TextAlign(Syncfusion.EJ2.Grids
.TextAlign.Center).Width("140").Type("boolean").DisplayAsCheckBox(true).Add();
}).AllowPaging()).PageSettings(page=>page.PageCount(2)).Render()
<script>
document.getElementById('search').addEventListener('click', () => {
var gridObj = document.getElementById("Search").ej2_instances[0];
var searchString = "Ha";
gridObj.search(searchString);
});
</script>
razor
search-a-column.cs
@Html.EJS().Grid("Search").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(
col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("160").Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("170").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("170").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("140").Add();
}).AllowPaging().SearchSettings(search => { search.Fields(new string[] { "CustomerID",
"ShipCity", "ShipName" }); }).PageSettings(page => page.PageCount(2)).Toolbar(new List<
string>() { "Search" }).Render()
822
{
var orders=OrderDetails.GetAllRecords();
ViewBag.datasource = orders;
return View();
}
823
Paging
Paging provides an option to display Grid data in page segments. To enable paging, set the
AllowPaging to true. When paging is enabled, pager component renders at the bottom of the
grid. Paging options can be configured through the PageSettings .
razor
page.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowPaging().Render()
You can achieve better performance by using grid paging to fetch only a pre-defined
number of records from the data source.
Template
You can use custom elements inside the pager instead of default elements. The custom
elements can be defined by using the Template property. Inside this template, you can access
the CurrentPage , PageSize , TotalPage and TotalRecordCount values.
razor
page-temp.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
824
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function updateTemplate() {
var numeric;
var grid = document.getElementById("Grid").ej2_instances[0];
numeric = new ej.inputs.NumericTextBox({
min: 1,
max: 3,
step: 1,
format: '###.##',
change: function(args) {
let value = args.value;
grid.goToPage(value);
}
});
numeric.appendTo('#currentPage');
};
var flag = true;
function dataBind() {
if (flag) {
flag = false;
updateTemplate();
}
}
function actionComplete (args) {
if (args.requestType === 'paging') {
updateTemplate();
}
}
</script>
825
</div>
See Also
Group with Paging
826
Scrolling
The scrollbar will be displayed in the grid when content exceeds the element Width or Height .
The vertical and horizontal scrollbars will be displayed based on the following criteria:
The vertical scrollbar appears when the total height of rows present in the grid exceeds its
element height.
The horizontal scrollbar appears when the sum of columns width exceeds the grid element
width.
The Height and Width are used to set the grid height and width, respectively.
razor
width-height.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("4
00").Width("auto").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").T
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipAddress").HeaderText("Ship Address").Width("170").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).Render()
827
ViewBag.datasource = orders;
return View();
}
razor
responsive-parent.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("
100%").Width("auto").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").T
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipAddress").HeaderText("Ship Address").Width("170").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).Render()
razor
828
scroll-selected-row.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height(
"400").Width("auto").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").T
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipAddress").HeaderText("Ship Address").Width("170").Add();
col.Field("ShipCity").HeaderText("Ship City").Width("170").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).RowSelected("rowSelected").Render()
<script>
function onChange(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
gridObj.selectRow(parseInt(this.getText(), 10));
}
function rowSelected(args) {
var rowHeight = this.getRows()[this.getSelectedRowIndexes()[0]].scrollHeigh
t;
this.getContent().children[0].scrollTop = rowHeight * this.getSelectedRowIn
dexes()[0];
}
</script>
829
}
In this demo, the FrozenColumns is set as '2' and the FrozenRows is set as '3'. Hence, the left
two columns and top three rows are frozen.
razor
freeze-row-column.cs
@Html.EJS().Grid("FrozenGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).All
owSelection(false).AllowResizing().Height("410").FrozenRows(2).FrozenColumns(1).Columns
(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").T
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("200").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("130").Format("yMd"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCity").HeaderText("Ship City").Width("200").Add();
col.Field("ShipAddress").HeaderText("Ship Address").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).Render()
830
int code = 10000;
for (int i = 1; i < 10; i++)
{
orders.Add(new OrderDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, n
ew DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7,
16), "Kirchgasse 6"));
orders.Add(new OrderDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new
DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11)
, "Avda. Azteca 123"));
orders.Add(new OrderDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new
DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996,
10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
orders.Add(new OrderDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, n
ew DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12
, 30), "Magazinweg 7"));
orders.Add(new OrderDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new
DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997
, 12, 3), "1029 - 12th Ave. S."));
code += 5;
}
}
In this demo, the columns with field name OrderID and EmployeeID is frozen using the
IsFrozen property.
razor
freeze-column.cs
@Html.EJS().Grid("FrozenGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).
AllowSelection(false).AllowResizing().Height("410").FrozenRows(2).FrozenColumns(1).Colu
mns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").IsFroze
n(true).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").T
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("200").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("130").Format("yMd"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
831
col.Field("ShipCity").HeaderText("Ship City").Width("200").Add();
col.Field("ShipAddress").HeaderText("Ship Address").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).Render()
The AllowScrolling must be true while giving frozen rows and columns.
Frozen rows and columns should not be set outside the grid view port.
Limitations
The following features are not supported in frozen rows and columns:
Grouping
Row Template
Detail Template
Hierarchy Grid
832
Virtualization
Grid allows you to load large amount of data without performance degradation.
Row Virtualization
Row virtualization allows you to load and render rows only in the content viewport. It is an
alternative way of paging in which the data will be loaded while scrolling vertically. To setup the
row virtualization, you need to define EnableVirtualization as true and content height by
Height property.
The number of records displayed in the Grid is determined implicitly by height of the content
area. Also, you have an option to define a visible number of records by the
PageSettings.PageSize property. The loaded data will be cached and reused when it is needed
for next time.
razor
row-virtualization.cs
@Html.EJS().Grid("VirtualGrid").DataBound("hide").EnableVirtualization().Height("50
0").Columns(col =>
{
col.Field("Field1").HeaderText("PlayerName").Width("140").Add();
col.Field("Field2").HeaderText("Year").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
col.Field("Field3").HeaderText("Stint").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Field4").HeaderText("TMID").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
col.Field("Field5").HeaderText("LGID").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
}).Render()
<script>
var virtualData = [], date1=null, date2=null, flag= true;
var names = ['hardire', 'abramjo01', 'aubucch01', 'Hook', 'Rumpelstiltskin', 'B
elle', 'Emma', 'Regina', 'Aurora', 'Elsa',
'Anna', 'Snow White', 'Prince Charming', 'Cora', 'Zelena', 'August', 'Mulan'
, 'Graham', 'Discord', 'Will', 'Robin Hood',
'Jiminy Cricket', 'Henry', 'Neal', 'Red', 'Aaran', 'Aaren', 'Aarez', 'Aarma
n', 'Aaron', 'Aaron-James', 'Aarron', 'Aaryan', 'Aaryn',
'Aayan', 'Aazaan', 'Abaan', 'Abbas', 'Abdallah', 'Abdalroof', 'Abdihakim',
'Abdirahman', 'Abdisalam', 'Abdul', 'Abdul-Aziz',
833
'Abdulbasir', 'Abdulkadir', 'Abdulkarem', 'Abdulkhader', 'Abdullah', 'Abdul
-Majeed', 'Abdulmalik', 'Abdul-Rehman', 'Abdur',
'Abdurraheem', 'Abdur-Rahman', 'Abdur-Rehmaan', 'Abel', 'Abhinav', 'Abhisum
ant', 'Abid', 'Abir', 'Abraham', 'Abu', 'Abubakar',
'Ace', 'Adain', 'Adam', 'Adam-James', 'Addison', 'Addisson', 'Adegbola', 'A
degbolahan', 'Aden', 'Adenn', 'Adie', 'Adil', 'Aditya',
'Adnan', 'Adrian', 'Adrien', 'Aedan', 'Aedin', 'Aedyn', 'Aeron', 'Afonso',
'Ahmad', 'Ahmed', 'Ahmed-Aziz', 'Ahoua', 'Ahtasham',
'Aiadan', 'Aidan', 'Aiden', 'Aiden-Jack', 'Aiden-Vee'];
document.getElementById("generate").addEventListener('click', () => {
})
function show() {
document.getElementById('popup').style.display = 'inline-block';
}
function hide(args) {
834
});
}
}
</script>
return View();
}
Column Virtualization
Column virtualization allows you to virtualize columns. It will render columns which are in the
viewport. You can scroll horizontally to view more columns.
razor
Column-virtualization.cs
@Html.EJS().Grid("VirtualGrid").DataBound("hide").EnableColumnVirtualization().Enab
leVirtualization().Height("500").Columns(col =>
{
col.Field("Field1").HeaderText("PlayerName").Width("140").Add();
col.Field("Field2").HeaderText("Year").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
col.Field("Field3").HeaderText("Stint").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Field4").HeaderText("TMID").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
col.Field("Field5").HeaderText("LGID").Width("120").TextAlign(Syncfusion.EJ2.Gri
ds.TextAlign.Right).Add();
col.Field("Field6").HeaderText("GP").Width("120").TextAlign(Syncfusion.EJ2.Grids
.TextAlign.Right).Add();
col.Field("Field7").HeaderText("GS").Width("120").TextAlign(Syncfusion.EJ2.Grids
.TextAlign.Right).Add();
col.Field("Field8").HeaderText("Minutes").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
835
col.Field("Field9").HeaderText("Points").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("Field10").HeaderText("oRebounds").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("Field11").HeaderText("dRebounds").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("Field12").HeaderText("Rebounds").Width("130").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("Field13").HeaderText("Assists").Width("120").TextAlign(Syncfusion.EJ2
.Grids.TextAlign.Right).Add();
col.Field("Field14").HeaderText("Steals").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field15").HeaderText("Blocks").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field16").HeaderText("Turnovers").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("Field17").HeaderText("PF").Width("120").TextAlign(Syncfusion.EJ2.Grid
s.TextAlign.Right).Add();
col.Field("Field18").HeaderText("fgAttempted").Width("150").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field19").HeaderText("fgMade").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field20").HeaderText("ftAttempted").Width("150").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field21").HeaderText("ftMade").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field22").HeaderText("ThreeAttempted").Width("150").TextAlign(Syncfus
ion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field23").HeaderText("ThreeMade").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Add();
col.Field("Field24").HeaderText("PostGP").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field25").HeaderText("PostGS").Width("120").TextAlign(Syncfusion.EJ2.
Grids.TextAlign.Right).Add();
col.Field("Field26").HeaderText("PostMinutes").Width("120").TextAlign(Syncfusion
.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field27").HeaderText("PostPoints").Width("130").TextAlign(Syncfusion.
EJ2.Grids.TextAlign.Right).Add();
col.Field("Field28").HeaderText("PostoRebounds").Width("130").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field29").HeaderText("PostdRebounds").Width("130").TextAlign(Syncfusi
on.EJ2.Grids.TextAlign.Right).Add();
col.Field("Field30").HeaderText("PostRebounds").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Add();
}).Render()
<script>
var virtualData = [], date1=null, date2=null, flag= true;
836
var names = ['hardire', 'abramjo01', 'aubucch01', 'Hook', 'Rumpelstiltskin', 'B
elle', 'Emma', 'Regina', 'Aurora', 'Elsa',
'Anna', 'Snow White', 'Prince Charming', 'Cora', 'Zelena', 'August', 'Mulan'
, 'Graham', 'Discord', 'Will', 'Robin Hood',
'Jiminy Cricket', 'Henry', 'Neal', 'Red', 'Aaran', 'Aaren', 'Aarez', 'Aarma
n', 'Aaron', 'Aaron-James', 'Aarron', 'Aaryan', 'Aaryn',
'Aayan', 'Aazaan', 'Abaan', 'Abbas', 'Abdallah', 'Abdalroof', 'Abdihakim',
'Abdirahman', 'Abdisalam', 'Abdul', 'Abdul-Aziz',
'Abdulbasir', 'Abdulkadir', 'Abdulkarem', 'Abdulkhader', 'Abdullah', 'Abdul
-Majeed', 'Abdulmalik', 'Abdul-Rehman', 'Abdur',
'Abdurraheem', 'Abdur-Rahman', 'Abdur-Rehmaan', 'Abel', 'Abhinav', 'Abhisum
ant', 'Abid', 'Abir', 'Abraham', 'Abu', 'Abubakar',
'Ace', 'Adain', 'Adam', 'Adam-James', 'Addison', 'Addisson', 'Adegbola', 'A
degbolahan', 'Aden', 'Adenn', 'Adie', 'Adil', 'Aditya',
'Adnan', 'Adrian', 'Adrien', 'Aedan', 'Aedin', 'Aedyn', 'Aeron', 'Afonso',
'Ahmad', 'Ahmed', 'Ahmed-Aziz', 'Ahoua', 'Ahtasham',
'Aiadan', 'Aidan', 'Aiden', 'Aiden-Jack', 'Aiden-Vee'];
document.getElementById("generate").addEventListener('click', () => {
})
function show() {
document.getElementById('popup').style.display = 'inline-block';
}
function hide(args) {
837
function dataSource() {
for (var i= 0; i < 100000; i++) {
virtualData.push({
'Field1': names[Math.floor(Math.random() * names.length)],
'Field2': 1967 + (i % 10),
'Field3': Math.floor(Math.random() * 200),
'Field4': Math.floor(Math.random() * 100),
'Field5': Math.floor(Math.random() * 2000),
'Field6': Math.floor(Math.random() * 1000),
'Field7': Math.floor(Math.random() * 100),
'Field8': Math.floor(Math.random() * 10),
'Field9': Math.floor(Math.random() * 10),
'Field10': Math.floor(Math.random() * 100),
'Field11': Math.floor(Math.random() * 100),
'Field12': Math.floor(Math.random() * 1000),
'Field13': Math.floor(Math.random() * 10),
'Field14': Math.floor(Math.random() * 10),
'Field15': Math.floor(Math.random() * 1000),
'Field16': Math.floor(Math.random() * 200),
'Field17': Math.floor(Math.random() * 300),
'Field18': Math.floor(Math.random() * 400),
'Field19': Math.floor(Math.random() * 500),
'Field20': Math.floor(Math.random() * 700),
'Field21': Math.floor(Math.random() * 800),
'Field22': Math.floor(Math.random() * 1000),
'Field23': Math.floor(Math.random() * 2000),
'Field24': Math.floor(Math.random() * 150),
'Field25': Math.floor(Math.random() * 1000),
'Field26': Math.floor(Math.random() * 100),
'Field27': Math.floor(Math.random() * 400),
'Field28': Math.floor(Math.random() * 600),
'Field29': Math.floor(Math.random() * 500),
'Field30': Math.floor(Math.random() * 300),
});
}
}
</script>
838
public void DataSource()
{
int code = 10000;
for (int i = 1; i < 10; i++)
{
orders.Add(new OrderDetails(code + 1, "ALFKI", i + 0, 2.3 * i, false, n
ew DateTime(1991, 05, 15), "Berlin", "Simons bistro", "Denmark", new DateTime(1996, 7,
16), "Kirchgasse 6"));
orders.Add(new OrderDetails(code + 2, "ANATR", i + 2, 3.3 * i, true, new
DateTime(1990, 04, 04), "Madrid", "Queen Cozinha", "Brazil", new DateTime(1996, 9, 11)
, "Avda. Azteca 123"));
orders.Add(new OrderDetails(code + 3, "ANTON", i + 1, 4.3 * i, true, new
DateTime(1957, 11, 30), "Cholchester", "Frankenversand", "Germany", new DateTime(1996,
10, 7), "Carrera 52 con Ave. Bolívar #65-98 Llano Largo"));
orders.Add(new OrderDetails(code + 4, "BLONP", i + 3, 5.3 * i, false, n
ew DateTime(1930, 10, 22), "Marseille", "Ernst Handel", "Austria", new DateTime(1996, 12
, 30), "Magazinweg 7"));
orders.Add(new OrderDetails(code + 5, "BOLID", i + 4, 6.3 * i, true, new
DateTime(1953, 02, 18), "Tsawassen", "Hanari Carnes", "Switzerland", new DateTime(1997
, 12, 3), "1029 - 12th Ave. S."));
code += 5;
}
}
Column's Width is required for column virtualization. If column's width is not defined then
Grid will consider its value as 200px .
839
items, refer to the Group with Page topic.
The page size provided must be two times larger than the number of visible rows in the grid.
If the page size is failed to meet this condition then the size will be determined by grid.
The height of the grid content is calculated using the row height and total number of records
in the data source and hence features which changes row height such as text wrapping are
not supported. If you want to increase the row height to accommodate the content then you
can specify the row height as below to ensure all the table rows are in same height.
.e-grid .e-row {
height: 2em;
}
Programmatic selection using the selectRows method is not supported in virtual scrolling.
840
Selection
Selection provides an option to highlight a row or a cell. It can be done through simple mouse
down or arrow keys. To disable selection in the Grid, set the AllowSelection to false.
The grid supports two types of selection that can be set by using the SelectionSettings.Type .
They are:
Single : The Single value is set by default, and it only allows selection of a single row or a
cell.
Multiple : Allows you to select multiple rows or cells. To perform the multi-selection, press
and hold CTRL key and click the desired rows or cells. To select range of rows or cells,
press and hold the SHIFT key and click the rows or cells.
razor
selection.cs
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.dataSource).A
llowSelection().Columns(col =>
{
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
Selection mode
841
The grid supports three types of selection mode that can be set by using the
SelectionSettings.Mode . They are:
Row : The Row value is set by default, and allows you to select only rows.
Cell : Allows you to select only cells.
Both : Allows you to select rows and cells at the same time.
razor
selection-mode.cs
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.dataSource).Al
lowSelection().Columns(col =>
{
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
Cell selection
Cell selection can be done through simple mouse down or arrow keys (up, down, left, and right).
The grid supports two types of cell selection mode that can be set by using the
SelectionSettings.CellSelectionMode . They are:
Flow : The Flow value is set by default. The range of cells are selected between the start
index and end index that includes in between cells of rows.
Box : Range of cells are selected from the start and end column indexes that includes in
between cells of rows within the range.
razor
842
cell-selection.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowS
election().Columns(col =>
{
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
Checkbox selection
Checkbox selection provides an option to select multiple grid records with help of checkbox in
each row.
To render the checkbox in each grid row, you need to use checkbox column with type as
checkbox using the column Type property.
razor
checkbox.cs
@Html.EJS().Grid("CheckboxSelection").DataSource((IEnumerable<object>)ViewBag.dataSou
rce).Columns(col =>
{
col.Type("checkbox").Width("50").Add();
843
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
}).AllowPaging().PageSettings(page => page.PageCount(2)).Render()
By default, selection is allowed by clicking a grid row or checkbox in that row. To allow
selection only through checkbox, you can set the SelectionSettings.CheckboxOnly
property to true.
Selection can be persisted in all the operations using the
SelectionSettings.PersistSelection property. For persisting selection on the grid,
any one of the columns should be defined as a primary key using the
Columns.IsPrimaryKey property.
razor
select-row.cs
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.dataSource).Al
lowSelection().Columns(col =>
{
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
844
ettings(page => page.PageCount(2)).Render()
razor
selected-row-index.cs
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.dataSource
).RowSelected("rowSelected").AllowSelection().Columns(col =>
{
col.Field("Inventor").HeaderText("Inventor Name").Width("180").Add();
col.Field("NumberofPatentFamilies").HeaderText("No of Patent Families").Width("195"
).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Country").HeaderText("Country").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("Active").HeaderText("Active").Width("130").Add();
<script>
function rowSelected(args){
var grid = document.getElementById("SelectionAPI").ej2_instances[0];
var selectedrowindex= grid.getSelectedRowIndexes(); // get the selected row indexe
s.
alert(selectedrowindex); // to alert the selected row indexes.
var selectedrecords = grid.getSelectedRecords(); // get the selected records.
}
</script>
845
public IActionResult Index()
{
var orders=OrderDetails.GetAllRecords();
ViewBag.datasource = orders;
return View();
}
Touch interaction
When you tap a grid row on touchscreen device, the tapped row is selected. It also shows a
popup for multi-row selection. To select multiple rows or cells, tap the popup and
then tap the desired rows or cells.
846
Aggregates
Aggregate values are displayed in the footer, group footer, or group caption of the Grid. It can be
configured through Aggregates property. Field and Type are the minimum properties
required to represent an aggregate column.
By default, the aggregate value can be displayed in the footer, group, and caption cells. To show
the aggregate value in one of the cells, use the FooterTemplate , GroupFooterTemplate , or
GroupCaptionTemplate property.
Sum
Average
Min
Max
Count
TrueCount
FalseCount
Multiple aggregates can be used for an aggregate column by setting the Type
property with an array of aggregate types.
Multiple types for a column is supported only when one of the aggregate templates is
used.
Footer aggregate
Footer aggregate value is calculated for all the rows, and it is displayed in the footer cells. Use
the FooterTemplate property to render the aggregate value in footer cells.
razor
footer-agg.cs
@Html.EJS().Grid("Footer").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns
(col =>
{
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("160").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
847
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("140").Add();
The aggregate values must be accessed inside the template using their corresponding
Type name.
razor
format-agg.cs
@Html.EJS().Grid("FormatAggregate").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Columns(col =>
{
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("160").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("140").Add();
848
public IActionResult Index()
{
var Order = Product.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
razor
group-caption.cs
@Html.EJS().Grid("GroupCaption").DataSource((IEnumerable<object>)ViewBag.dataSource).Co
lumns(col =>
{
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("160").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("140").Add();
849
}
The aggregate values must be accessed inside the template using their corresponding
Type name.
Custom aggregate
To calculate the aggregate value with your own aggregate functions, use the custom aggregate
option. To use custom aggregation, specify the Type as Custom , and provide the custom
aggregate function in the CustomAggregate property.
The custom aggregate function will be invoked with different arguments for total and group
aggregations.
Total aggregation: The custom aggregate function will be called with the whole data and
current AggregateColumn object.
Group aggregation: This will be called with the current group details and AggregateColumn
object.
razor
@Html.EJS().Grid("DefaultAggregate").DataSource((IEnumerable<object>)ViewBag.dataSource
).Columns(col =>
{
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("160").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("140").Add();
<script>
function customAggregateFn(data) {
return data.result.filter(function (item) {
return item['ShipCountry'] === 'Brazil';
}).length;
}
</script>
To access the custom aggregate value inside the template, use the key as Custom .
850
Print
To print the Grid, use the print method from grid instance. The print option can be displayed
on the Toolbar by adding the Print toolbar item.
razor
print.cs
@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
Page setup
Some of the print options cannot be configured through JavaScript code. So, you have to
customize the layout, paper size, and margin options using the browser page setup dialog.
Please refer to the following links to know more about the browser page setup:
Chrome
Firefox
Safari
IE
851
razor
external-btn.cs
@Html.EJS().Button("printbtn").Content("Print").IsPrimary(true).Render();
@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().Render()
<script>
document.getElementById('printbtn').onclick = function () {
document.getElementById('Grid').ej2_instances[0].print();
}
</script>
razor
current-page.cs
@Html.EJS().Grid("Print").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(
col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
852
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
853
State Persistence
State persistence refers to the Grid's state maintained in the browser's localStorage even if the
browser is refreshed or if you move to the next page within the browser. State persistence stores
grid’s model object in the local storage when the EnablePersistence is defined as true.
razor
state-persist.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowF
iltering(true).EnablePersistence(true).ActionBegin("actionBegin").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("170").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
<script>
function actionBegin(args) {
this.query.addParams('$filter', 'EmployeeID eq 1');
}
</script>
854
Get or set localStorage value
If the EnablePersistance property is set to true, the grid property value is saved in the
window.localStorage for reference. You can get/set the localStorage value by using the
getItem / setItem method in the window.localStorage .
855
ToolBar
The Grid provides ToolBar support to handle grid actions. The Toolbar property accepts either
the collection of built-in toolbar items and ItemModel objects for custom toolbar items or HTML
element ID for toolbar template.
The following table shows built-in toolbar items and its actions.
razor
toolbar.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").
Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropd
ownedit").Add();
856
}).AllowPaging().PageSettings(page => page.PageCount(2)).Toolbar(new List<string>()
{ "Print", "Search" }).Render()
The Toolbar has options to define both built-in and custom toolbar items.
razor
custom-toolbar-item.cs
@{
List<object> toolbarItems = new List<object>();
toolbarItems.Add(new { text = "Expand All", tooltipText = "Expand All", prefixI
con = "e-expand", id = "expandall" });
toolbarItems.Add(new { text = "Collapse All", tooltipText = "Collapse All", pre
fixIcon = "e-collapse", id = "collapseall" });
}
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Toolba
rClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").
Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropd
ownedit").Add();
857
<script>
function toolbarClick(args){
}
</script>
The Toolbar has options to define both built-in and custom toolbar items.
If a toolbar item does not match the built-in items, it will be treated as a custom toolbar
item.
razor
enable-disable.cs
@Html.EJS().Button("disable").Content("Disable").Render()
@Html.EJS().Button("enable").Content("Enable").Render()
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Toolba
rClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").EditType("numericedit").For
mat("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
858
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropdown
edit").Add();
<script>
document.getElementById("enable").addEventListener('click', () => {
document.getElementById("disable").addEventListener('click', () => {
function toolbarClick(args){
}
</script>
859
PDF Export
PDF export allows exporting Grid data to PDF document. You need to use the PdfExport
method for exporting. To enable PDF export in the grid, set the AllowPdfExport as true.
razor
pdf-export.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdf
Export().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
gridObj.pdfExport();
}
}
</script>
Multiple exporting
PDF export provides an option for exporting multiple grids to same file. In this exported
document, each grid will be exported to new page of document in same file.
860
razor
multiple.cs
@Html.EJS().Grid("FirstGrid").DataSource((IEnumerable<object>)ViewBag.FirstGridData).
AllowPdfExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
@Html.EJS().Grid("SecondGrid").DataSource((IEnumerable<object>)ViewBag.SecondGridDa
ta).AllowExcelExport().Columns(col =>
{
col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right
).Add();
col.Field("FirstName").Width("140").Add();
col.Field("BirthDate").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right)
.Add();
col.Field("City").Width("120").Add();
col.Field("Country").Width("140").Add();
}).AllowPaging().Render()
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("FirstGrid").ej2_instances[0];
if (args.item.id === 'FirstGrid_pdfexport') {
var firstGridPdfExport = firstGrid.pdfExport({}, true);
firstGridPdfExport.then((pdfData) => {
secondGrid.pdfExport({}, false, pdfData);
});
}
}
</script>
861
return View();
}
You can add text either in Header or Footer of exported PDF document.
var exportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Text',
value: "Northwind Traders",
position: { x: 0, y: 50 },
style: { textBrushColor: '#000000', fontSize: 13 }
},
]
}
you can add line either in Header or Footer of the exported PDF document.
dash
dot
dashdot
dashdotdot
solid
862
var exportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Line',
style: { penColor: '#000080', penSize: 2, dashStyle: 'Solid' },
points: { x1: 0, y1: 4, x2: 685, y2: 4 }
}
]
}
}
LowerLatin - a, b, c,
UpperLatin - A, B, C,
LowerRoman - i, ii, iii,
UpperRoman - I, II, III,
Number - 1,2,3.
var exportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'PageNumber',
pageNumberType: 'Arabic',
format: 'Page {$current} of {$total}', //optional
position: { x: 0, y: 25 },
style: { textBrushColor: '#ffff80', fontSize: 15, hAlign: 'Center' }
}
]
}
}
Image (Base64 string) can be added in the exported document in header/footer using the
exportProperties .
863
var exportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Image',
src: image,
position: { x: 435, y: 10 },
size: { height: 100, width: 250 },
}
]
}
}
razor
header-footer.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfE
xport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args['item'].id === 'Grid_pdfexport') {
var pdfExportProperties = {
header: {
fromTop: 0,
height: 130,
contents: [
{
type: 'Text',
value: "Northwind Traders",
864
position: { x: 0, y: 50 },
style: { textBrushColor: '#000000', fontSize: 13 }
}
]
},
footer: {
fromBottom: 160,
height: 150,
contents: [
{
type: 'PageNumber',
pageNumberType: 'arabic',
format: 'Page {$current} of {$total}',
position: { x: 0, y: 25 },
style: { textBrushColor: '#ffff80', fontSize: 15 }
}
]
}
};
grid.pdfExport(pdfExportProperties);
}
}
</script>
razor
orientation.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfE
xport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
865
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var exportProperties = {
pageOrientation: 'Landscape',
};
grid.pdfExport(exportProperties);
}
}
</script>
Letter
Note
Legal
A0
A1
A2
A3
A5
A6
A7
A8
A9
B0
866
B1
B2
B3
B4
B5
Archa
Archb
Archc
Archd
Arche
Flsa
HalfLetter
Letter11x17
Ledger
razor
page-size.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfE
xport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var exportProperties = {
pageSize: 'Letter'
};
grid.pdfExport(exportProperties);
}
}
</script>
867
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
razor
export-current.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowP
dfExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var exportProperties = {
exportType: 'CurrentPage'
};
gridObj.pdfExport(exportProperties);
}
}
</script>
868
}
razor
export-hidden.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfE
xport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Visible(false).Width("120").
Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var exportProperties = {
includeHiddenColumn: true
};
gridObj.pdfExport(exportProperties);
}
}
</script>
Theme
869
PDF export provides an option to include theme for exported PDF document.
razor
theme.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfE
xport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var exportProperties = {
theme: {
header: {
fontColor: '#64FA50', fontName: 'Calibri', fontSize: 17, bold:
true, borders: { color: '#64FA50', lineStyle: 'Thin' }
},
record: {
fontColor: '#64FA50', fontName: 'Calibri', fontSize: 17, bold:
true
},
caption: {
fontColor: '#64FA50', fontName: 'Calibri', fontSize: 17, bold:
true
}
}
};
gridObj.pdfExport(exportProperties);
}
}
</script>
870
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
razor
custom-data.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowPdfEx
port().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_pdfexport') {
var data = [
{ OrderID: "100", CustomerID: "Vinet", Freight: "2.00", OrderDate: new
Date() },
{ OrderID: "101", CustomerID: "Hanar", Freight: "2.01", OrderDate: new
Date() },
{ OrderID: "102", CustomerID: "Mega", Freight: "4.48", OrderDate: new D
ate() },
{ OrderID: "103", CustomerID: "Sam", Freight: "19.23", OrderDate: new D
ate() }
];
var pdfExportProperties = {
dataSource: data
};
gridObj.pdfExport(pdfExportProperties);
871
}
}
</script>
872
Excel Export
The excel export allows exporting Grid data to Excel document. You need to use the
ExcelExport method for exporting. To enable Excel export in the grid, set the
AllowExcelExport as true.
To use excel export, You need to define the ExcelExport in inbuild toolbar and define the
toolbarClick event for exporting the Grid.
razor
excel-export.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowExce
lExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
gridObj.excelExport();
}
}
</script>
873
The excel export provides an option to export multiple grid data in the same excel file.
Same sheet
The excel export provides support to export multiple grids in same sheet. To export in same
sheet, define multipleExport.type as AppendToSheet in exportProperties . It have an option
to provide blank rows between grids. These blank rows count can be defined by using
the multipleExport.blankRows .
razor
same-sheet.cs
@Html.EJS().Grid("FirstGrid").DataSource((IEnumerable<object>)ViewBag.FirstGridData).A
llowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
@Html.EJS().Grid("SecondGrid").DataSource((IEnumerable<object>)ViewBag.SecondGridDa
ta).AllowExcelExport().Columns(col =>
{
col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right
).Add();
col.Field("FirstName").Width("140").Add();
col.Field("BirthDate").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right)
.Add();
col.Field("City").Width("120").Add();
col.Field("Country").Width("140").Add();
}).AllowPaging().Render()
<script>
function toolbarClick(args) {
if(args.item.id === 'FirstGrid_excelexport'){
var firstGrid = document.getElementById("FirstGrid").ej2_instances[0];
var secondGrid = document.getElementById("SecondGrid").ej2_instances[0];
var appendExcelExportProperties = {
multipleExport: { type: 'AppendToSheet', blankRows: 2 }
};
874
var firstGridExport = firstGrid.excelExport(appendExcelExportProperties, tr
ue);
firstGridExport.then((fData) => {
secondGrid.excelExport(appendExcelExportProperties, false, fData);
});
}
}
</script>
New Sheet
Excel exporting provides support to export multiple grids in new sheet. To export in new sheet,
define multipleExport.type as NewSheet in exportProperties .
razor
new-sheet.cs
@Html.EJS().Grid("FirstGrid").DataSource((IEnumerable<object>)ViewBag.FirstGridData).Al
lowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
@Html.EJS().Grid("SecondGrid").DataSource((IEnumerable<object>)ViewBag.SecondGr
idData).AllowExcelExport().Columns(col =>
{
col.Field("EmployeeID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right
).Add();
875
col.Field("FirstName").Width("140").Add();
col.Field("BirthDate").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right)
.Add();
col.Field("City").Width("120").Add();
col.Field("Country").Width("140").Add();
}).AllowPaging().Render()
<script>
function toolbarClick(args) {
if(args.item.id === 'FirstGrid_excelexport'){
var firstGrid = document.getElementById("FirstGrid").ej2_instances[0];
var secondGrid = document.getElementById("SecondGrid").ej2_instances[0];
var appendExcelExportProperties = {
multipleExport: { type: 'NewSheet' }
};
razor
export-current.cs
876
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowE
xcelExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
var excelExportProperties = {
exportType: 'CurrentPage'
};
gridObj.excelExport(excelExportProperties);
}
}
</script>
razor
export-hidden.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Al
lowExcelExport().ToolbarClick("toolbarClick").Columns(col =>
877
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").Visible(fal
se).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
var excelExportProperties = {
includeHiddenColumn: true
};
gridObj.excelExport(excelExportProperties);
}
}
</script>
Theme
The excel export provides an option to include theme for exported excel document.
razor
theme.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowExcel
Export().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
878
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
var excelExportProperties = {
theme:{
header: { fontName: 'Segoe UI', fontColor: '#666666' },
record: { fontName: 'Segoe UI', fontColor: '#666666' },
caption: { fontName: 'Segoe UI', fontColor: '#666666' }
}
};
gridObj.excelExport(excelExportProperties);
}
}
</script>
razor
header-footer.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowExcel
Export().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
879
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
var excelExportProperties = {
header: {
headerRows: 7,
rows: [
{ cells: [{ colSpan: 4, value: "Northwind Traders", style: { fo
ntColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, } }] },
{ cells: [{ colSpan: 4, value: "2501 Aerial Center Parkway", st
yle: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] },
{ cells: [{ colSpan: 4, value: "Suite 200 Morrisville, NC 27560
USA", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }]
},
{ cells: [{ colSpan: 4, value: "Tel +1 888.936.8638 Fax +1 919.
573.0306", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, }
}] },
{ cells: [{ colSpan: 4, hyperlink: { target: 'https://www.north
wind.com/', displayText: 'www.northwind.com' }, style: { hAlign: 'Center' } }] },
{ cells: [{ colSpan: 4, hyperlink: { target: 'mailto:support@no
rthwind.com' }, style: { hAlign: 'Center' } }] },
]
},
footer: {
footerRows: 4,
rows: [
{ cells: [{ colSpan: 4, value: "Thank you for your business!",
style: { hAlign: 'Center', bold: true } }] },
{ cells: [{ colSpan: 4, value: "!Visit Again!", style: { hAlign
: 'Center', bold: true } }] }
]
},
};
gridObj.excelExport(excelExportProperties);
}
}
</script>
880
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
razor
custom-data.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowEx
celExport().ToolbarClick("toolbarClick").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
<script>
function toolbarClick(args) {
var gridObj = document.getElementById("Grid").ej2_instances[0];
if (args.item.id === 'Grid_excelexport') {
var data = [
{ OrderID: "100", CustomerID: "Vinet", Freight: "2.00", OrderDate: new
Date() },
{ OrderID: "101", CustomerID: "Hanar", Freight: "2.01", OrderDate: new
Date() },
{ OrderID: "102", CustomerID: "Mega", Freight: "4.48", OrderDate: new D
ate() },
{ OrderID: "103", CustomerID: "Sam", Freight: "19.23", OrderDate: new D
ate() }
];
var excelExportProperties = {
dataSource: data
881
};
gridObj.excelExport(excelExportProperties);
}
}
</script>
882
Globalization
Localization
The Localization library allows you to localize default text content of the Grid. The grid
component has static text on some features (like group drop area text, pager information text,
etc.) that can be changed to other cultures (Arabic, Deutsch, French, etc.) by defining the
[ Locale ] value and translation object.
The following list of properties and its values are used in the grid.
True true
False false
Loading translations
To load translation object in an application, use load function of the L10n class.
razor
localization.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Add
();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
883
}).AllowPaging().AllowGrouping().Locale("de-DE").PageSettings(page => page.PageSize(
6)).Render()
<script>
ej.base.L10n.load({
'de-DE': {
'grid': {
'EmptyRecord': 'Keine Aufzeichnungen angezeigt',
'GroupDropArea': 'Ziehen Sie einen Spaltenkopf hier, um die Gruppe
ihre Spalte',
'UnGroup': 'Klicken Sie hier, um die Gruppierung aufheben',
'EmptyDataSourceError': 'DataSource darf bei der Erstauslastung nic
ht leer sein, da Spalten aus der dataSource im AutoGenerate Spaltenraster',
'Item': 'Artikel',
'Items': 'Artikel'
},
'pager': {
'currentPageInfo': '{0} von {1} Seiten',
'totalItemsInfo': '({0} Beiträge)',
'firstPageTooltip': 'Zur ersten Seite',
'lastPageTooltip': 'Zur letzten Seite',
'nextPageTooltip': 'Zur nächsten Seite',
'previousPageTooltip': 'Zurück zur letzten Seit',
'nextPagerTooltip': 'Zum nächsten Pager',
'previousPagerTooltip': 'Zum vorherigen Pager'
}
}
});
</script>
Internationalization
The Internationalization library is used to globalize number, date, and time values in grid
component using format strings in the Format .
razor
internationalization.cs
884
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Add
();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("Freight").HeaderText("Ship Name").Format("C2").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
<script>
ej.base.L10n.load({
'de-DE': {
'grid': {
'EmptyRecord': 'Keine Aufzeichnungen angezeigt',
'GroupDropArea': 'Ziehen Sie einen Spaltenkopf hier, um die Gruppe
ihre Spalte',
'UnGroup': 'Klicken Sie hier, um die Gruppierung aufheben',
'EmptyDataSourceError': 'DataSource darf bei der Erstauslastung nic
ht leer sein, da Spalten aus der dataSource im AutoGenerate Spaltenraster',
'Item': 'Artikel',
'Items': 'Artikel'
},
'pager': {
'currentPageInfo': '{0} von {1} Seiten',
'totalItemsInfo': '({0} Beiträge)',
'firstPageTooltip': 'Zur ersten Seite',
'lastPageTooltip': 'Zur letzten Seite',
'nextPageTooltip': 'Zur nächsten Seite',
'previousPageTooltip': 'Zurück zur letzten Seit',
'nextPagerTooltip': 'Zum nächsten Pager',
'previousPagerTooltip': 'Zum vorherigen Pager'
}
}
});
</script>
885
In the above sample, Freight column is formatted by NumberFormatOptions .
By default, [ locale ] value is en-US . If you want to change the en-US culture to a
different culture, you have to change the [ locale ] accordingly.
razor
righttoleft.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Column
s(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Add
();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().AllowGrouping().EnableRtl(true).Locale("de-DE").PageSettings(page
=> page.PageSize(6)).Render()
<script>
ej.base.L10n.load({
'de-DE': {
'grid': {
'EmptyRecord': 'Keine Aufzeichnungen angezeigt',
'GroupDropArea': 'Ziehen Sie einen Spaltenkopf hier, um die Gruppe
ihre Spalte',
'UnGroup': 'Klicken Sie hier, um die Gruppierung aufheben',
'EmptyDataSourceError': 'DataSource darf bei der Erstauslastung nic
ht leer sein, da Spalten aus der dataSource im AutoGenerate Spaltenraster',
'Item': 'Artikel',
'Items': 'Artikel'
},
'pager': {
'currentPageInfo': '{0} von {1} Seiten',
'totalItemsInfo': '({0} Beiträge)',
'firstPageTooltip': 'Zur ersten Seite',
'lastPageTooltip': 'Zur letzten Seite',
'nextPageTooltip': 'Zur nächsten Seite',
'previousPageTooltip': 'Zurück zur letzten Seit',
'nextPagerTooltip': 'Zum nächsten Pager',
886
'previousPagerTooltip': 'Zum vorherigen Pager'
}
}
});
</script>
See Also
Internationalization
Localization
887
Accessibility
Accessibility is achieved in the Grid component through WAI-ARIA standard and keyboard
navigations. The Grid features can be effectively accessed through assistive technologies such
as screen readers.
WAI-ARIA
WAI-ARIA (Accessibility Initiative – Accessible Rich Internet Applications) defines a way to
increase the accessibility of web pages, dynamic content, and user interface components
developed with Ajax, HTML, JavaScript, and related technologies. ARIA provides additional
semantics to describe the role, state, and functionality of web components.
grid (role)
row (role)
gridcell (role)
aria-selected (attribute)
aria-expanded (attribute)
aria-sort (attribute)
aria-busy (attribute)
aria-invalid (attribute)
aria-grabbed (attribute)
aria-owns (attribute)
aria-label (attribute)
Keyboard navigation
Grid functionalities can be interactive with keyboard shortcuts.
Interaction
Description
Keys
PageDown Goes to the next page.
PageUp Goes to the previous page.
Ctrl + Alt
+PageDown Goes to the last page.
Ctrl + Alt
+ PageUp Goes to the first page.
888
Alt + Goes to the next page.
PageDown
Alt +
Goes to the previous page.
PageUp
Ctrl +
Goes to the first row.
Home
Shift +
Extends the row/cell selection downwards.
DownArrow
Shift +
UpArrow Extends the row/cell selection upwards.
Shift +
LeftArrow Extends the cell selection to the left side.
Shift +
RightArrow Extends the cell selection to the right side.
Moves the row/cell selection downward. If current cell is in edit state, then
completes the editing. If the current cell is a header then performs sorting.
Enter If the current cell is an expand/collapse cell then expands/collapses the
current group/detailrow/childgrid. If the current cell is a detailrow, child grid
or command column then the focus will be moved to the focusable
element inside the cell.
Shift + Moves the row/cell selection upward. If the current cell is a header then
Enter clears sorting for the selected column.
Ctrl +
Enter If the current cell is a header then performs multi-sorting.
Shift +
Moves the cell selection left side.
Tab
889
LeftArrow Moves to the left cell selection.
Alt +
Expands the selected group.
DownArrow
Ctrl +
Expands all the visible groups.
DownArrow
Alt +
UpArrow Collapses the selected group.
Ctrl +
UpArrow Collapses all the visible groups.
Ctrl +
Shift + H Copy selected rows or cells data with header into clipboard
890
Clipboard
The clipboard provides an option to copy selected rows or cells data into the clipboard.
The following list of keyboard shortcuts is supported in the Grid to copy selected rows or cells
data into the clipboard.
Ctrl + Shift + H Copy selected rows or cells data with header into clipboard.
razor
local.cs
@Html.EJS().Grid("Clipboard").DataSource((IEnumerable<object>)ViewBag.DataSource).Colum
ns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").TextAlign(Syncfusion.EJ2.Gr
ids.TextAlign.Right).Format("C2").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
891
razor
local.cs
@Html.EJS().Button("Copy").Content("Copy").IsPrimary(true).Render()
@Html.EJS().Button("CopyHeader").Content("Copy With Header").IsPrimary(true).Render()
@Html.EJS().Grid("CopyBtn").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns
(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").TextAlign(Syncfusion.EJ2.Grids.TextAlign
.Right).Width("120").Format("C2").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().Render()
<script>
document.getElementById("Copy").onclick = function () {
var grid = document.getElementById("CopyBtn").ej2_instances[0];
grid.copy();
}
document.getElementById("CopyHeader").onclick = function () {
var grid = document.getElementById("CopyBtn").ej2_instances[0];
grid.copy(true);
}
</script>
892
Context menu
The Grid has options to show the context menu when right clicked on it. To enable this feature,
you need to define either default or custom item in the ContextMenuItems .
Items Description
razor
contextmenu.cs
@Html.EJS().Grid("ContextMenu").DataSource((IEnumerable<object>)ViewBag.DataSource).All
owSorting(true).AllowExcelExport(true).AllowPdfExport(true).EditSettings(edit => edit.A
llowAdding(true).AllowEditing(true).AllowDeleting(true)).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").IsPrimaryKey(true).TextAli
gn(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
893
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlig
n(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
razor
customcontextmenu.cs
@{
List<object> ContextMenuitems = new List<object>();
ContextMenuitems.Add(new { text = "Copy with headers", target = ".e-content", id
= "copywithheader" });
}
@Html.EJS().Grid("Customcontext").DataSource((IEnumerable<object>)ViewBag.DataSource).C
olumns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextA
lign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShippedDate").HeaderText("Shipped Date").Width("140").Format("yMd").T
894
extAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
}).AllowPaging().ContextMenuItems(ContextMenuitems).ContextMenuClick("ContextMenuCli
ck").Render()
<script>
function ContextMenuClick(args) {
if (args.item.id === 'copywithheader') {
this.copy(true);
}
}
</script>
You can hide or show an item in context menu for specific area inside of grid by defining the
Target property.
895
How To
While performing grid save operation, you can send anti-forgery token along with the save
request using the below custom adaptor.
This custom adaptor will read the anti-forgery token from the hidden element and send it along
with the request. Also content type is set to application/x-www-form-urlencoded; charset=UTF-8
since the ValidateAntiForgeryToken will look for the token in the form encoded data.
<script>
customAdaptor = ej.base.extend(customAdaptor, {
896
//Added the anti-forgery token.
__RequestVerificationToken: document.getElementsByName("__RequestVe
rificationToken")[0].value,
value: value,
table: tableName,
action: 'insert'
}),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
};
},
});
</script>
<script>
function load(args) {
this.dataSource.adaptor = customAdaptor;
}
</script>
razor
anti-forgery-token.cs
@Html.EJS().Grid("Grid")
.DataSource(dm => dm.Url("Home/DataSource")
.InsertUrl("Home/Insert")
.UpdateUrl("Home/Update")
.RemoveUrl("Home/Delete")
.Adaptor("UrlAdaptor"))
.Load("load").Columns(col => {
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("1
20").ValidationRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.
Right).Add();
col.Field("EmployeeID").HeaderText("Employee ID").Width("150").Add();
})
.AllowPaging()
.EditSettings(edit => edit.AllowAdding(true).AllowEditing(true).AllowDeleti
ng(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal))
.Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }
)
.Render()
897
static List<OrderData> vData = new List<OrderData>();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Insert(OrderData value,string token)
{
getData().Insert(0, value);
return Json(getData());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Update(OrderData value)
{
return Json(ord);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int key)
{
898
if (itemToRemove != null)
getData().Remove(itemToRemove);
return Json(getData());
}
}
Step 1:
Get the column object corresponding to the field name by using the getColumnByField method.
Then, change the header text value.
Step 2:
To reflect the changes in the grid header, invoke the refreshHeader method.
grid.refreshHeader();
razor
column-header-text.cs
899
}).Render()
<script>
document.getElementById('change-text').addEventListener('click', () => { // changin
g the header text for ShipCity column.
var grid = document.getElementById("Grid").ej2_instances[0];
var column = grid.getColumnByField("Freight"); // get the JSON object of the co
lumn corresponding to the field name.
column.headerText = "Changed Text"; // assign a new header text to the column.
grid.refreshHeader();
});
</script>
Step 1:
Create a CSS class with custom style to override the default style for rowcell and headercell.
.e-grid .e-rowcell.customcss{
background-color: #ecedee;
color: 'red';
font-family: 'Bell MT';
font-size: 20px;
}
.e-grid .e-headercell.customcss{
background-color: #2382c3;
color: white;
font-family: 'Bell MT';
font-size: 20px;
}
Step 2:
900
Add the custom CSS class to the specified column by using the customAttributes property.
razor
custom-column-style.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).CustomAttributes("@(new { class='customcss' })').A
dd();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).Render()
<style>
.e-grid .e-rowcell.customcss{
background-color: #ecedee;
color: 'red';
font-family: 'Bell MT';
font-size: 20px;
}
.e-grid .e-headercell.customcss{
background-color: #2382c3;
color: white;
font-family: 'Bell MT';
font-size: 20px;
}
</style>
901
Display custom ToolTip for columns in Grid
To display custom ToolTip ( EJ2 Tooltip ), use the QueryCellInfo event.
Render the ToolTip component for the grid cells by using the following code in the
QueryCellInfo event.
razor
custom-tooltip.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(c
ol =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).QueryCellInfo("tooltip").Render()
<script>
function tooltip(args) { // event triggers on every cell render.
let tooltip = new ej.popups.Tooltip({
content: args.data[args.column.field].toString() // add Essential JS2 toolt
ip for every cell.
}, args.cell);
}
</script>
902
Render other components in a column
You can render any component in a grid column using the Template property.
Step 1:
template:`<div>
<select class="e-control e-dropdownlist">
<option value="1" selected="selected">Order Placed</option>
<option value="2">Processing</option>
<option value="3">Delivered</option>
</select>
</div>`
Step 2:
Using the QueryCellInfo event, you can render the DropDown component with the following
code.
function dropdown(args) {
let ele=args.cell.querySelector('select');
let drop = new ej.dropdowns.DropDownList({popupHeight: 150, popupWidth: 150});
drop.appendTo(ele);
}
razor
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Column
s(col =>
{
col.HeaderText("Order Status").Width("200").Template("#dropdown").Add();
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).QueryCellInfo("dropdown").Render()
903
<div id='dropdown'>
<select class="e-control e-dropdownlist">
<option value="1" selected="selected">Order Placed</option>
<option value="2">Processing</option>
<option value="3">Delivered</option>
</select>
</div>
<script>
function dropdown(args) {
var ele = args.cell.querySelector('select');
var drop = new ej.dropdowns.DropDownList({ popupHeight: 150, popupWidth: 150 });
drop.appendTo(ele);
}
</script>
Step 1:
Create a CSS class with orientation style for the grid header cell.
.orientationcss .e-headercelldiv {
transform: rotate(90deg);
}
Step 2:
Add the custom CSS class to a particular column by using the CustomAttributes property.
Step 3:
function setHeaderHeight(args) {
var textWidth = document.querySelector(".orientationcss > div").scrollWidth;//Obtai
n the width of the headerText content.
var headerCell = document.querySelectorAll(".e-headercell");
for(var i = 0; i < headerCell.length; i++) {
headerCell.item(i).style.height = textWidth + 'px'; //Assign the obtained textW
904
idth as the height of the headerCell.
}
}
razor
orientation.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").CustomAttribute
s(new { @class="orientationcss" }).Add();
}).Created("setHeaderHeight").Render()
<style>
.orientationcss .e-headercelldiv {
transform: rotate(90deg);
}
</style>
<script>
function setHeaderHeight(args) {
var textWidth = document.querySelector(".orientationcss > div").scrollWidth; // obt
ain the width of the headerText content.
var headerCell = document.querySelectorAll(".e-headercell");
for (var i = 0; i < headerCell.length; i++) {
headerCell.item(i).style.height = textWidth + 'px'; // assign the obtained text
Width as the height of the headerCell.
}
}
</script>
905
Refresh the data source
You can add/delete the data source records through an external button. To reflect the data
source changes in the grid, invoke the refresh method.
Step 1:
Step 2:
Refresh the grid after the data source change by using the refresh method.
razor
refresh-datasource.cs
@Html.EJS().Button("add").Content("Add").CssClass('e-block').IsPrimary(true).Render();
@Html.EJS().Button("delete").Content("Delete").CssClass('e-block').IsPrimary(true).Rend
er();
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ
2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusio
n.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).Render()
<script>
document.getElementById('add').onclick = () => {
var grid = document.getElementById("Grid").ej2_instances[0];
var data = { OrderID: 10247, CustomerID: "ASDFG", Freight: 40.4, OrderDate: new Dat
e(8367642e5) };
grid.dataSource.unshift(data); // add new record.
906
grid.refresh(); // refresh the Grid.
};
document.getElementById('delete').onclick = () => {
var grid = document.getElementById("Grid").ej2_instances[0];
if (grid.getSelectedRowIndexes().length) {
let selectedRow: number = grid.getSelectedRowIndexes()[0];
grid.dataSource.splice(selectedRow, 1); // delete the selected record.
} else {
alert("No records selected for delete operation");
}
grid.refresh(); // refresh the Grid.
};
</script>
In the below demo, the ShipCountry column is rendered with the template.
razor
edit-temp.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Template('#temp
late').EditType('dropdownedit').Add();
907
>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
In the below demo, dialog header content is customized using the ActionComplete event.
razor
customize-filter-menu.cs
@{
List<object> operators = new List<object>();
operators.Add(new { value = "startswith", text = "starts with" });
operators.Add(new { value = "endswith", text = "ends with" });
operators.Add(new { value = "contains", text = "contains" });
}
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
}).AllowFiltering().FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterT
ype.Menu).Operators(new { stringOperator = operators }); }).Render()
908
ViewBag.DataSource = OrderDetails.GetAllRecords();
return View();
}
In the below demo, you can access the Editor component instance while adding or editing
actions on the ActionComplete event.
razor
access-editor.cs
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).ActionBegi
n("access").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").Text
Align(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(S
yncfusion.EJ2.Grids.TextAlign.Right).EditType("numericedit").Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("150").EditType("dropd
ownedit").Add();
<script>
function access(args) {
if (args.requestType === 'beginEdit' || args.requestType === 'add') {
var tr = args.row;
var numericTextBox = tr.querySelector('.e-numerictextbox'); // numeric Text
Box component element
if (numericTextBox) {
console.log('NumericTextBox instance: ', numericTextBox.ej2_instances[0
]); // numeric TextBox instance
}
var dropDownList = tr.querySelector('.e-dropdownlist'); // dropDownList com
ponent element
if (dropDownList) {
console.log('DropDownList instance: ', dropDownList.ej2_instances[0]);
909
// dropDownList instance
}
}
}
</script>
razor
customize-filter-menu.cs
@{
List<object> operators = new List<object>();
operators.Add(new { value = "startswith", text = "starts with" });
operators.Add(new { value = "endswith", text = "ends with" });
operators.Add(new { value = "contains", text = "contains" });
}
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(co
l =>
{
col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.G
rids.TextAlign.Right).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add();
col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.E
J2.Grids.TextAlign.Right).Format("yMd").Add();
col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Sync
fusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();
910
}).AllowFiltering().FilterSettings(filter => { filter.Type(Syncfusion.EJ2.Grids.FilterT
ype.Menu).Operators(new { stringOperator = operators }); }).Render()
911
Overview
The HeatMap control is used to visualize a two-dimensional data in which the values are
represented in gradient or fixed colors.
Key Features
Axis Types - Supports three different types of axes to populate the data, namely Numerical,
Categorical,and Datetime.
Axis Feature - Supports inverted axis, opposed position and axis intervals.
Legend - Supports legend which provides value information for the colors which represents
each values in HeatMap.
Data Binding - Supports binding data in JSON and two-dimensional array formats.
Rendering Modes - Supports automatic switching between SVG and Canvas rendering
modes based on the data source length.
912
Getting Started with ASP.NET MVC
Prerequisites
To get start with ASP.NET MVC application, need to ensure the following software to be installed
on the machine.
Step 1: Create ASP.NET MVC Application with default template project in Visual Studio.
Step 2: Once your project created. We need to add Syncfusion EJ2 package into your
application by using NuGet Package Manager .
After installation complete, this will be included in the project. You can refer it from the Project
Assembly Reference.
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>
<system.web>
<compilation>
<assemblies>
<add assembly="Syncfusion.EJ2" Version=15.3400.0.27, Culture=neutral, PublicKey
Token=31BF3856AD364E35"/>
</assemblies>
</compilation>
</system.web>
913
Step 4: Add client side resource through CDN or local package in the layout page
_Layout.cshtml .
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
914
<script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js"></script>
@Html.EJ().Button("mute").Content("click").CssClass("e-success").Render()
915
@* Syncfusion Essential JS2 Styles *@
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/material.css" />
@Html.EJS().ScriptManager()
Step 6:
Add the below code to your Index.cshtml view page which is present under Views/Home folder,
to initialize the heatmap.
@using Syncfusion.EJ2;
@Html.EJS().HeatMap("container").Render()
razor
data.cs
@Html.EJS().HeatMap("container").DataSource(ViewBag.dataSource).Render()
916
public ActionResult Data()
{
ViewBag.dataSource = GetDataSource();
return View();
}
razor
axis.cs
@Html.EJS().HeatMap("container").XAxis(
xAxis =>
{
xAxis.Labels(ViewBag.xLabels);
}).YAxis(yaxis =>
{
yaxis.Labels(ViewBag.yLabels);
}).DataSource(ViewBag.dataSource).Render()
917
{
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "Steven"
, "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "S
at" };
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Add Title
You can add a title using titleSettings property to the heatmap to provide quick information to
the user about the data populated in the heatmap.
razor
title.cs
918
yaxis.Labels(ViewBag.yLabels);
}).DataSource(ViewBag.dataSource).Render()
Enable Legend
919
You can use legend for the heatmap by setting the visible property to true in
legendSettings object and by injecting the Legend module using HeatMap.Inject(Legend)
method.
razor
legend.cs
920
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
razor
label.cs
921
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
razor
palette.cs
922
CellSettings(cs =>cs.ShowLabel(true)).
PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#C06C84").Value(0).Add();
palette.Color("#6C5B7B").Value(50).Add();
palette.Color("#355C7D").Value(100).Add();
}
).Type(Syncfusion.EJ2.HeatMap.PaletteType.Gradient)).
DataSource(ViewBag.dataSource).Render()
923
return data;
}
Enable Tooltip
The tooltip is useful when you cannot display information by using the data labels due to space
constraints. You can enable tooltip by setting the showTooltip property as true and by injecting
Tooltip module using HeatMap.Inject(Tooltip) method.
razor
tooltip.cs
924
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
925
Working with data
Heatmap can visualize JSON data and two-dimensional array data. Using the data adaptor
support, data can be bound to the Heatmap.
Data Adaptor
Heat map supports the following types of data binding with the adaptor support.
Array
Table Binding
Cell Binding
JSON data
Table Binding
Cell Binding
razor
array-row.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("GDP Growth Rate for Major Economies (in Percentage)").TextStyle(ViewBag.te
xtStyle)).XAxis(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.IntervalType.Years).LabelForma
t("yyyy");
}).YAxis(yaxis => yaxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.Numeric)).Legend
Settings(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
926
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "China", "India", "Australia", "Mexico", "
Canada", "Brazil",
"USA", "UK", "Germany", "Russia", "France", "Japan"};
ViewBag.xLabels = xlabels;
string[] yLabels = new string[10] { "2008", "2009", "2010", "2011", "2012", "2
013", "2014", "2015", "2016", "2017" };
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
razor
array-cell.cs
@using Syncfusion.EJ2;
@ControlsSection{
927
@Html.EJS().HeatMap("container").TitleSettings(ts => ts.Text("Percentage of Individ
uals Using Internet by Country").TextStyle(ViewBag.textStyle)).XAxis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).DataSource(ViewBag.dataSource).PaletteSettings(ps =>
ps.Palette(palette =>
{
palette.Color("#3498DB").Add();
palette.Color("#2C3E50").Add();
})).CellSettings(cs =>cs.Border(ViewBag.border).TextStyle(ViewBag.cellTextStyle).Fo
rmat("{value} %")).LegendSettings(ls =>
ls.Visible(false)).TooltipRender("tooltipRender").Render()
}
<script>
var tooltipRender = function (args) {
args.content = [args.yLabel + ' | ' + args.xLabel + ' : ' + args.value + '
%'];
};
</script>
928
, 85.80}, {3, 6, 87.5},
{4, 0, 10.5}, {4, 1, 20.75}, {4, 2, 35.5}, {4, 3, 35.5}, {4, 4, 45.5}, {
4, 5, 65}, {4, 6, 75.5},
{5, 0, 45.5}, {5, 1, 20.75}, {5, 2, 45.5}, {5, 3, 50.75}, {5, 4, 79.30}
, {5, 5, 84.20}, {5, 6, 87.36},
{6, 0, 26.82}, {6, 1, 70}, {6, 2, 75}, {6, 3, 79.5}, {6, 4, 88.5}, {6, 5
, 89.5}, {6, 6, 91.75},
{7, 0, 15.75}, {7, 1, 20.75}, {7, 2, 25.5}, {7, 3, 42.35}, {7, 4, 45.15
}, {7, 5, 76.5}, {7, 6, 80.5},
{8, 0, 1.98}, {8, 1, 15.23}, {8, 2, 43}, {8, 3, 49}, {8, 4, 63.80}, {8,
5, 67.97}, {8, 6, 70.52},
{9, 0, 14.31}, {9, 1, 42.87}, {9, 2, 77.28}, {9, 3, 77.82}, {9, 4, 81.44
}, {9, 5, 81.92}, {9, 6, 83.75},
{10, 0, 25.5}, {10, 1, 35.5}, {10, 2, 40.5}, {10, 3, 45.05}, {10, 4, 50
.5}, {10, 5, 75.5}, {10, 6, 90.58}
};
object dataSource = new
{
isJsonData = false,
adaptorType = "Cell",
data = cellData
};
ViewBag.dataSource = dataSource;
return View();
}
razor
json-row.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts => ts.Text("Olympic Medal Achieve
ments of most Successful Countries").TextStyle(ViewBag.textStyle)).XAxis(
xAxis =>
{
xAxis.LabelRotation(45)
.LabelIntersectAction(Syncfusion.EJ2.HeatMap.LabelIntersectAction.None)
929
.Labels(ViewBag.xLabels);
}).YAxis(yaxis =>
{
yaxis.Title(ViewBag.title)
.Labels(ViewBag.yLabels);
}).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#F0C27B").Add();
palette.Color("#4B1248").Add();
})).LegendSettings(ls => ls.Visible(false)).CellSettings(cs =>
cs.Border(ViewBag.border).TextStyle(ViewBag.cellTextStyle).Format("{value} %")).Dat
aSource("dataSource").TooltipRender("tooltipRender").Render()
}
<script>
var tooltipRender = function (args) {
args.content = [args.yLabel + ' | ' + args.xLabel + ' : ' + args.value + '
medals'];
};
var dataSource = {
data: [
{ "Region": "USA", "2000": 93, "2004": 101, "2008": 112, "2012": 103, "
2016": 121 },
{ "Region": "GBR", "2000": 28, "2004": 30, "2008": 49, "2012": 65, "201
6": 67 },
{ "Region": "China", "2000": 58, "2004": 63, "2008": 100, "2012": 91, "
2016": 70 },
{ "Region": "Russia", "2000": 89, "2004": 90, "2008": 60, "2012": 69, "
2016": 55 },
{ "Region": "Germany", "2000": 56, "2004": 49, "2008": 41, "2012": 44,
"2016": 42 },
{ "Region": "Japan", "2000": 18, "2004": 37, "2008": 25, "2012": 38, "2
016": 41 },
{ "Region": "France", "2000": 38, "2004": 33, "2008": 43, "2012": 35, "
2016": 42 },
{ "Region": "KOR", "2000": 28, "2004": 30, "2008": 32, "2012": 30, "201
6": 21 },
{ "Region": "Italy", "2000": 34, "2004": 32, "2008": 27, "2012": 28, "2
016": 28 }],
isJsonData: true,
adaptorType: "Table",
xDataMapping: "Region",
};
</script>
930
ViewBag.textStyle = new
{
size = "15px",
fontWeight = 500,
fontStyle = "Normal",
fontFamily = "Segoe UI"
};
ViewBag.border = new
{
width = 0,
};
ViewBag.cellTextStyle = new { color = "white" };
string[] xlabels = new string[9] { "China", "France", "GBR", "Germany", "It
aly", "Japan", "KOR", "Russia", "USA" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[5] { "2000", "2004", "2008", "2012", "2016" }
;
ViewBag.yLabels = yLabels;
ViewBag.title = new { text = "Olympic Year" };
return View();
}
razor
json-cell.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts => ts.Text("Most Visited Destinat
ions by International Tourist Arrivals").TextStyle(ViewBag.textStyle)).XAxis(
xAxis => xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).DataSource("dataSource").PaletteSettings(ps => ps.Pa
lette(palette =>
{
palette.Color("#DCD57E").Add();
palette.Color("#A6DC7E").Add();
palette.Color("#7EDCA2").Add();
palette.Color("#6EB5D0").Add();
})).CellSettings(cs =>
cs.Border(ViewBag.border).ShowLabel(true).Format("{value} M")).Load("load").Render(
931
)
}
<script>
var load = function (args) {
var selectedTheme = location.hash.split('/')[1];
selectedTheme = selectedTheme ? selectedTheme : 'Material';
args.heatmap.theme = (selectedTheme.charAt(0).toUpperCase() + selectedTheme
.slice(1));
};
var dataSource = {
data: [
{ 'rowid': 'France', 'columnid': '2010', 'value': '77.6' },
{ 'rowid': 'France', 'columnid': '2011', 'value': '79.4' },
{ 'rowid': 'France', 'columnid': '2012', 'value': '80.8' },
{ 'rowid': 'France', 'columnid': '2013', 'value': '86.6' },
{ 'rowid': 'France', 'columnid': '2014', 'value': '83.7' },
{ 'rowid': 'France', 'columnid': '2015', 'value': '84.5' },
{ 'rowid': 'France', 'columnid': '2016', 'value': '82.6' },
{ 'rowid': 'USA', 'columnid': '2010', 'value': '60.6' },
{ 'rowid': 'USA', 'columnid': '2011', 'value': '65.4' },
{ 'rowid': 'USA', 'columnid': '2012', 'value': '70.8' },
{ 'rowid': 'USA', 'columnid': '2013', 'value': '73.8' },
{ 'rowid': 'USA', 'columnid': '2014', 'value': '75.3' },
{ 'rowid': 'USA', 'columnid': '2015', 'value': '77.5' },
{ 'rowid': 'USA', 'columnid': '2016', 'value': '77.6' },
{ 'rowid': 'Spain', 'columnid': '2010', 'value': '64.9' },
{ 'rowid': 'Spain', 'columnid': '2011', 'value': '52.6' },
{ 'rowid': 'Spain', 'columnid': '2012', 'value': '60.8' },
{ 'rowid': 'Spain', 'columnid': '2013', 'value': '65.6' },
{ 'rowid': 'Spain', 'columnid': '2014', 'value': '52.6' },
{ 'rowid': 'Spain', 'columnid': '2015', 'value': '68.5' },
{ 'rowid': 'Spain', 'columnid': '2016', 'value': '75.6' },
{ 'rowid': 'China', 'columnid': '2010', 'value': '55.6' },
{ 'rowid': 'China', 'columnid': '2011', 'value': '52.3' },
{ 'rowid': 'China', 'columnid': '2012', 'value': '54.8' },
{ 'rowid': 'China', 'columnid': '2013', 'value': '51.1' },
{ 'rowid': 'China', 'columnid': '2014', 'value': '55.6' },
{ 'rowid': 'China', 'columnid': '2015', 'value': '56.9' },
{ 'rowid': 'China', 'columnid': '2016', 'value': '59.3' },
{ 'rowid': 'Italy', 'columnid': '2010', 'value': '43.6' },
{ 'rowid': 'Italy', 'columnid': '2011', 'value': '43.2' },
{ 'rowid': 'Italy', 'columnid': '2012', 'value': '55.8' },
{ 'rowid': 'Italy', 'columnid': '2013', 'value': '50.1' },
{ 'rowid': 'Italy', 'columnid': '2014', 'value': '48.5' },
{ 'rowid': 'Italy', 'columnid': '2015', 'value': '50.7' },
{ 'rowid': 'Italy', 'columnid': '2016', 'value': '52.4' },
{ 'rowid': 'UK', 'columnid': '2010', 'value': '28.2' },
{ 'rowid': 'UK', 'columnid': '2011', 'value': '31.6' },
932
{ 'rowid': 'UK', 'columnid': '2012', 'value': '29.8' },
{ 'rowid': 'UK', 'columnid': '2013', 'value': '33.1' },
{ 'rowid': 'UK', 'columnid': '2014', 'value': '32.6' },
{ 'rowid': 'UK', 'columnid': '2015', 'value': '34.4' },
{ 'rowid': 'UK', 'columnid': '2016', 'value': '35.8' },
{ 'rowid': 'Germany', 'columnid': '2010', 'value': '26.8' },
{ 'rowid': 'Germany', 'columnid': '2011', 'value': '29' },
{ 'rowid': 'Germany', 'columnid': '2012', 'value': '26.8' },
{ 'rowid': 'Germany', 'columnid': '2013', 'value': '27.6' },
{ 'rowid': 'Germany', 'columnid': '2014', 'value': '33' },
{ 'rowid': 'Germany', 'columnid': '2015', 'value': '35' },
{ 'rowid': 'Germany', 'columnid': '2016', 'value': '35.6' },
{ 'rowid': 'Mexico', 'columnid': '2010', 'value': '23.2' },
{ 'rowid': 'Mexico', 'columnid': '2011', 'value': '24.9' },
{ 'rowid': 'Mexico', 'columnid': '2012', 'value': '30.1' },
{ 'rowid': 'Mexico', 'columnid': '2013', 'value': '22.2' },
{ 'rowid': 'Mexico', 'columnid': '2014', 'value': '29.3' },
{ 'rowid': 'Mexico', 'columnid': '2015', 'value': '32.1' },
{ 'rowid': 'Mexico', 'columnid': '2016', 'value': '35' },
{ 'rowid': 'Thailand', 'columnid': '2010', 'value': '15.9' },
{ 'rowid': 'Thailand', 'columnid': '2011', 'value': '19.8' },
{ 'rowid': 'Thailand', 'columnid': '2012', 'value': '21.8' },
{ 'rowid': 'Thailand', 'columnid': '2013', 'value': '23.5' },
{ 'rowid': 'Thailand', 'columnid': '2014', 'value': '24.8' },
{ 'rowid': 'Thailand', 'columnid': '2015', 'value': '29.9' },
{ 'rowid': 'Thailand', 'columnid': '2016', 'value': '32.6' },
{ 'rowid': 'Austria', 'columnid': '2010', 'value': '22' },
{ 'rowid': 'Austria', 'columnid': '2011', 'value': '21.3' },
{ 'rowid': 'Austria', 'columnid': '2012', 'value': '24.2' },
{ 'rowid': 'Austria', 'columnid': '2013', 'value': '23.2' },
{ 'rowid': 'Austria', 'columnid': '2014', 'value': '25' },
{ 'rowid': 'Austria', 'columnid': '2015', 'value': '26.7' },
{ 'rowid': 'Austria', 'columnid': '2016', 'value': '28.1' },],
isJsonData: true,
adaptorType: 'Cell',
xDataMapping: 'rowid',
yDataMapping: 'columnid',
valueMapping: 'value'
};
</script>
933
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
ViewBag.border = new
{
width = 1,
radius = 4,
color = "white"
};
string[] xlabels = new string[10] { "Austria", "China", "France", "Germany", "
Italy", "Mexico", "Spain", "Thailand", "UK", "USA" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[7] { "2010", "2011", "2012", "2013", "2014", "20
15", "2016" };
ViewBag.yLabels = yLabels;
return View();
}
Empty Points
The Data points that uses the null or "" or undefined as value are considered as empty
points. Empty data points are ignored and not displayed in the heatmap. Empty data points are
rendered with default palette. You can customize the empty data point color value using
emptyPointColor property.
razor
empty-points.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(false)).LegendSettings(ls =>
ls.Visible(true)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#C06C84").Add();
palette.Color("#6C5B7B").Add();
palette.Color("#355C7D").Add();
}).Type(Syncfusion.EJ2.HeatMap.PaletteType.Fixed)).DataSource(ViewBag.dataSource).R
ender()
}
934
public ActionResult EmptyPoints()
{
ViewBag.textStyle = new
{
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
ViewBag.dataSource = GetDataSource();
return View();
}
935
Rendering Mode
Heat map can be displayed using Canvas or Scalable Vector Graphics (SVG) rendering logic
to improve the initial load performance and scalability. Heatmap can also automatically switch
between Canvas and SVG modes based on dataset size and you can enable this mode by
setting renderingMode property as Auto .
If the Auto mode is enabled in the heatmap and if there are more than 10,000 data points,
then the heatmap will be rendered in Canvas mode else the heatmap will be rendered in
SVG mode.
razor
rendering-mode.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(true)).RenderingMode(Syncfusion.EJ2.HeatMap.DrawType.SVG).ShowTooltip(
true).DataSource(ViewBag.dataSource).Render()
}
936
{
int[,] data = new int[,]
{
{73, 39, 26, 39, 94, 0},
{93, 58, 53, 38, 26, 68},
{99, 28, 22, 4, 66, 90},
{14, 26, 97, 69, 69, 3},
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
937
Axis
Heatmap consists two axes, x-axis and y-axis which displays the row headers and column
headers for plotting the data points. You can define the type, format and other customizing
options for both the axes in heatmap.
Types
There are three different axis types available in heatmap, which defines the data type of the axis
labels. You can define the axis type using valueType property in heatmap.
Category Axis
Category axis type is used to represent the string values in axis labels.
razor
category.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels).ValueType(Syncfusion.EJ2.HeatMap.ValueType.Category))
.YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels).ValueType(Syncfusion.EJ2.HeatMap.ValueType.Category))
.DataSource(ViewBag.dataSource).Render()
}
938
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Numeric Axis
Numeric axis type is used to represent the numeric values in axis labels
razor
numeric.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)")).XAxis(xAxis =>
xAxis.Minimum(1).Maximum(11).ValueType(Syncfusion.EJ2.HeatMap.ValueType.Numeric)).Y
Axis(yaxis =>
yaxis.Minimum(1).Maximum(5).ValueType(Syncfusion.EJ2.HeatMap.ValueType.Category)).D
ataSource(ViewBag.dataSource).Render()
}
939
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
ViewBag.dataSource = GetDataSource();
return View();
}
DateTime Axis
DateTime axis type is used to represent the date time values in axis labels with specific format. In
DateTime axis, you can define the start and end date/time using the minimum and maximum
properties.
razor
dateTime.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Monthly Flight Traffic at JFK Airport").TextStyle(ViewBag.textStyle)).XAxi
s(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1))
.Maximum(new System.DateTime(2017, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.I
940
ntervalType.Years)
.LabelFormat("yyyy").LabelRotation(45)
.LabelIntersectAction(Syncfusion.EJ2.HeatMap.LabelIntersectAction.None);
}).YAxis(yaxis => yaxis.Labels( ViewBag.yLabels)).CellSettings(cs =>
cs.Border(ViewBag.border).ShowLabel(false).Format("{value} flights")).LegendSetting
s(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
941
{32494, 29848, 34385, 35804, 37943, 38722, 41315, 41335, 37177, 37443,
32457, 37304},
{34378, 29576, 30547, 35664, 36622, 38145, 40347, 41868, 38252, 36505,
29576, 36450},
{35219, 31670, 32589, 34927, 36998, 39825, 41126, 42002, 37021, 36583,
32408, 37108}
};
return data;
}
Inversed Axis
Heatmap supports inversing the axis origin for both the axes, where the axis labels are placed in
an inversed manner. You can enable axis inversing by enabling the isInversed property.
razor
inversed.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Monthly Flight Traffic at JFK Airport").TextStyle(ViewBag.textStyle)).XAxi
s(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1))
.Maximum(new System.DateTime(2017, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.I
ntervalType.Years)
.LabelFormat("yyyy").LabelRotation(45)
.LabelIntersectAction(Syncfusion.EJ2.HeatMap.LabelIntersectAction.None).IsInver
sed(true);
}).YAxis(yaxis => yaxis.Labels( ViewBag.yLabels)).CellSettings(cs =>
cs.Border(ViewBag.border).ShowLabel(false).Format("{value} flights")).LegendSetting
s(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
942
};
string[] yLabels = new string[12] { "Jan", "Feb", "Mar", "Apr", "May", "June",
"July", "Aug",
"Sep", "Oct", "Nov", "Dec"};
ViewBag.yLabels = yLabels;
ViewBag.border = new { width = 0};
ViewBag.dataSource = GetDataSource();
return View();
}
Opposed Axis
In heatmap, it is possible to place the axis label in opposite position of its default axis label
position using opposedPosition property.
razor
943
opposed.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Monthly Flight Traffic at JFK Airport").TextStyle(ViewBag.textStyle)).XAxi
s(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1))
.Maximum(new System.DateTime(2017, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.I
ntervalType.Years)
.LabelFormat("yyyy").LabelRotation(45)
.LabelIntersectAction(Syncfusion.EJ2.HeatMap.LabelIntersectAction.None).Opposed
Position(true);
}).YAxis(yaxis => yaxis.Labels( ViewBag.yLabels)).CellSettings(cs =>
cs.Border(ViewBag.border).ShowLabel(false).Format("{value} flights")).LegendSetting
s(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
944
{34522, 31324, 32128, 34231, 36817, 34381, 37180, 38255, 32776, 32645,
31539, 32981},
{32213, 28755, 29517, 31214, 33747, 33507, 35763, 36837, 32910, 33437,
30659, 31965},
{31282, 28663, 32952, 33941, 34506, 36875, 38836, 35497, 34285, 34094,
32256, 33699},
{31714, 29405, 33745, 32838, 33461, 35034, 36122, 37943, 34128, 30624,
32398, 33522},
{32064, 28387, 33751, 32537, 34034, 35977, 37196, 38301, 33627, 34115,
31072, 33939},
{32417, 27868, 30807, 33386, 35284, 36126, 39753, 40978, 35777, 35277,
31281, 35411},
{32494, 29848, 34385, 35804, 37943, 38722, 41315, 41335, 37177, 37443,
32457, 37304},
{34378, 29576, 30547, 35664, 36622, 38145, 40347, 41868, 38252, 36505,
29576, 36450},
{35219, 31670, 32589, 34927, 36998, 39825, 41126, 42002, 37021, 36583,
32408, 37108}
};
return data;
}
Label Formatting
Heatmap supports formatting the axis labels by using labelFormat property. Using this property
you can customize the axis label by global string format ('P', 'C', etc) or customized format like
'{value}°C'.
razor
label-format.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Monthly Flight Traffic at JFK Airport").TextStyle(ViewBag.textStyle)).XAxi
s(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.IntervalType.Years).LabelForma
t("yyyy");
}).YAxis(yaxis => yaxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.Numeric).LabelFo
rmat("${value}")).LegendSettings(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
945
public ActionResult LabelFormat()
{
ViewBag.textStyle = new
{
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
ViewBag.dataSource = GetDataSource();
return View();
}
Axis Intervals
In heatmap, it is possible to define an interval between the axis labels using interval property.
In DateTime axis, you can change the interval mode by using intervalType property. DateTime
axis supports following interval types
Years
Months
Days
Hours
Minutes
razor
946
interval.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Monthly Flight Traffic at JFK Airport").TextStyle(ViewBag.textStyle)).XAxi
s(xAxis =>
{
xAxis.ValueType(Syncfusion.EJ2.HeatMap.ValueType.DateTime).Minimum(new System.D
ateTime(2007, 1, 1))
.Maximum(new System.DateTime(2017, 1, 1)).IntervalType(Syncfusion.EJ2.HeatMap.I
ntervalType.Years)
.LabelFormat("yyyy").Interval(2);
}).YAxis(yaxis => yaxis.Labels( ViewBag.yLabels)).CellSettings(cs =>
cs.Border(ViewBag.border).ShowLabel(false).Format("{value} flights")).LegendSetting
s(ls =>
ls.Visible(false)).DataSource(ViewBag.dataSource).Render()
}
947
{32213, 28755, 29517, 31214, 33747, 33507, 35763, 36837, 32910, 33437,
30659, 31965},
{31282, 28663, 32952, 33941, 34506, 36875, 38836, 35497, 34285, 34094,
32256, 33699},
{31714, 29405, 33745, 32838, 33461, 35034, 36122, 37943, 34128, 30624,
32398, 33522},
{32064, 28387, 33751, 32537, 34034, 35977, 37196, 38301, 33627, 34115,
31072, 33939},
{32417, 27868, 30807, 33386, 35284, 36126, 39753, 40978, 35777, 35277,
31281, 35411},
{32494, 29848, 34385, 35804, 37943, 38722, 41315, 41335, 37177, 37443,
32457, 37304},
{34378, 29576, 30547, 35664, 36622, 38145, 40347, 41868, 38252, 36505,
29576, 36450},
{35219, 31670, 32589, 34927, 36998, 39825, 41126, 42002, 37021, 36583,
32408, 37108}
};
return data;
}
948
Palette
In Heatmap, each data point is displayed as a cell with color applied based on the data value.
Palette in heatmap is used to define the color range for the cells and the gradient type for the
colors. You can define the colors either in RGB or hex codes using the color property in
palette . The defined colors are applied to the cell background based on palette type and cell
value.
Palette Types
You can display the heatmap cells either in gradient colors or in fixed colors.
Gradient
The smooth transition between the given palette colors will be applied for the heatmap cells
based on value. Heatmap will calculate all the gradient colors between the start and end color for
all the distinct data values. Default start color and end color will be considered for gradient
calculation, if the colors are not defined. The palette type must be defined as Gradient for the
type property in paletteSettings property.
razor
gradient.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).LegendSettings(ls =>
ls.Visible(true)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#C06C84").Add();
palette.Color("#6C5B7B").Add();
palette.Color("#355C7D").Add();
}).Type(Syncfusion.EJ2.HeatMap.PaletteType.Gradient))
.DataSource(ViewBag.dataSource).Render()
}
949
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Fixed
In Fixed palette type, solid colors are applied to the heatmap cells. The data values will be
grouped based on the number of colors defined for the heatmap. The palette type must be
defined as Fixed for the type property in paletteSettings property.
razor
fixed.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
950
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(false)).LegendSettings(ls =>
ls.Position("Right")).PaletteSettings(ps =>
ps.Type(Syncfusion.EJ2.HeatMap.PaletteType.Fixed)).DataSource(ViewBag.dataSource).R
ender()
}
951
}
razor
color.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).LegendSettings(ls =>
ls.Visible(true)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#C06C84").Add();
palette.Color("#6C5B7B").Add();
palette.Color("#355C7D").Add();
}).Type(Syncfusion.EJ2.HeatMap.PaletteType.Gradient))
.DataSource(ViewBag.dataSource).Render()
}
952
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
953
Legend
The legend is used to provide the information about the heatmap cell. You can enable the legend
by setting visible property to true and by injecting Legend module using
HeatMap.Inject(Legend) .
razor
default.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Value(0).Color("#C2E7EC").Add();
palette.Value(10).Color("#AEDFE6").Add();
palette.Value(20).Color("#9AD7E0").Add();
palette.Value(30).Color("#72C7D4").Add();
palette.Value(40).Color("#5EBFCE").Add();
palette.Value(50).Color("#4AB7C8").Add();
palette.Value(60).Color("#309DAE").Add();
palette.Value(70).Color("#2B8C9B").Add();
palette.Value(80).Color("#206974").Add();
palette.Value(90).Color("#15464D").Add();
palette.Value(100).Color("#000000").Add();
})).LegendSettings(ls =>
ls.Position("Right")).DataSource(ViewBag.dataSource).Render()
}
954
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Legend Types
Heatmap supports two legend types Gradient and List type.
Gradient - This is a continuous color legend with smooth color transition between palette
color values.
List - List is fixed color legend. Each and every palette color informations are shown
separately as list item.
You can change the legend type by using type property in paletteSettings property.
razor
types.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
955
cs.ShowLabel(false)).LegendSettings(ls =>
ls.Visible(true)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Color("#C06C84").Add();
palette.Color("#6C5B7B").Add();
palette.Color("#355C7D").Add();
}).Type(Syncfusion.EJ2.HeatMap.PaletteType.Fixed)).DataSource(ViewBag.dataSource).R
ender()
}
956
return data;
}
Placement
You can place the legend at left, right, top or bottom to the heatmap layout by using the
position property. The legend is positioned at the right to the heatmap by default.
razor
placement.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).LegendSettings(ls =>
ls.Position("Top")).DataSource(ViewBag.dataSource).Render()
}
957
{99, 28, 22, 4, 66, 90},
{14, 26, 97, 69, 69, 3},
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
Alignment
You can align the legend as center, far or near to the heatmap using alignment property.
razor
alignment.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).LegendSettings(ls =>
ls.Position("Top").Alignment("Near").Width("150px")).DataSource(ViewBag.dataSource)
.Render()
}
958
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Legend Dimensions
You can change the legend dimensions with values in pixels or percentage by using the width
and height properties.
razor
dimensions.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).LegendSettings(ls =>
ls.Position("Right").Height("150px")).DataSource(ViewBag.dataSource).Render()
}
959
{
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
razor
paging.cs
@using Syncfusion.EJ2;
@ControlsSection{
960
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).PaletteSettings(ps => ps.Palette(palette =>
{
palette.Value(0).Color("#C2E7EC").Add();
palette.Value(10).Color("#AEDFE6").Add();
palette.Value(20).Color("#9AD7E0").Add();
palette.Value(25).Color("#86CFDA").Add();
palette.Value(30).Color("#72C7D4").Add();
palette.Value(40).Color("#5EBFCE").Add();
palette.Value(50).Color("#4AB7C8").Add();
palette.Value(55).Color("#36AFC2").Add();
palette.Value(60).Color("#309DAE").Add();
palette.Value(70).Color("#2B8C9B").Add();
palette.Value(75).Color("#257A87").Add();
palette.Value(80).Color("#206974").Add();
palette.Value(85).Color("#1B5761").Add();
palette.Value(90).Color("#15464D").Add();
palette.Value(100).Color("#000000").Add();
}).Type(Syncfusion.EJ2.HeatMap.PaletteType.Fixed)).LegendSettings(ls =>
ls.Position("Right").Height("150px")).DataSource(ViewBag.dataSource).Render()
}
961
{
{73, 39, 26, 39, 94, 0},
{93, 58, 53, 38, 26, 68},
{99, 28, 22, 4, 66, 90},
{14, 26, 97, 69, 69, 3},
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
962
Appearance
Cell/Customizations
You can customize the cell by using cellSettings property.
Border
You can change the width, color and radius of the heatmap cells, by using border property.
razor
border.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.Border(ViewBag.border)).DataSource(ViewBag.dataSource).Render()
}
963
int[,] data = new int[,]
{
{73, 39, 26, 39, 94, 0},
{93, 58, 53, 38, 26, 68},
{99, 28, 22, 4, 66, 90},
{14, 26, 97, 69, 69, 3},
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
Cell Highlighting
You can enable or disable the cell highlighting while hovering on the heatmap cells, by using
enableCellHighlighting property.
razor
cell-highlight.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.EnableCellHighlighting(true)).DataSource(ViewBag.dataSource).Render()
}
964
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Margin
You can set margin for heatmap from its container through margin property.
razor
margin.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").Margin(margin => margin.Left(15).Right(15).Top(15)
.Bottom(15)).TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).DataSource(ViewBag.dataSource).Render()
}
965
public ActionResult Margin()
{
ViewBag.textStyle = new
{
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
Title
The title is used to provide a quick information about the data plotted in heat map. The text
property is used to set the title for heatmap. You can also customize text style of the title by using
the textStyle property.
razor
966
title.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).DataSource(ViewBag.dataSource).Render()
}
967
return data;
}
Data label
You can toggle the visibility of data labels by using the property showLabel . By Default, the data
label will be visible.
razor
data-label.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(false)).DataSource(ViewBag.dataSource).Render()
}
968
{99, 28, 22, 4, 66, 90},
{14, 26, 97, 69, 69, 3},
{7, 46, 47, 47, 88, 6},
{41, 55, 73, 23, 3, 79},
{56, 69, 21, 86, 3, 33},
{45, 7, 53, 81, 95, 79},
{60, 77, 74, 68, 88, 51},
{25, 25, 10, 12, 78, 14},
{25, 56, 55, 58, 12, 82},
{74, 33, 88, 23, 86, 59}
};
return data;
}
Text Style
You can customize the font family, font size, color of the data label, by using the textStyle in
cellSettings property.
razor
text-style.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.TextStyle(ViewBag.TextStyle)).DataSource(ViewBag.dataSource).Render()
}
969
ViewBag.dataSource = GetDataSource();
ViewBag.textStyle = new { fontStyle = "Italic",fontFamily = "Segoe UI"};
return View();
}
Format
You can change the format of the data label, such as currency, decimal, percent etc. by using
format property.
razor
format.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.Format("{value} $")).DataSource(ViewBag.dataSource).Render()
}
970
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
971
Dimensions
Size for Container
Heatmap can render to its container size. You can set the size via inline or CSS as demonstrated
below.
<div id='container'>
<div id='element' style="width:650px; height:350px;"></div>
</div>
You can also set size for heatmap directly through width and height properties.
In Pixel
razor
pixel.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").Width("650px").Height("350px").TitleSettings(ts =>
972
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
In Percentage
By setting value in percentage, heatmap gets its dimension with respect to its container. For
example, when the height is ‘50%’, heatmap renders to half of the container height.
razor
percentage.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").Width("80%").Height("90%").TitleSettings(ts =>
ts.Text("Sales Revenue per Employee (in 1000 US$)").TextStyle(ViewBag.textStyle)).X
Axis(xAxis =>
xAxis.Labels(ViewBag.xLabels)).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(true)).DataSource(ViewBag.dataSource).Render()
}
973
ViewBag.textStyle = new
{
size= "15px",
fontWeight= "500",
fontStyle= "Normal",
fontFamily= "Segoe UI"
};
string[] xlabels = new string[12] { "Nancy", "Andrew", "Janet", "Margaret", "S
teven", "Michael", "Robert", "Laura", "Anne", "Paul", "Karin", "Mario" };
ViewBag.xLabels = xlabels;
string[] yLabels = new string[6] { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"
};
ViewBag.yLabels = yLabels;
ViewBag.dataSource = GetDataSource();
return View();
}
974
Tooltip
Tooltip is used to provide the details of the heatmap cell and this will be displayed with mouse
hovering on the cell and on tap action in touch devices.
Default Tooltip
You can enable the tooltip by setting showTooltip property to true and by injecting Tooltip
module using HeatMap.Inject(Tooltip) .
razor
tooltip.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts => ts.Text("Crude Oil Production
of Non-OPEC Countries (in Million barrels per day)").TextStyle(ViewBag.textStyle)).XAxi
s(
xAxis =>{ xAxis.Labels(ViewBag.xLabels)}).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(false)).ShowTooltip(true).DataSource(ViewBag.dataSource).Render()
}
975
[3.30, 3.39, 3.40, 3.48, 3.60, 3.67, 3.73, 3.79, 3.79, 4.07],
[5.80, 5.74, 5.64, 5.44, 5.18, 5.08, 5.07, 5.00, 5.35, 5.47],
[6.91, 7.40, 8.13, 8.80, 9.04, 9.24, 9.43, 9.35, 9.49, 9.69]
};
return data;
}
Tooltip Template
In heatmap, you can customize the tooltip by using tooltipRender client side event.
razor
template.cs
@using Syncfusion.EJ2;
@ControlsSection{
@Html.EJS().HeatMap("container").TitleSettings(ts => ts.Text("Crude Oil Production
of Non-OPEC Countries (in Million barrels per day)").TextStyle(ViewBag.textStyle)).XAxi
s(
xAxis =>{ xAxis.Labels(ViewBag.xLabels)}).YAxis(yaxis =>
yaxis.Labels(ViewBag.yLabels)).CellSettings(cs =>
cs.ShowLabel(false)).ShowTooltip(true).TooltipRender("tooltipRender").DataSource(Vi
ewBag.dataSource).Render()
}
<script>
var tooltipRender = function (args) {
args.content = ['In ' + args.yLabel + ', the ' + args.xLabel + ' produced '
+ args.value + ' million barrels per day'];
};
</script>
976
private int[,] GetDataSource()
{
int[,] data = new int[,]
{
[0.72, 0.71, 0.71, 0.67, 0.72, 0.53, 0.53, 0.56, 0.58, 0.56],
[2.28, 2.29, 2.09, 1.84, 1.64, 1.49, 1.49, 1.39, 1.32, 1.23],
[2.02, 2.17, 2.30, 2.39, 2.36, 2.52, 2.62, 2.57, 2.57, 2.74],
[3.21, 3.26, 3.45, 3.47, 3.42, 3.34, 3.14, 2.83, 2.64, 2.61],
[3.22, 3.13, 3.04, 2.95, 2.69, 2.49, 2.27, 2.18, 2.06, 1.87],
[3.30, 3.39, 3.40, 3.48, 3.60, 3.67, 3.73, 3.79, 3.79, 4.07],
[5.80, 5.74, 5.64, 5.44, 5.18, 5.08, 5.07, 5.00, 5.35, 5.47],
[6.91, 7.40, 8.13, 8.80, 9.04, 9.24, 9.43, 9.35, 9.49, 9.69]
};
return data;
}
977
Overview
The ListView component represents the data in interactive hierarchical structure interface across
different layouts or views, that also has features such as data-binding, template, grouping and
Virtualization.
Key Features
Data binding: Supports data binding to display the list of items from the local or server-side
data source.
Grouping: Provides support to group the logically related items under a category.
Customizing templates: Allows you to customize the list item, header, and category group
header.
Virtualization: Allows you to load only viewable list items in a view port which will increase
ListView performance on loading large number of data.
Accessibility: Provides built-in accessibility support that helps to access all the ListView
component features through the keyboard, on-screen readers, or other assistive technology
devices.
978
Getting Started
This section briefly explains about how to render ListView component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x , if you reference Syncfusion assemblies from trial setup or from
the NuGet feed, you also have to include a license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP .NET MVC application to
use our components.
@Html.EJS().ListView("listview").Render()
Bind dataSource
Populate the data in ListView by using the dataSource property. Here, the JSON values are
passed to the ListView component are generated in HomeController.cs and assigned to
ViewBag variable.
ViewBag.dataSource variable is used for bounding the dataSource property in view page.
979
@Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewBag.dataSource
).Render()
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewBag.dataSource).Re
nder()
980
981
Data binding
ListView provides an option to load the data either from local dataSource or remote data
services. This can be done through the dataSource property that supports the data type of array
or DataManager .
ListView supports different kind of data services such as OData, OData V4, and Web API, and
data formats like XML, JSON, and, JSONP with the help of DataManager Adaptors.
Specifies the icon class of each list item that will be added
iconCss string
before to the list item text.
sortBy string Specifies sorting field, that is used to sort the listview data.
When complex data bind to ListView, you should map the fields properly. Otherwise, the
ListView properties remain as undefined or null.
razor
982
simpledata.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Render()
}
<style>
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult simpledata()
{
ViewBag.dataSource = new string[] { "Artwork", "Abstract", "Modern Painting"
, "Ceramics", "Animation Art", "Oil Painting" };
return View();
}
}
}
In the following example, role column is mapped with the text field.
983
razor
arraydata.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { Text = "Name", Tooltip= "Name" , Id="id"}).ShowHead
er(true).HeaderTitle("Device settings").Render()
}
<style>
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult arraydata()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
Name = "Display",
id = "list-01"
}); listdata.Add(new
{
Name = "Notification",
id = "list-02"
}); listdata.Add(new
{
984
Name = "Sound",
id = "list-03"
}); listdata.Add(new
{
Name = "Apps",
id = "list-04"
}); listdata.Add(new
{
Name = "Storage",
id = "list-05"
}); listdata.Add(new
{
Name = "Battery",
id = "list-06"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
In the following sample, first 6 products from the Product table of NorthWind data service are
displayed.
razor
remotedata.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("remotelist").DataSource(dataManger =>
{
dataManger.Url("http://services.odata.org/V4/Northwind/Northwind.svc").Adaptor(
"ODataV4Adaptor");
}).Query("new ej.data.Query().from('Products').select('ProductID,ProductName').take
985
(6)").Fields(new ListViewFieldSettings { Id = "ProductID" , Text = "ProductName" }).Sho
wHeader(true).HeaderTitle("Products").Render()
}
<style>
#remotelist {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult remotedata()
{
return View();
}
}
}
986
Grouping
The ListView supports to wrap the nested element into a group based on the category. The
category of each list item can be mapped with groupBy field in the data table, that also support
single-level navigation.
In the following sample, The cars are grouped based on its category by using the groupBy field.
razor
grouping.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { GroupBy = "category" }).Render()
}
<style>
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult grouping()
{ List<object> listdata = new List<object>();
listdata.Add(new
{
987
text = "Audi A4",
id = "9bdb",
category = "Audi"
}); listdata.Add(new
{
text = "Audi A5",
id = "4589",
category = "Audi"
}); listdata.Add(new
{
text = "BMW 501",
id = "f849",
category = "BMW"
}); listdata.Add(new
{
text = "BMW 502",
id = "7aff",
category = "BMW"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
Customization
The grouping header can be customized by using the groupTemplate property for both inline and
fixed group header. The complete customization description and explanation with an example is
given in the following link.
Group Template.
988
Checklist
The ListView supports checkbox in default and group-lists which is used to select multiple items.
The checkbox can be enabled by the showCheckBox property.
The Checkbox will be useful in the scenario where we need to select multiple options. For
Example, In Shipping cart we can be able to select or unselect the desired items before checkout
and also it will be useful in selecting multiple items that belongs to same category using the
group list.
razor
default.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { Text = "text", Id="id"}).ShowCheckBox(true).Render(
)
}
<style>
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult default()
{
List<object> listdata = new List<object>();
989
listdata.Add(new
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
}); listdata.Add(new
{
text = "Aston Martin One- 77",
id = "list-07"
}); listdata.Add(new
{
text = "Jaguar XJ220",
id = "list-08"
}); listdata.Add(new
{
text = "McLaren P1",
id = "list-09"
}); listdata.Add(new
{
text = "Ferrari LaFerrari",
id = "list-10"
});
ViewBag.dataSource = listdata;
return View();
990
}
}
}
Checkbox Position
In ListView the checkbox can be positioned into either Left or Right side of the list-item text.
This can be achieved by checkBoxPositon property. By default, checkbox will be positioned to
Left of list-item text.
razor
position.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { Text = "text", Id="id"}).ShowCheckBox(true).CheckBo
xPosition(CheckBoxPosition.Right).Render()
}
<style>
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult position()
{
List<object> listdata = new List<object>();
listdata.Add(new
991
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
}); listdata.Add(new
{
text = "Aston Martin One- 77",
id = "list-07"
}); listdata.Add(new
{
text = "Jaguar XJ220",
id = "list-08"
}); listdata.Add(new
{
text = "McLaren P1",
id = "list-09"
}); listdata.Add(new
{
text = "Ferrari LaFerrari",
id = "list-10"
});
ViewBag.dataSource = listdata;
return View();
}
992
}
}
993
Nested List
The ListView component supports Nested list. For that, the child property should be defined for
the nested list in the array of JSON.
razor
nestedlist.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewBag.dataSource
).Fields(new ListViewFieldSettings { Tooltip = "text" }).ShowHeader(true).HeaderTitle("
Continent").Render()
}
<style>
#listview {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult nestedlist()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Asia",
id = "01",
category = "Continent",
994
child = new List<object>() { new { text = "India", id = "1", category =
"Asia",
child= new List<object>() {
new { id= "1001", text= "Delhi", category= "India" },
new {text= "Kashmir", id= "1002", category= "India"},
new { text= "Goa",id= "1003", category= "India" }
}
},
new { text = "China",id = "2",category = "Asia",
child = new List<object>() {
new { text = "Zhejiang", id = "2001", category = "China" },
new {text= "Hunan",id= "2002", category= "China"},
new { text= "Shandong", id= "2003",category= "China"}
}
}
}
});
listdata.Add(new
{
text = "North America",
id = "02",
category = "Continent",
child = new List<object>() { new { text = "USA", id = "3", category = "
North America",
child= new List<object>() {
new {text= "California", id= "3001", category= "USA"},
new { text= "New York",id= "3002", category= "USA" },
new { text= "Florida",id= "3003", category= "USA" }
}
},
new { text = "Canada",id = "4",category = "North America",
child = new List<object>() {
new { text = "Ontario", id = "4001", category = "Canada" },
new {text= "Alberta",id= "4002", category= "Canada"},
new { text= "Manitoba", id= "4003",category= "Canada"}
}
}
}
});
listdata.Add(new
{
text = "Europe",
id = "03",
category = "Continent",
child = new List<object>() { new { text = "Germany", id = "5", category
= "Europe",
child= new List<object>() {
new {text= "Berlin", id= "5001", category= "Germany"},
new { text= "Bavaria",id= "5002", category= "Germany" },
995
new { text= "Hesse",id= "5003", category= "Germany" }
}
},
new { text = "France",id = "6",category = "Europe",
child = new List<object>() {
new { text = "Paris", id = "6001", category = "France" },
new {text= "Lyon",id= "6002", category= "France"},
new { text= "Marseille", id= "6003",category= "France"}
}
}
}
});
listdata.Add(new
{
text = "Australia",
id = "04",
category = "Continent",
child = new List<object>() { new { text = "Australia", id = "7", catego
ry = "Australia",
child= new List<object>() {
new {text= "Sydney", id= "7001", category= "Australia"},
new { text= "Melbourne",id= "7002", category= "Australia" },
new { text= "Brisbane",id= "7003", category= "Australia" }
}
},
new { text = "New Zealand",id = "8",category = "Australia",
child = new List<object>() {
new { text = "Milford Sound", id = "8001", category = "New Ze
aland" },
new {text= "Tongariro National Park",id= "8002", category=
"New Zealand"},
new { text= "Fiordland National Park", id= "8003",category=
"New Zealand"}
}
},
}
});
listdata.Add(new
{
text = "Africa",
id = "05",
category = "Continent",
child = new List<object>() { new { text = "Morocco", id = "9", category
= "Africa",
child= new List<object>() {
new {text= "Rabat", id= "9001", category= "Morocco"},
new { text= "Toubkal",id= "9002", category= "Morocco" },
new { text= "Todgha Gorge",id= "9003", category= "Morocco" }
996
}
},
new { text = "South Africa",id = "10",category = "Africa",
child = new List<object>() {
new { text = "Cape Town", id = "10001", category = "South Afr
ica" },
new {text= "Pretoria",id= "10002", category= "South Africa"
},
new { text= "Bloemfontein", id= "10003",category= "South Afr
ica"}
}
},
}
});
ViewBag.dataSource = listdata;
return View();
}
}
}
997
Customizing templates
The ListView component is designed to customize each list items and group title. It uses
Essential JS2 Template engine to render the elements.
Template
The ListView supports to customize the content of each list items with the help of template
property.
razor
customizetemplate.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { Text = "socialMedia" }).ShowHeader(true).HeaderTitl
e("Social Media").Template("<span class='${css} icon'><span class='media'>${socialMedia
}</span></span>").Render()
}
<style>
/* csslint ignore:start */
@font-face {
font-family: 'e-icons';
src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvM
j0gSR4AAAEoAAAAVmNtYXDOVM6ZAAABsAAAAFJnbHlm7gIZ8wAAAiAAAA1YaGVhZA0acjMAAADQAAAANmhoZWEH
mQN1AAAArAAAACRobXR4LvgAAAAAAYAAAAAwbG9jYRUsEYgAAAIEAAAAGm1heHABIQEoAAABCAAAACBuYW1lc0c
OBgAAD3gAAAIlcG9zdEs6jNMAABGgAAAAoAABAAADUv9qAFoEAAAA//4D6gABAAAAAAAAAAAAAAAAAAAADAABAA
AAAQAAgbXF1F8PPPUACwPoAAAAANUJFrEAAAAA1QkWsQAAAAAD6gPsAAAACAACAAAAAAAAAAEAAAAMARwACwAAA
AAAAgAAAAoACgAAAP8AAAAAAAAAAQPqAZAABQAAAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAUGZFZABA5wDnCwNS/2oAWgPsAJYAAAABAAAAAAAABAAAAAPoAAAD6AAAA+gAAAPoAAAD6AA
AA+gAAAPoAAAD6AAAA+gAAAPoAAAD6AAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA+AAAABgAEAAEAAucE5wv//w
AA5wDnBv//AAAAAAABAAYADgAAAAEAAgADAAQABQAGAAcACAAJAAoACwAAAAAAAAAsAH4AvgHgAqYDJgS2BZIGO
gZyBqwAAAABAAAAAAMwA+oAHAAAEwYVERQWOwE+ATQmKwEiJj0BITI2NCYjITU0JgbbH7mC0Cw+PizQLDwBKSg5
OSn+2D5XA8YkNf4LmtwBSWdKSDNYRV9EtjNKAQAAAQAAAAAD6gNGADIAAAEUFy4BJwYHHgEXJicVHgEXBiMiJx4
BFw4BIyInHgEzJAA3NCc2NwYHPgE3BgcuASMOAQHqBYHZTRsBATEqMyoBW0gaHBQSFGdENYFIGRhEn1cBHAErAQ
E9KTc+IC4MPEYdTSxXdAKdFBMGXU4mLy1JFwITAj9aDQYDM0ECIiYCJCgJASixCwskNBUGEDAeHgwZHQJfAAABA
AAAAAPqA9MAJwAAATYzMhUUBwYHBiMmJyYvASYjIgcGDwEXNjMyFxMWNzITEj8BJicjBgI/JyJEAQQ/Px8oIgcJ
GBlpBwYzYZMwQwszLVI7WI7LxgYBAZELyQLSEUkKCzZxbQGoGT+ksgEHXZBCM7H+ubMBASQBF6IavgUBAAsAAAA
998
AA+oDjwAKABcAMgBaAGsAcwCMAJkAsgDLANQAAAEGFQczNzQmKwEiJwYdARQWMjY9ATQmIicXFAYXFjY3NiY9AT
MVJzcOAiImLwEmNjUnJRYXHgEXHgEdASMVFBY7ATI2PQEzFhcUBwYHIyYnJj0BNDY3NjcyNycVNjMyFxYdARQOA
SYnDwERIxUjFSMRIzU3DgIdARQeAjMhMj4CPQE0LgIjISIlFh0BFAYiJj0BNDYyFxUUHgEXHgEzMjc2NwczNSMV
FAYiJj0BIwcOAQcVFBYXHgEyNz4BNzY9ATQmJy4BIyIHFTM1NyMHJyMDGAkBQgETDQMN3gkTGBITF/ABAQEIHQM
EAkU5AgYaHyAZAQMCAgICHQsKFR4DAwJ3EAwKDBE0AgEUGyMHHxwfEhQQFQgI9CAYDgogEh4sHAU50FNFRyAeLB
sbLDwhAqAiPCwaGi07Iv1gIQF7CRMYEhIYewMCAwcVEQ8MCQsBTDwPFg1BvhQQAQsJCScxEhAbAgQJCQwlHB/TS
VZQLS5QAWIGCBsbCQsEBQd/BwoKB38HChSJDREDEAkIAhAPiNkBGwcOCAwKEwUWD4cNAQEEEg8IIBEeNAkKCgkY
CQgYDxQCARESKkQeIgoIAwE/VREEDiBxFB8OCBESAgEjJ/4BACVICBwnFvEWJh0QEB0mFvEWJxwR8QYKdwoNDgl
3Cg17GAkKCgQKCgUGCxLgrgcKCgeuAgkoHjseHwkLCgYFHQwOHzoXGgoODEOsrJNubgAAAAAEAAAAAAPnA+wANA
BLAGIAfAAAATIWFxYXFgcOAQcGFxYXFhcWNzY3NhcWFxYXFhcUBw4BIyYnLgEnLgEnJicmNjc2Nz4BMzI3DgEHB
hcWDwE3Njc2FxY3PgEnLgEnIgUWAgcGJyYnJg8BNzYnJjc+ATc2Mx4BJQQDBhYXFgcGDwE3NhcWNzY3NicuAScm
IyYBfxYMBQ8QCQ8HDAYNCh8sHB0LCQ8RCg00NAQBAgEBCTQYHx8uTyMnOw8KAwIMDAUFCRIKBTWFqwcGYAYDJQh
BQQgHpaZ7eBkf0YsiAcwwXoCMpjc0Dg7XNQMHYAgKooZIR47k/cv++w0DLS0EARISGfkKCnh/q26JJh7hnBcXZQ
LlCBInJhQPBg8GCgwxJhcWCAoQDgoFExUCBRQVAgMWJAEHDTEgIlIxJSYSHg0GBQgNpxvEh5ZzCAmEAxkaAgJQS
TnphY2nAeyV/uhYXRUHFQYGVNYKCIKhjdUuFwKgjX/+3k6NPwcHSkpiYgQELxYdhqnXmdARAgIAAAACAAAAAAPj
A+oAPABYAAABHgIUBiMiJicuASMiBhUUHgIXHgMVFA4BIyInLgE1NDYzMhYXHgIzMjY1NC4BJy4CNTQ+ATMyBRQ
XBhUWABcyNxYXPgE3NCc2NSYAJwYHJicOAQJmLz4dJh0aHA8RMTYzPBMlJy06XUQmQn1VZUMwPCceGCILDRwzKz
pHJT82SmQ9QHZPQP3SJQkFAQnILCo6R3SZAxwLBf72xyonQFF0mgMuDzA3NCgYGiIkJxoQGBILCgweLEQxOl00I
xpWKholHRodJRkxIxsjFAsQK0w4NVMsYk09LjHI/vcFCCABA5p0QjcxNMgBCQYBBigBApoACAAAAAAD6gPTACUA
PwBTAGEAcgCfALIBGwAAASMGBwYVFBYXFjsBMjY/AT4BNzY3NjQnJicmIgcGByInJi8BJiIlBgcGFRQXFRYXFjM
yNzM2NzY1NCcmJyYjIgUOAQcGHQEUFhcWMzI2PQE0JiMiJRYXFhUUBwYHLgEnNjIhMzIfAQ4BByYnJj0BNjc2Ny
UWHwEeARceAR0BFAcGBwYHDgEHBisBIiYvAiYvATUjJyYnJjU0PgE3NjMyATIXFh0BDgErASImPQE0Njc2MycjB
gcmIyIHIw4BBw4BFQ4BDwEuASsBIg4CFRYXFhcGDwEUFhceARceATMyNjc+ATc2NTQvAT4BPQEuAScjJiMmBwYH
JiMnLgEnNDY3NjczHgEXFQYWFxYXMxY3PgE3NjU0JicjJiMmAU4BCAcDBwhHVgkpTiQLBQ0EBgIBAwQICg4IRFA
8NAcLDAcIASYSCwwBBBISGAcKAhAQCwQFEhEUCv7IERkFAxgTCQsYKCgYCAI1EgkGBwcJDikZDyX9DgUJCBEaKQ
4IBgkCEhUXAbAfHSc0XCAPEgIJGRYiNHc/CgsVP3o1CQkmHgMEBxMIBUJbM01VHQEkFQ4SAiAVAxUhGBIFCSoCJ
RQzMhMTAhkoDQ8KPXs2DRIsGgwZKyMVAhURHwEBARIRH2E1NGw4JUklRH0sMgECHSgDOSYBEg8qIAYKAwICNXY+
BwwOIwwWKRUBEg4eLA4sIhAUAwEpHgITGhQBFwMLBwwJEgQ4FBQGAwgGCAgDCgkLBQYELwEcAwwGA94HExEYCQQ
CGw0RBAQVExgLDBYPDAEEGhQEBgoZJgYFKR4FHCldDBQQDhMPDQkkOhoJAwYaOiMHDgwTBRwUFAMmBAcNEUIzGj
sfEwgILCgkHiotBgEfIwYFHiQFBgsgJBMZQWZEERwBARISGwMZIyIaAxghBAI8EiUZBQcmGyBGIwUhJAcQExcqM
x0nJB4VCAgRJEggPFAZGBgMCRRRQkpbCQkREUQqCDBIDAUBGgQJAwIjIwQcOBcjBQEOCQUbLBEmBAEjECsaBQko
RA4KAQAFAAAAAAPpA+oAEAAsADgATQCTAAABDgEHJi8BLgE1PgE3NjMeASUUFR4BFyE+ATcRNCYjIRYOAiYnJjc
nBiciBgUeARc+ATcuAScOAQEyFhUWBxQHBgcGJyImJzU2NzY3MyUWFRQGIyImNTc0Jg4BFRYVBhcWJwYmNzU3NC
cmBgcVFgYjIiY1NDUjBgcGFhUUFjchFjc+ARcWNyEyNjU0NicuASchJgYChwJTPDIlAxkdAkU1Cgs/UP1/A25SA
l5RbgMFBv7oOhuBp5YeLEoFiYkHAwEsA25TVW8BAm5TVHACOw4RAQEBBxc1NA4RAQEKCA01/c8BCBUHBQEICwoB
AQEBDBUKAQEDBhQBAQkTBwUERQkDAQcEASgIB0zCTgkMAScEBQECCGxK/ewHBQHuO1EBAR0CFD0kNU0JAQJSTNv
bUW4DA25QAbcHBVy1dxFbUX1vAQEBB45TbgICb1NUbgICbwFSEQ42NgUFFAEBAREOaxEIBwFGZ2gUCQYH4QgDAQ
EJOzs2NwwBAQoWyQUDAgINB8QUCAUHY2MzVSRIJAcCAQEGRgJFCQECBiNIJElkAgEGAAAAAAYAAAAAA+oD6gAPA
BsALQBcAGYAbgAAAQ4BBx4BFz4BNTQmLwEiBiUVMxUjFSM1IzUzNSUOARUUFhcyNjc+ATU0JiciBjcHIx4BFw4B
Bw4BFBYfAR4BFxQGBy4BNSY2Nz4BNy4BNTQ2NwYjLgE1NDY3PgEXAR4BFyE+ATcRITchLgEnIQ4BAQEPMAMBSD4
3OSgrEgYxAepzc05zc/5ACQgvMQ8bCg0GMS8QHPkxLw8lAgEmGQgNDQcbGiUBZmNTUQEbISVRHAkOBAQNDD1CGB
khSCD+pgNvUgJgU28C/BgBA+cGbVH9oFBtAUEEIigpMgEBLSQbKx0BBNRzTnNzTnNnDB0PKVkEDAkOHgssWwQOJ
xkMMSopMRIHEhgPBRUUMCY3VQIBPywVMhUUDQEKGBEKDQcCAkcuGjUVGhEB/hBTbgMDblMCPitQagEBagAAAAEA
AAAAA+UD6gAjAAATER4BFyERIzUzNT4BNzMVIyIGHQEzFSMRIT4BNxEuASchDgEIAR0VAcpvbwJXQo1BGSF7ewE
AFR0BAR0V/IkVHQOx/IsZIAEBm4ZQQlkChiEZLYb+ZQEgGQN1GSABASAAAAACAAAAAAPlA+oAEgAiAAABFTMVIx
EGFjcVBgQnESM1FjY3JREeARchPgE3ES4BIyEiBgIRy8sGQ5oW/sQjbgmIEv5gATAkAzMkMAEBMCT8zSQwA4TRf
v70ClIzeQsYfAFUawJjhBH8wyUwAQEwJQM9JTAwAAAAEgDeAAEAAAAAAAAAAQAAAAEAAAAAAAEABwABAAEAAAAA
AAIABwAIAAEAAAAAAAMABwAPAAEAAAAAAAQABwAWAAEAAAAAAAUACwAdAAEAAAAAAAYABwAoAAEAAAAAAAoALAA
vAAEAAAAAAAsAEgBbAAMAAQQJAAAAAgBtAAMAAQQJAAEADgBvAAMAAQQJAAIADgB9AAMAAQQJAAMADgCLAAMAAQ
999
QJAAQADgCZAAMAAQQJAAUAFgCnAAMAAQQJAAYADgC9AAMAAQQJAAoAWADLAAMAAQQJAAsAJAEjIGUtaWNvbnNSZ
Wd1bGFyZS1pY29uc2UtaWNvbnNWZXJzaW9uIDEuMGUtaWNvbnNGb250IGdlbmVyYXRlZCB1c2luZyBTeW5jZnVz
aW9uIE1ldHJvIFN0dWRpb3d3dy5zeW5jZnVzaW9uLmNvbQAgAGUALQBpAGMAbwBuAHMAUgBlAGcAdQBsAGEAcgB
lAC0AaQBjAG8AbgBzAGUALQBpAGMAbwBuAHMAVgBlAHIAcwBpAG8AbgAgADEALgAwAGUALQBpAGMAbwBuAHMARg
BvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAdQBzAGkAbgBnACAAUwB5AG4AYwBmAHUAcwBpAG8AbgAgAE0AZ
QB0AHIAbwAgAFMAdAB1AGQAaQBvAHcAdwB3AC4AcwB5AG4AYwBmAHUAcwBpAG8AbgAuAGMAbwBtAAAAAAIAAAAA
AAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAECAQMBBAEFAQYBBwEIAQkBCgELAQwBDQAHdHdpdHRlcgx0d2l
0dGVyLWJpcmQFdmltZW8IeW91dHViZTEId2hhdHNhcHAIc2t5cGUtMDEGcmVkZGl0CWluc3RhZ3JhbQtnb29nbG
UtcGx1cwhmYWNlYm9vawZ0dW1ibHIAAA==) format('truetype');
font-weight: normal;
font-style: normal;
}
/* csslint ignore:end */
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
cursor: pointer;
}
.media {
font-size: 17px;
}
.icon {
font-family: 'e-icons';
margin: 4px 28px 0 -12px;
color: black;
color: rgba(0, 0, 0, .57);
line-height: 1.9;
font-size: 12px;
height: 20px;
width: 20px;
}
.twitter:before {
content: "\e700";
margin: 8px
}
.vimeo:before {
content: "\e702";
margin: 8px
}
.youtube:before {
content: "\e703";
1000
margin: 8px
}
.skype:before {
content: "\e706";
margin: 8px
}
.instagram:before {
content: "\e708";
margin: 8px
}
.google-plus:before {
content: "\e709";
margin: 8px
}
.facebook:before {
content: "\e70a";
margin: 8px
}
.tumblr:before {
content: "\e70b";
margin: 8px
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult customizetemplate()
{
List<object> listdata = new List<object>();
listdata.Add(new {css= "facebook", socialMedia= "Facebook", id= "media1" })
;
listdata.Add(new { css= "twitter", socialMedia= "Twitter", id= "media2" });
1001
listdata.Add(new { css= "tumblr", socialMedia= "Tumblr", id= "media4" });
listdata.Add(new { css= "google-plus", socialMedia= "Google Plus", id= "med
ia5" });
listdata.Add(new { css= "skype", socialMedia= "Skype", id= "media6" });
listdata.Add(new { css= "vimeo", socialMedia= "Vimeo", id= "media7" });
listdata.Add(new { css= "instagram", socialMedia= "Instagram", id= "media8"
});
listdata.Add(new { css= "youtube", socialMedia= "YouTube", id= "media9" });
ViewBag.dataSource = listdata;
return View();
}
}
}
Group template
The ListView has an option to custom design the group header title with the help of
groupTemplate property.
This template is common for both the inline and floating group header template.
razor
grouptemplate.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource)
.Fields(new ListViewFieldSettings { Text = "socialMedia", GroupBy = "category" }).ShowH
eader(true).HeaderTitle("Social Media").Template("<span class='${css} icon'><span class
='media'>${socialMedia}</span></span>").GroupTemplate("<span class='group icon'><span>$
{socialMedia}</span></span>").Render()
}
<style>
/* csslint ignore:start */
@font-face {
font-family: 'e-icons';
src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT
1MvMj0gSR4AAAEoAAAAVmNtYXDOVM6ZAAABsAAAAFJnbHlm7gIZ8wAAAiAAAA1YaGVhZA0acjMAAADQAAAANmho
ZWEHmQN1AAAArAAAACRobXR4LvgAAAAAAYAAAAAwbG9jYRUsEYgAAAIEAAAAGm1heHABIQEoAAABCAAAACBuYW1
lc0cOBgAAD3gAAAIlcG9zdEs6jNMAABGgAAAAoAABAAADUv9qAFoEAAAA//4D6gABAAAAAAAAAAAAAAAAAAAADA
ABAAAAAQAAgbXF1F8PPPUACwPoAAAAANUJFrEAAAAA1QkWsQAAAAAD6gPsAAAACAACAAAAAAAAAAEAAAAMARwAC
1002
wAAAAAAAgAAAAoACgAAAP8AAAAAAAAAAQPqAZAABQAAAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAUGZFZABA5wDnCwNS/2oAWgPsAJYAAAABAAAAAAAABAAAAAPoAAAD6AAAA+gAAAPoAAA
D6AAAA+gAAAPoAAAD6AAAA+gAAAPoAAAD6AAAAAAAAgAAAAMAAAAUAAMAAQAAABQABAA+AAAABgAEAAEAAucE5w
v//wAA5wDnBv//AAAAAAABAAYADgAAAAEAAgADAAQABQAGAAcACAAJAAoACwAAAAAAAAAsAH4AvgHgAqYDJgS2B
ZIGOgZyBqwAAAABAAAAAAMwA+oAHAAAEwYVERQWOwE+ATQmKwEiJj0BITI2NCYjITU0JgbbH7mC0Cw+PizQLDwB
KSg5OSn+2D5XA8YkNf4LmtwBSWdKSDNYRV9EtjNKAQAAAQAAAAAD6gNGADIAAAEUFy4BJwYHHgEXJicVHgEXBiM
iJx4BFw4BIyInHgEzJAA3NCc2NwYHPgE3BgcuASMOAQHqBYHZTRsBATEqMyoBW0gaHBQSFGdENYFIGRhEn1cBHA
ErAQE9KTc+IC4MPEYdTSxXdAKdFBMGXU4mLy1JFwITAj9aDQYDM0ECIiYCJCgJASixCwskNBUGEDAeHgwZHQJfA
AABAAAAAAPqA9MAJwAAATYzMhUUBwYHBiMmJyYvASYjIgcGDwEXNjMyFxMWNzITEj8BJicjBgI/JyJEAQQ/Px8o
IgcJGBlpBwYzYZMwQwszLVI7WI7LxgYBAZELyQLSEUkKCzZxbQGoGT+ksgEHXZBCM7H+ubMBASQBF6IavgUBAAs
AAAAAA+oDjwAKABcAMgBaAGsAcwCMAJkAsgDLANQAAAEGFQczNzQmKwEiJwYdARQWMjY9ATQmIicXFAYXFjY3Ni
Y9ATMVJzcOAiImLwEmNjUnJRYXHgEXHgEdASMVFBY7ATI2PQEzFhcUBwYHIyYnJj0BNDY3NjcyNycVNjMyFxYdA
RQOASYnDwERIxUjFSMRIzU3DgIdARQeAjMhMj4CPQE0LgIjISIlFh0BFAYiJj0BNDYyFxUUHgEXHgEzMjc2Nwcz
NSMVFAYiJj0BIwcOAQcVFBYXHgEyNz4BNzY9ATQmJy4BIyIHFTM1NyMHJyMDGAkBQgETDQMN3gkTGBITF/ABAQE
IHQMEAkU5AgYaHyAZAQMCAgICHQsKFR4DAwJ3EAwKDBE0AgEUGyMHHxwfEhQQFQgI9CAYDgogEh4sHAU50FNFRy
AeLBsbLDwhAqAiPCwaGi07Iv1gIQF7CRMYEhIYewMCAwcVEQ8MCQsBTDwPFg1BvhQQAQsJCScxEhAbAgQJCQwlH
B/TSVZQLS5QAWIGCBsbCQsEBQd/BwoKB38HChSJDREDEAkIAhAPiNkBGwcOCAwKEwUWD4cNAQEEEg8IIBEeNAkK
CgkYCQgYDxQCARESKkQeIgoIAwE/VREEDiBxFB8OCBESAgEjJ/4BACVICBwnFvEWJh0QEB0mFvEWJxwR8QYKdwo
NDgl3Cg17GAkKCgQKCgUGCxLgrgcKCgeuAgkoHjseHwkLCgYFHQwOHzoXGgoODEOsrJNubgAAAAAEAAAAAAPnA+
wANABLAGIAfAAAATIWFxYXFgcOAQcGFxYXFhcWNzY3NhcWFxYXFhcUBw4BIyYnLgEnLgEnJicmNjc2Nz4BMzI3D
gEHBhcWDwE3Njc2FxY3PgEnLgEnIgUWAgcGJyYnJg8BNzYnJjc+ATc2Mx4BJQQDBhYXFgcGDwE3NhcWNzY3Nicu
AScmIyYBfxYMBQ8QCQ8HDAYNCh8sHB0LCQ8RCg00NAQBAgEBCTQYHx8uTyMnOw8KAwIMDAUFCRIKBTWFqwcGYAY
DJQhBQQgHpaZ7eBkf0YsiAcwwXoCMpjc0Dg7XNQMHYAgKooZIR47k/cv++w0DLS0EARISGfkKCnh/q26JJh7hnB
cXZQLlCBInJhQPBg8GCgwxJhcWCAoQDgoFExUCBRQVAgMWJAEHDTEgIlIxJSYSHg0GBQgNpxvEh5ZzCAmEAxkaA
gJQSTnphY2nAeyV/uhYXRUHFQYGVNYKCIKhjdUuFwKgjX/+3k6NPwcHSkpiYgQELxYdhqnXmdARAgIAAAACAAAA
AAPjA+oAPABYAAABHgIUBiMiJicuASMiBhUUHgIXHgMVFA4BIyInLgE1NDYzMhYXHgIzMjY1NC4BJy4CNTQ+ATM
yBRQXBhUWABcyNxYXPgE3NCc2NSYAJwYHJicOAQJmLz4dJh0aHA8RMTYzPBMlJy06XUQmQn1VZUMwPCceGCILDR
wzKzpHJT82SmQ9QHZPQP3SJQkFAQnILCo6R3SZAxwLBf72xyonQFF0mgMuDzA3NCgYGiIkJxoQGBILCgweLEQxO
l00IxpWKholHRodJRkxIxsjFAsQK0w4NVMsYk09LjHI/vcFCCABA5p0QjcxNMgBCQYBBigBApoACAAAAAAD6gPT
ACUAPwBTAGEAcgCfALIBGwAAASMGBwYVFBYXFjsBMjY/AT4BNzY3NjQnJicmIgcGByInJi8BJiIlBgcGFRQXFRY
XFjMyNzM2NzY1NCcmJyYjIgUOAQcGHQEUFhcWMzI2PQE0JiMiJRYXFhUUBwYHLgEnNjIhMzIfAQ4BByYnJj0BNj
c2NyUWHwEeARceAR0BFAcGBwYHDgEHBisBIiYvAiYvATUjJyYnJjU0PgE3NjMyATIXFh0BDgErASImPQE0Njc2M
ycjBgcmIyIHIw4BBw4BFQ4BDwEuASsBIg4CFRYXFhcGDwEUFhceARceATMyNjc+ATc2NTQvAT4BPQEuAScjJiMm
BwYHJiMnLgEnNDY3NjczHgEXFQYWFxYXMxY3PgE3NjU0JicjJiMmAU4BCAcDBwhHVgkpTiQLBQ0EBgIBAwQICg4
IRFA8NAcLDAcIASYSCwwBBBISGAcKAhAQCwQFEhEUCv7IERkFAxgTCQsYKCgYCAI1EgkGBwcJDikZDyX9DgUJCB
EaKQ4IBgkCEhUXAbAfHSc0XCAPEgIJGRYiNHc/CgsVP3o1CQkmHgMEBxMIBUJbM01VHQEkFQ4SAiAVAxUhGBIFC
SoCJRQzMhMTAhkoDQ8KPXs2DRIsGgwZKyMVAhURHwEBARIRH2E1NGw4JUklRH0sMgECHSgDOSYBEg8qIAYKAwIC
NXY+BwwOIwwWKRUBEg4eLA4sIhAUAwEpHgITGhQBFwMLBwwJEgQ4FBQGAwgGCAgDCgkLBQYELwEcAwwGA94HExE
YCQQCGw0RBAQVExgLDBYPDAEEGhQEBgoZJgYFKR4FHCldDBQQDhMPDQkkOhoJAwYaOiMHDgwTBRwUFAMmBAcNEU
IzGjsfEwgILCgkHiotBgEfIwYFHiQFBgsgJBMZQWZEERwBARISGwMZIyIaAxghBAI8EiUZBQcmGyBGIwUhJAcQE
xcqMx0nJB4VCAgRJEggPFAZGBgMCRRRQkpbCQkREUQqCDBIDAUBGgQJAwIjIwQcOBcjBQEOCQUbLBEmBAEjECsa
BQkoRA4KAQAFAAAAAAPpA+oAEAAsADgATQCTAAABDgEHJi8BLgE1PgE3NjMeASUUFR4BFyE+ATcRNCYjIRYOAiY
nJjcnBiciBgUeARc+ATcuAScOAQEyFhUWBxQHBgcGJyImJzU2NzY3MyUWFRQGIyImNTc0Jg4BFRYVBhcWJwYmNz
U3NCcmBgcVFgYjIiY1NDUjBgcGFhUUFjchFjc+ARcWNyEyNjU0NicuASchJgYChwJTPDIlAxkdAkU1Cgs/UP1/A
25SAl5RbgMFBv7oOhuBp5YeLEoFiYkHAwEsA25TVW8BAm5TVHACOw4RAQEBBxc1NA4RAQEKCA01/c8BCBUHBQEI
CwoBAQEBDBUKAQEDBhQBAQkTBwUERQkDAQcEASgIB0zCTgkMAScEBQECCGxK/ewHBQHuO1EBAR0CFD0kNU0JAQJ
STNvbUW4DA25QAbcHBVy1dxFbUX1vAQEBB45TbgICb1NUbgICbwFSEQ42NgUFFAEBAREOaxEIBwFGZ2gUCQYH4Q
gDAQEJOzs2NwwBAQoWyQUDAgINB8QUCAUHY2MzVSRIJAcCAQEGRgJFCQECBiNIJElkAgEGAAAAAAYAAAAAA+oD6
gAPABsALQBcAGYAbgAAAQ4BBx4BFz4BNTQmLwEiBiUVMxUjFSM1IzUzNSUOARUUFhcyNjc+ATU0JiciBjcHIx4B
1003
Fw4BBw4BFBYfAR4BFxQGBy4BNSY2Nz4BNy4BNTQ2NwYjLgE1NDY3PgEXAR4BFyE+ATcRITchLgEnIQ4BAQEPMAM
BSD43OSgrEgYxAepzc05zc/5ACQgvMQ8bCg0GMS8QHPkxLw8lAgEmGQgNDQcbGiUBZmNTUQEbISVRHAkOBAQNDD
1CGBkhSCD+pgNvUgJgU28C/BgBA+cGbVH9oFBtAUEEIigpMgEBLSQbKx0BBNRzTnNzTnNnDB0PKVkEDAkOHgssW
wQOJxkMMSopMRIHEhgPBRUUMCY3VQIBPywVMhUUDQEKGBEKDQcCAkcuGjUVGhEB/hBTbgMDblMCPitQagEBagAA
AAEAAAAAA+UD6gAjAAATER4BFyERIzUzNT4BNzMVIyIGHQEzFSMRIT4BNxEuASchDgEIAR0VAcpvbwJXQo1BGSF
7ewEAFR0BAR0V/IkVHQOx/IsZIAEBm4ZQQlkChiEZLYb+ZQEgGQN1GSABASAAAAACAAAAAAPlA+oAEgAiAAABFT
MVIxEGFjcVBgQnESM1FjY3JREeARchPgE3ES4BIyEiBgIRy8sGQ5oW/sQjbgmIEv5gATAkAzMkMAEBMCT8zSQwA
4TRfv70ClIzeQsYfAFUawJjhBH8wyUwAQEwJQM9JTAwAAAAEgDeAAEAAAAAAAAAAQAAAAEAAAAAAAEABwABAAEA
AAAAAAIABwAIAAEAAAAAAAMABwAPAAEAAAAAAAQABwAWAAEAAAAAAAUACwAdAAEAAAAAAAYABwAoAAEAAAAAAAo
ALAAvAAEAAAAAAAsAEgBbAAMAAQQJAAAAAgBtAAMAAQQJAAEADgBvAAMAAQQJAAIADgB9AAMAAQQJAAMADgCLAA
MAAQQJAAQADgCZAAMAAQQJAAUAFgCnAAMAAQQJAAYADgC9AAMAAQQJAAoAWADLAAMAAQQJAAsAJAEjIGUtaWNvb
nNSZWd1bGFyZS1pY29uc2UtaWNvbnNWZXJzaW9uIDEuMGUtaWNvbnNGb250IGdlbmVyYXRlZCB1c2luZyBTeW5j
ZnVzaW9uIE1ldHJvIFN0dWRpb3d3dy5zeW5jZnVzaW9uLmNvbQAgAGUALQBpAGMAbwBuAHMAUgBlAGcAdQBsAGE
AcgBlAC0AaQBjAG8AbgBzAGUALQBpAGMAbwBuAHMAVgBlAHIAcwBpAG8AbgAgADEALgAwAGUALQBpAGMAbwBuAH
MARgBvAG4AdAAgAGcAZQBuAGUAcgBhAHQAZQBkACAAdQBzAGkAbgBnACAAUwB5AG4AYwBmAHUAcwBpAG8AbgAgA
E0AZQB0AHIAbwAgAFMAdAB1AGQAaQBvAHcAdwB3AC4AcwB5AG4AYwBmAHUAcwBpAG8AbgAuAGMAbwBtAAAAAAIA
AAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAECAQMBBAEFAQYBBwEIAQkBCgELAQwBDQAHdHdpdHRlcgx
0d2l0dGVyLWJpcmQFdmltZW8IeW91dHViZTEId2hhdHNhcHAIc2t5cGUtMDEGcmVkZGl0CWluc3RhZ3JhbQtnb2
9nbGUtcGx1cwhmYWNlYm9vawZ0dW1ibHIAAA==) format('truetype');
font-weight: normal;
font-style: normal;
}
/* csslint ignore:end */
#element {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
cursor: pointer;
}
.e-list-group-item .group {
font-size: 25px;
line-height: 32px;
margin-left: -5px;
}
.text {
margin: 437px;
line-height: 2;
}
.media {
font-size: 17px;
}
.icon {
font-family: 'e-icons';
1004
margin: 4px 28px 0 -12px;
color: black;
color: rgba(0, 0, 0, .57);
line-height: 1.9;
font-size: 12px;
height: 20px;
width: 20px;
}
.twitter:before {
content: "\e700";
margin: 8px
}
.youtube:before {
content: "\e703";
margin: 8px
}
.instagram:before {
content: "\e708";
margin: 8px
}
.facebook:before {
content: "\e70a";
margin: 8px
}
.tumblr:before {
content: "\e70b";
margin: 8px
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult grouptemplate()
{
1005
List<object> listdata = new List<object>();
listdata.Add(new {css= "facebook", socialMedia= "Facebook", category = "F"
});
listdata.Add(new { css= "twitter", socialMedia= "Twitter", category = "T" }
);
listdata.Add(new { css= "tumblr", socialMedia= "Tumblr", category = "T" });
1006
UI Virtualization
UI virtualization loads only viewable list items in a view port, which will improve the ListView
performance while loading a large number of data.
Getting started
UI virtualization can be enabled in the ListView by setting the enableVirtualization property to
true.
Container scroll: This scroller is used, when the height property of the ListView is set.
razor
virtualization.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("ui-list").DataSource((IEnumerable<object>)ViewBag.listData).E
nableVirtualization(true).Render()
}
<style>
#ui-list {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
cursor: pointer;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
1007
{
public class ListViewController : Controller
{
public IActionResult nestedlist()
{
List<object> listData = new List<object>();
listData.Add(new { listData = "Nancy", id = "0" });
listData.Add(new { listData = "Andrew", id = "1" });
listData.Add(new { listData = "Janet", id = "2" });
listData.Add(new { listData = "Margaret", id = "3" });
listData.Add(new { listData = "Steven", id = "4" });
listData.Add(new { text = "Laura", id = "5" });
listData.Add(new { text = "Robert", id = "6" });
listData.Add(new { text = "Michael", id = "7" });
listData.Add(new { text = "Albert", id = "8" });
listData.Add(new { text = "Nolan", id = "9" });
ViewBag.listData = listData;
return View();
}
}
}
razor
virtualization.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@{ var template = "<div class='list-container'><div id='icon' class=\"${$imgUrl ? \'img
\' : $icon }\">" +
"<span class=\"${$imgUrl ? \'hideUI\' : \'showUI\' }\">" +
"${icon}</span> <img class=\"${$imgUrl ? \'showUI\' : \'hideUI\' }\" width =
45 height = 45 src=\"${$imgUrl ? $imgUrl : \' \' }\" />" +
1008
"</div><div class='text'>${text}</div></div>";
}
@Html.EJS().ListView("ui-list").DataSource((IEnumerable<object>)ViewBag.listData).E
nableVirtualization(true).ShowHeader(true).HeaderTitle("Contacts").Template(@template).
Height(500).Render()
}
<style>
#ui-list {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
cursor: pointer;
}
button {
float: right
}
#icon {
width: 45px;
height: 45px;
text-align: center;
line-height: 45px;
border-radius: 50%;
font-size: 20px;
font-weight: 500;
float: left;
margin-top: 17px;
margin-right: 35px;
}
img {
border-radius: 50%;
border: #ddd;
border: 1px solid rgba(40, 40, 40, 0.12);
}
.R {
background: purple;
}
.M {
background: pink;
}
1009
.A {
background: green;
}
.S {
background: lightskyblue;
}
.J {
background: orange;
}
.N {
background: blue;
}
#ui-list .e-list-item {
height: 80px;
border: #ddd;
border: 1px solid rgba(184, 184, 184, 0.12);
}
.list-container {
width: inherit;
height: 100%;
.showUI {
display: inline;
}
.hideUI {
display: none;
}
.content {
height: 100%;
float: left;
}
.name {
height: 100%;
font-size: 20px;
font-weight: 600;
line-height: 78px;
}
</style>
1010
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult nestedlist()
{
List<object> listData = new List<object>();
listData.Add(new { text = "Nancy", imgUrl = "", icon = "N", id = "0" });
listData.Add(new { text = "Andrew", imgUrl = "", icon = "A", id = "1" });
listData.Add(new { text = "Janet", imgUrl = "", icon = "J", id = "2" });
listData.Add(new { text = "Margaret", icon = "", imgUrl = "./margaret.png",
id = "3" });
listData.Add(new { text = "Steven", imgUrl = "", icon = "S", id = "4" });
listData.Add(new { text = "Laura", icon = "", imgUrl = "./images/laura.png"
, id = "5" });
listData.Add(new { text = "Robert", imgUrl = "", icon = "R", id = "6" });
listData.Add(new { text = "Michael", imgUrl = "", icon = "M", id = "7" });
listData.Add(new { text = "Albert", icon = "", imgUrl = "./images/albert.pn
g", id = "8" });
listData.Add(new { text = "Nolan", imgUrl = "", icon = "N", id = "9" });
ViewBag.listData = listData;
return View();
}
1011
}
}
Conditional rendering
The following conditional rendering support is provided for the template and groupTemplate.
Name Syntax
<div class="${ $id % 2 === 0 ? 'even-list' : 'odd-list'}">
conditional class </div>
In the following sample, the light blue is applied for the even list and light coral is applied for the
odd list based on the conditional class.
razor
virtualization.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("ui-list").DataSource((IEnumerable<object>)ViewBag.listData).E
nableVirtualization(true).Template(@template).Height(500).Render()
}
<style>
#ui-list {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
cursor: pointer;
}
#list-container{
height: inherit;
width: inherit;
padding-left: 30px;
1012
}
#ui-list .e-list-item{
padding: 0;
}
#ui-list .even-list{
background-color: #cfd8dc;
}
#ui-list .odd-list{
background-color: #eceff1;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult nestedlist()
{
List<object> listData = new List<object>();
listData.Add(new { listData = "Nancy", id = "0" });
listData.Add(new { listData = "Andrew", id = "1" });
listData.Add(new { listData = "Janet", id = "2" });
listData.Add(new { listData = "Margaret", id = "3" });
listData.Add(new { listData = "Steven", id = "4" });
listData.Add(new { text = "Laura", id = "5" });
listData.Add(new { text = "Robert", id = "6" });
listData.Add(new { text = "Michael", id = "7" });
listData.Add(new { text = "Albert", id = "8" });
listData.Add(new { text = "Nolan", id = "9" });
1013
istData[index], null).ToString(),
id = i.ToString()
});
}
ViewBag.listData = listData;
return View();
}
}
}
1014
Accessibility
Keyboard interaction
The following key shortcuts are used to access the ListView component without any interruption.
razor
accessibility.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@section ControlsSection{
@Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewBag.dataSource
).Fields(new ListViewFieldSettings { Tooltip = "text" }).ShowHeader(true).HeaderTitle("
Continent").Render()
}
<style>
#listview {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
1015
public class ListViewController : Controller
{
public IActionResult accessibility()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Asia",
id = "01",
category = "Continent",
child = new List<object>() { new { text = "India", id = "1", category =
"Asia",
child= new List<object>() {
new { id= "1001", text= "Delhi", category= "India" },
new {text= "Kashmir", id= "1002", category= "India"},
new { text= "Goa",id= "1003", category= "India" }
}
},
new { text = "China",id = "2",category = "Asia",
child = new List<object>() {
new { text = "Zhejiang", id = "2001", category = "China" },
new {text= "Hunan",id= "2002", category= "China"},
new { text= "Shandong", id= "2003",category= "China"}
}
}
}
});
listdata.Add(new
{
text = "North America",
id = "02",
category = "Continent",
child = new List<object>() { new { text = "USA", id = "3", category = "
North America",
child= new List<object>() {
new {text= "California", id= "3001", category= "USA"},
new { text= "New York",id= "3002", category= "USA" },
new { text= "Florida",id= "3003", category= "USA" }
}
},
new { text = "Canada",id = "4",category = "North America",
child = new List<object>() {
new { text = "Ontario", id = "4001", category = "Canada" },
new {text= "Alberta",id= "4002", category= "Canada"},
new { text= "Manitoba", id= "4003",category= "Canada"}
}
}
}
});
1016
listdata.Add(new
{
text = "Europe",
id = "03",
category = "Continent",
child = new List<object>() { new { text = "Germany", id = "5", category
= "Europe",
child= new List<object>() {
new {text= "Berlin", id= "5001", category= "Germany"},
new { text= "Bavaria",id= "5002", category= "Germany" },
new { text= "Hesse",id= "5003", category= "Germany" }
}
},
new { text = "France",id = "6",category = "Europe",
child = new List<object>() {
new { text = "Paris", id = "6001", category = "France" },
new {text= "Lyon",id= "6002", category= "France"},
new { text= "Marseille", id= "6003",category= "France"}
}
}
}
});
listdata.Add(new
{
text = "Australia",
id = "04",
category = "Continent",
child = new List<object>() { new { text = "Australia", id = "7", catego
ry = "Australia",
child= new List<object>() {
new {text= "Sydney", id= "7001", category= "Australia"},
new { text= "Melbourne",id= "7002", category= "Australia" },
new { text= "Brisbane",id= "7003", category= "Australia" }
}
},
new { text = "New Zealand",id = "8",category = "Australia",
child = new List<object>() {
new { text = "Milford Sound", id = "8001", category = "New Ze
aland" },
new {text= "Tongariro National Park",id= "8002", category=
"New Zealand"},
new { text= "Fiordland National Park", id= "8003",category=
"New Zealand"}
}
},
}
});
listdata.Add(new
1017
{
text = "Africa",
id = "05",
category = "Continent",
child = new List<object>() { new { text = "Morocco", id = "9", category
= "Africa",
child= new List<object>() {
new {text= "Rabat", id= "9001", category= "Morocco"},
new { text= "Toubkal",id= "9002", category= "Morocco" },
new { text= "Todgha Gorge",id= "9003", category= "Morocco" }
}
},
new { text = "South Africa",id = "10",category = "Africa",
child = new List<object>() {
new { text = "Cape Town", id = "10001", category = "South Afr
ica" },
new {text= "Pretoria",id= "10002", category= "South Africa"
},
new { text= "Bloemfontein", id= "10003",category= "South Afr
ica"}
}
},
}
});
ViewBag.dataSource = listdata;
return View();
}
}
}
ARIA attributes
The following ARIA attributes are applicable for ListView component based on its state.
Properties Functionality
1018
Overview
The MaskedTextBox allows the user to enter the valid input based on the provided mask only.
Key features
Custom Characters: Allows to use your own characters as the mask elements.
Regular Expression: Uses as a mask element for each character of the MaskedTextBox.
Accessibility: Provides built-in accessibility support that helps to access all the
MaskedTextBox component features through the keyboard, on-screen readers, or other
assistive technology devices.
1019
Getting Started
This section briefly explains about how to include a simple MaskedTextBox in your ASP.NET
MVC application. You can refer ASP.NET MVC Getting Started documentation page for
introduction part part of the system requirements and configure the common specifications.
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Placeholder("MaskedTextBox").Render()
The following example demonstrates the usage of mask element 0 that allows any single digit
from 0 to 9 .
razor
mask.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Placeholder("MaskedTextBox").Fl
oatLabelType(FloatLabelType.Always).Render()
1020
public ActionResult Mask()
{
return View();
}
1021
Mask Configuration
The mask is a combination of standard and custom mask elements that validates the user input
based on its behavior.
When the mask value is empty, the MaskedTextBox behaves as an input element with text
type.
The mask can be formed by combining any one or more of these mask elements.
0 Digit required. This element will accept any single digit from 0 to 9.
All other Literals. All non-mask elements (literals) will appear as themselves within
characters MaskedTextBox.
razor
standardmasks.cs
@section ControlsSection{
1022
FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask2").Mask("LLLLLL").Placeholder("Mask LLLLLL (ex: Sample)"
).FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask3").Mask("&&&&&").Placeholder("Mask &&&&& (ex: A12@#)").
FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask4").Mask(">LLL<LLL").Placeholder("Mask >LLL<LL (ex: SAMp
le)").FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask5").Mask("\\A999").Placeholder("Mask \\A999 (ex: A321)")
.FloatLabelType(FloatLabelType.Always).Render()
Custom characters
You can define any of the non-mask element as the mask element and its behavior through the
customCharacters property.
razor
custom-mask.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Mask("00:00 >PM").CustomCharacters(ViewBag.cusObj).P
laceholder("Time (ex: 10:00 PM, 10:00 AM)").FloatLabelType(FloatLabelType.Always).Rende
r()
namespace EJ2CoreSampleBrowser.Controllers.MaskedTextbox
1023
{
public partial class MaskedTextboxController : Controller
{
}
}
public class CustomCharacters
{
public string P { get; set; }
public string M { get; set; }
}
Regular expression
Instead of the mask element, you can define your own regular expression to validate the input of
a particular input place. The regular expressions should be wrapped by the square brackets (e.g.,
[ Regex ]).
In the following example, regular expression has been set for each input places.
razor
regularExpression.cs
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
<form id="form-element" class="form-horizontal">
<div class="form-group">
<div class="control-label">IP Address (ex: 212.212.111.222)</div>
@Html.EJS().MaskedTextBox("mask1").Mask("[0-2][0-9][0-9].[0-2][0-9]
[0-9].[0-2][0-9][0-9].[0-2][0-9][0-9]").Created("onCreate").Render()
</div>
</form>
</div>
</div>
<script>
var customFn = function (args) {
1024
var mask = document.getElementById('mask1').ej2_instances[0];
var maskValue =mask.element.value;
var splitedValues = maskValue.split('.');
var returnedvalue = true;
if (mask.value.length != 0) {
for (var i = 0; i < splitedValues.length; i++) {
if (parseInt(splitedValues[i]) > 255) {
returnedvalue = false;
}
}
return returnedvalue;
}
else {
return true;
}
};
//value is returned based on the length of mask
var custom = function (args) {
var mask = document.getElementById('mask1').ej2_instances[0];
var dateValue = mask.element.value;
var date = new Date(dateValue);
if (mask.value.length == 0 && date.toString() !== "Invalid IP Address") {
return 0;
}
else {
return mask.value.length;
}
};
// places error label outside the MaskedTextBox using the customPlacement event
of FormValidator
formObject.customPlacement = function (element, errorElement) {
element.parentNode.parentNode.appendChild(errorElement);
};
function onCreate() {
document.getElementById(this.element.id).setAttribute("name", "mask_value")
1025
;
}
</script>
<style>
.content-wrapper {
width: 45%;
margin: 0 auto;
min-width: 185px;
max-width: 350px;
}
.control-label {
padding-right: 200px;
font-size: 12px;
}
.e-mask.e-control-wrapper {
margin-bottom: 20px;
width: 250px
}
label.e-error {
margin-top: -1px;
}
#container {
visibility: hidden;
}
#loader {
color: #008cff;
font-family: 'Helvetica Neue','calibiri';
font-size: 14px;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
.control-section {
min-height: 200px;
}
1026
</style>
}
namespace EJ2CoreSampleBrowser.Controllers.MaskedTextbox
{
public partial class MaskedTextboxController : Controller
{
Prompt character
The Prompt character is a prompting symbol in the MaskedTextBox for the mask elements. The
symbol is used to show the input positions in the MaskedTextBox. You can customize the prompt
character of MaskedTextBox by using the promptChar property.
The following example demonstrates the MaskedTextBox with customized prompt character as
* .
razor
prompt.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Mask("999-999-9999").PromptChar("#").Render()
1027
Accessibility
The MaskedTextBox is characterized with complete ARIA Accessibility support that helps to
access through the on-screen readers and other assistive technology devices. This component is
designed with the reference of the guidelines document given in WAI ARAI Accessibility
practices.
The MaskedTextBox uses the textbox role and following ARIA properties for its element based
on its state.
Property Functionality
aria-live The aria-live attribute indicates the priority of updates to a live region.
The aria-invalid property indicates that the user input is incorrect or not
aria-invalid
within the acceptable ranges.
aria- The aria-placeholder is a short hint to help the users with data entry when
placeholder the MaskedTextBox has no value.
aria- The aria-labelledby property indicates the floating label element of the
labelledby MaskedTextBox.
1028
How To
In the following example, the MaskedTextBox is validated for invalid mobile number by adding
custom validation in the rules collection of the FormValidator.
razor
howto.cs
@section ControlsSection{
<form id="form-element">
@Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Placeholder("Mobile Number"
).FloatLabelType(FloatLabelType.Always).Created("onCreate").Render()
@Html.EJS().Button("submit_btn").Content("Button").Render()
</form>
<script>
1029
// defines FormValidator to validate the MaskedTextBox
var formObject = new ej.inputs.FormValidator('#form-element', options);
formObject.addRules('mask', { maxLength: [custom, 'Enter mobile number'] });
// places error label outside the MaskedTextBox using the customPlacement event of
FormValidator
function onCreate() {
document.getElementById(this.element.id).setAttribute("name", "mask");
}
</script>
Following is an example that demonstrates the above cases to set cursor position in the
MaskedTextBox using focus event.
razor
1030
cursorPosition.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Mask("00000-00000").Value("93828-32132").Placeholder(
"Default cursor position").FloatLabelType(FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask2").Mask("00000-00000").Value("83929-43427").Placeholder(
"Cursor positioned at start").FloatLabelType(FloatLabelType.Always).Focus("onfocus").Re
nder()
@Html.EJS().MaskedTextBox("mask3").Mask("00000-00000").Value("83929-32131").Placeholder(
"Cursor positioned at end").FloatLabelType(FloatLabelType.Always).Focus("onfocus1").Ren
der()
@Html.EJS().MaskedTextBox("mask4").Mask("+1 000-000-0000").Value("234-432-4324").Placeh
older("Cursor at specified position").FloatLabelType(FloatLabelType.Always).Focus("onfo
cus2").Render()
}
<script>
function onfocus(args) {
//sets cursor position at start of MaskedTextBox
args.selectionEnd= args.selectionStart;
}
function onfocus1(args) {
//sets cursor position at end of MaskedTextBox
args.selectionStart=args.selectionEnd;
}
function onfocus2(args) {
//sets cursor at specified position
args.selectionStart = 3;
args.selectionEnd = 3;
}
</script>
1031
Display numeric keypad in MaskedTextBox for mobile
devices
By default, on focusing the MaskedTextBox, alphanumeric keypad will be displayed on mobile
devices. Sometimes only numeric keypad for number values is needed, and this can be achieved
by setting "type" property to tel . Refer to the following example to enable numeric keypad in
MaskedTextBox.
razor
numericKeypad.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Created("onCreate").Render()
}
<script>
function onCreate() {
var key = document.getElementById("mask1");
key.type = "tel";
}
</script>
razor
customCss.cs
@section ControlsSection{
@Html.EJS().MaskedTextBox("mask4").Mask("00000").Value("42648").cssClass("e-style").Pla
ceholder("Enter user ID").FloatLabelType(FloatLabelType.Always).Created("oncreated").Fo
cus("onfocus").Render()
1032
<script>
function onfocus(args) {
//sets cursor position at start of MaskedTextBox
args.selectionEnd= args.selectionStart;
}
</script>
<style>
.e-mask.e-style .e-control.e-maskedtextbox {
color: #00ffff ;
letter-spacing: 10px ;
font-size: xx-large ;
border: 1px ;
border-color: #ffffff ;
}
.e-control-wrapper.e-mask.e-float-input.e-style .e-float-line::before {
background: #ffffff ;
}
.e-control-wrapper.e-mask.e-float-input.e-style .e-float-line::after {
background: #ffffff ;
}
.e-control-wrapper.e-mask.e-float-input.e-style .e-float-text.e-label-top {
color: #00ffff ;
font-size: medium ;
}
</style>
1033
Overview
The RadioButton is a graphical user interface element that allows you to select only one option
from the choices. It contains checked and unchecked states.
Key Features
Supports different states.
Supports label and its position.
Supports small size.
1034
Getting Started
This section briefly explains about how to include a simple RadioButton in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("default").Render()
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("default").Render()
razor
default.cs
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("default").Render()
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("default").Render()
1035
Change the RadioButton state
The Essential JS 2 RadioButton contains 2 states visually, they are as follows:
Checked
Unchecked
The RadioButton checked property is used to handle the checked and unchecked state. In the
checked state an inner circle will be added to the visualization of RadioButton.
razor
state.cs
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("state").Checked(true).Render(
)
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("state").Render()
1036
Label and Size
This section explains the different sizes and labels.
Label
RadioButton caption can be defined by using the label property. This reduces the manual
addition of label for RadioButton. You can customize the label position before or after the
RadioButton through the labelPosition property.
razor
label.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("state").Checked(true).Re
nder()
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("state").Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
Size
1037
The different RadioButton sizes available are default and small. To reduce the size of the default
RadioButton to small, set the cssClass property to e-small .
razor
size.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Small").Name("size").CssClass("e-small").
Checked(true).Render()
@Html.EJS().RadioButton("radio2").Label("Default").Name("size").Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
1038
How To
The background and border color of the RadioButton is customized through the custom classes
to create the primary, success, info, warning, and danger type of RadioButton.
razor
custom.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Primary").Name("custom").CssClass("e-prim
ary").Render()
@Html.EJS().RadioButton("radio2").Label("Success").Name("custom").CssClass("e-succ
ess").Render()
@Html.EJS().RadioButton("radio3").Label("Info").Name("custom").CssClass("e-info").
Checked(true).Render()
@Html.EJS().RadioButton("radio4").Label("Warning").Name("custom").CssClass("e-warn
ing").Render()
@Html.EJS().RadioButton("radio5").Label("Danger").Name("custom").CssClass("e-dange
r").Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
1039
}
.e-radio:checked + .e-success::before {
border-color: #689f38;
}
.e-radio +.e-success:hover::before {
border-color: #b1afaf
}
.e-radio:checked + .e-info::after { /* csslint allow: adjoining-classes */
background-color: #2196f3;
}
.e-radio:checked + .e-info::before {
border-color: #2196f3;
}
.e-radio + .e-info:hover::before {
border-color: #b1afaf
}
.e-radio:checked + .e-warning::before {
border-color: #ef6c00;
}
1040
e {
border-color: #cc5c00;
}
.e-radio + .e-warning:hover::before {
border-color: #b1afaf
}
.e-radio:checked + .e-danger::before {
border-color: #d84315;
}
.e-radio + .e-danger:hover::before {
border-color: #b1afaf
}
</style>
razor
customheight.cs
1041
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("default").Checked(true).
Render()
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("default").Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
.e-radio + label::before {
height: 30px;
width: 30px;
}
.e-radio + label::after {
height: 28px;
width: 28px;
}
</style>
1042
return View();
}
In the following code snippet, Credit and Debit card is in checked state. Now, the value that is in
checked state will be sent on form submit.
razor
form.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Credit/Debit Card").Name("payment").Check
ed(true).Render()
@Html.EJS().RadioButton("radio2").Label("Net Banking").Name("payment").Render()
@Html.EJS().RadioButton("radio3").Label("Cash on Delivery").Name("payment").Render
()
@Html.EJS().RadioButton("radio4").Label("Others").Name("payment").Render()
@Html.EJS().Button("primarybtn").Content("Submit")IsPrimary(true).Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
button {
margin: 20px 0 0 5px;
}
li {
list-style: none;
}
</style>
1043
{
return View();
}
razor
disabled.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Option 1").Name("default").Checked(true).
Render()
@Html.EJS().RadioButton("radio2").Label("Option 2").Name("default").Disabled(true)
.Render()
@Html.EJS().RadioButton("radio3").Label("Option 3").Name("default").Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
button {
margin: 20px 0 0 5px;
}
li {
list-style: none;
}
</style>
1044
Right-To-Left
RadioButton component has RTL support. This can be achieved by setting enableRtl as
true .
The following example illustrates how to enable right-to-left support in RadioButton component.
razor
rtl.cs
@section ControlsSection{
@Html.EJS().RadioButton("radio1").Label("Default").Name("default").EnableRtl(true)
.Render()
}
<style>
.e-radio-wrapper {
margin-top: 18px;
}
li {
list-style: none;
}
</style>
1045
Overview
The Chart control is used to visualize the data with user interactivity and provides customizing
options to configure the data visually. It can bind data from datasource such as array of JSON
objects , OData web services or DataManager . All chart elements are rendered using Scalable
Vector Graphics (SVG).
Key Features
Supports 16 interactive chart types starting from line series to stacking series.
Support to bind local and remote datasource.
Supports multiple axes, and able to plot data with different data types such as numbers,
datetime, logarithmic and string.
Supports interactive features like zooming, crosshair, trackball, tooltip and selection.
1046
Getting Started
System Requirements
To work with ASP.NET Core 1.0, you need to make sure is whether you have installed the
following software on your machine
DotNetCore 2.0
Select the Tools->Nuget Package Manager->Package Manager settings the dialog window
will open.
Navigate to the Nuget Package Manager->Package Sources from the options dialog.
Select the newly created Package Source and rename the source name using the Name
input box.
https://api.nuget.org/v3/index.json
Adding TagHelpers
Now open _viewImports.cshtml file from the views folder and add the following namespace
for components references and Tag Helper support.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
1047
@addTagHelper *, Syncfusion.EJ2
Adding ScriptManager
Add ScriptManager to the bottom of the layout.cshtml page. The ScriptManager used to
place our control initialization script in the page.
<ej-scripts> </ej-scripts>
<ejs-rangenavigator></ejs-rangenavigator>
razor
data.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1048
new data { x = new DateTime(2007, 01, 01), y = 36, y1 = 48 },
new data { x = new DateTime(2008, 01, 01), y = 38, y1 = 50 },
new data { x = new DateTime(2009, 01, 01), y = 54, y1 = 66 },
new data { x = new DateTime(2010, 01, 01), y = 57, y1 = 78 },
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
Enable Tooltip
The tooltip is useful to show the selected data. You can enable tooltip by setting the enable
property as true in tooltip object.
razor
tooltip.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy").
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd").DisplayMode(Syncf
usion.EJ2.Charts.TooltipDisplayMode.Always))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1049
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
1050
Selecting Range
The left and right thumb of RangeNavigator are used to indicate the selected range in the large
collection of data. Following are the ways you can select a range.
Following code example shows how to configure the selected range using value property of
RangeNavigator.
razor
range.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Value(ViewBag.range)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1051
public double y1;
}
1052
Lightweight range navigator
By default, when the dataSource for series property in RangeNavigator is empty, a light weight
Range navigator will get initialized without chart. The following code example shows the basic
lightweight range navigator.
razor
light-weight.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Value(ViewBag.range)
.XName("x").YName("y").DataSource(ViewBag.dataSource)
.Render()
)
1053
Series Types
Essential JS 2 Range navigator supports 3 types of series, to render the data.
Line
To render a step line series, use series type as Line . By default line series render in range
navigator.
razor
line.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy").
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd").DisplayMode(Syncf
usion.EJ2.Charts.TooltipDisplayMode.Always))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Type(Syncfu
sion.EJ2.Charts.RangeNavigatorType.Line).Add();
}).Render()
)
1054
public double y1;
}
Area
To render a step line series, use series type as Area
razor
area.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy").
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd").DisplayMode(Syncf
usion.EJ2.Charts.TooltipDisplayMode.Always))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Type(Syncfu
sion.EJ2.Charts.RangeNavigatorType.Area).Add();
}).Render()
)
1055
StepLine
To render a step line series, use series type as StepLine
razor
step.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy").
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd").DisplayMode(Syncf
usion.EJ2.Charts.TooltipDisplayMode.Always))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Type(Syncfu
sion.EJ2.Charts.RangeNavigatorType.StepLine).Add();
}).Render()
)
1056
Types of data
Numeric
Numeric scale is used to represent the numeric values of data in a chart. By default, the
valueType of a range navigator is Double.
razor
double.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Range
1057
Minimum and maximum of the Range navigator will be calculated automatically based on the
provided data. You can also customize the range using the minimum, maximum, and interval
properties.
razor
range.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.Minimum(10).
.Maximum(400)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Label Format
Numeric labels can be formatted using the labelFormat property.
razor
format.cs
1058
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
The following table describes the result of applying some commonly used label formats on
numeric values.
1059
The Currency symbol is appended to number
1000 c1 $1,000.0
and number is rounded to 1 decimal place
razor
format.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Logarithmic Axis
1060
Logarithmic supports logarithmic scale, and it is used to visualize data when the Range navigator
has numerical values in both lower (e.g.: 10-6) and higher (e.g.: 106) orders of magnitude.
razor
log.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.Logarithmic)
.Series(sr =>
{
sr.XName("y").YName("y1").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Range
Minimum and maximum of the Range navigator will be calculated automatically based on the
provided data. You can also customize the range using the minimum, maximum, and interval
properties.
razor
log-range.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.Logarithmic)
1061
.Minimum(10)
.Maximum(1000)
.Series(sr =>
{
sr.XName("y").YName("y1").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Logarithmic Base
Logarithmic base can be customized using the logBase property. The default value of the
logBase property is 10.
razor
log-base.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.Logarithmic)
.LogBase(10)
.Series(sr =>
{
sr.XName("y").YName("y1").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1062
public IActionResult Data()
{
List dataSource = new List
{
new data { y = 12, y1 = 28 },
new data { y = 100, y1 = 44 },
new data { y = 500, y1 = 48 },
new data { y = 1000, y1 = 50 },
new data { y = 5000, y1 = 66 },
new data { y = 7000, y1 = 78 },
new data { y = 89, y1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
public class data
{
public double y;
public double y1;
}
Date-time
Date-time Range navigator supports date-time scale and displays date-time values as a labels in
the specified format.
razor
date-time.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1063
new data { x = new DateTime(2008, 01, 01), y = 38, y1 = 50 },
new data { x = new DateTime(2009, 01, 01), y = 54, y1 = 66 },
new data { x = new DateTime(2010, 01, 01), y = 57, y1 = 78 },
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
Note: Date-time Range navigator supports date-time scale and displays date-time values as
a labels in the specified format.
Interval Customization
Date-time intervals can be customized using the interval and intervalType properties of the range
navigator. For example, when you set interval as 2 and intervalType as years, the interval is
considered as 2 years. Date-time supports the following interval types:
Auto
Years
Quarter
Months
Weeks
Days
Hours
Minutes
razor
date-time-interval.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.IntervalType("Months")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1064
public IActionResult Data()
{
List dataSource = new List
{
new data { x = new DateTime(2005, 01, 01), y = 21, y1 = 28 },
new data { x = new DateTime(2006, 01, 01), y = 24, y1 = 44 },
new data { x = new DateTime(2007, 01, 01), y = 36, y1 = 48 },
new data { x = new DateTime(2008, 01, 01), y = 38, y1 = 50 },
new data { x = new DateTime(2009, 01, 01), y = 54, y1 = 66 },
new data { x = new DateTime(2010, 01, 01), y = 57, y1 = 78 },
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
The following table describes the result of applying some common date time formats to the
labelFormat property
Label Format
Label Value Result Description
Property Value
new
The Date is displayed in day
Date(2000, EEEE Monday
format
03, 10)
new
The Date is displayed in
Date(2000, yMd 04/10/2000
month/date/year format
03, 10)
new
The Shorthand month for the
Date(2000, MMM Apr
date is displayed
03, 10)
new
Time of the date value is
Date(2000, hm 12:00 AM
displayed as label
03, 10)
new
12:00:00 The Label is displayed in
Date(2000, hms
AM hours:minutes:seconds format
03, 10)
1065
Period selector
The period selector allows to select a range with specified periods.
Periods
Periods is an array of objects that allows users to specify the range of periods. The “interval”
property specifies the count value of the button, and the “text” property specifies the text to be
displayed on button. The “intervalType” property allows users to customize the intervals of the
buttons. The “intervalType” property supports the following interval types:
Auto
Years
Quarter
Months
Weeks
Days
Hours
Minutes
Seconds
razor
periods.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.PeriodSelectorSettings(ps => ps.Position(Syncfusion.EJ2.Charts.Per
iodSelectorPosition.Top).Periods(ViewBag.periods))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1066
new data { x = new DateTime(2009, 01, 01), y = 54, y1 = 66 },
new data { x = new DateTime(2010, 01, 01), y = 57, y1 = 78 },
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
List<RangeNavigatorPeriod> periods = new List<RangeNavigatorPeriod>();
RangeNavigatorPeriod one = new RangeNavigatorPeriod();
one.Text = "1M";
one.IntervalType = RangeIntervalType.Months;
one.Interval = 1;
RangeNavigatorPeriod two = new RangeNavigatorPeriod();
two.Text = "3M";
two.IntervalType = RangeIntervalType.Months;
two.Interval = 3;
RangeNavigatorPeriod three = new RangeNavigatorPeriod();
three.Text = "6M";
three.IntervalType = RangeIntervalType.Months;
three.Interval = 6;
RangeNavigatorPeriod four = new RangeNavigatorPeriod();
four.Text = "YTD";
RangeNavigatorPeriod five = new RangeNavigatorPeriod();
five.Text = "1Y";
five.Interval = 1;
RangeNavigatorPeriod six = new RangeNavigatorPeriod();
six.Text = "2Y";
six.Interval = 2;
six.Selected = true;
RangeNavigatorPeriod seven = new RangeNavigatorPeriod();
seven.Text = "ALL";
periods.Add(one);
periods.Add(two);
periods.Add(three);
periods.Add(four);
periods.Add(five);
periods.Add(six);
periods.Add(seven);
ViewBag.periods = periods;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
1067
The “position” property allows users to position the period selector either at the “top” or “bottom”.
razor
position.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.PeriodSelectorSettings(ps => ps.Position(Syncfusion.EJ2.Charts.Per
iodSelectorPosition.Top).Periods(ViewBag.periods).Position("Bottom"))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1068
RangeNavigatorPeriod six = new RangeNavigatorPeriod();
six.Text = "2Y";
six.Interval = 2;
six.Selected = true;
RangeNavigatorPeriod seven = new RangeNavigatorPeriod();
seven.Text = "ALL";
periods.Add(one);
periods.Add(two);
periods.Add(three);
periods.Add(four);
periods.Add(five);
periods.Add(six);
periods.Add(seven);
ViewBag.periods = periods;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
Height
The “height” property allows users to specify the height for period selector. The default value of
the height property is 43.
razor
height.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.PeriodSelectorSettings(ps => ps.Position(Syncfusion.EJ2.Charts.Per
iodSelectorPosition.Top).Periods(ViewBag.periods).Height("45"))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1069
new data { x = new DateTime(2005, 01, 01), y = 21, y1 = 28 },
new data { x = new DateTime(2006, 01, 01), y = 24, y1 = 44 },
new data { x = new DateTime(2007, 01, 01), y = 36, y1 = 48 },
new data { x = new DateTime(2008, 01, 01), y = 38, y1 = 50 },
new data { x = new DateTime(2009, 01, 01), y = 54, y1 = 66 },
new data { x = new DateTime(2010, 01, 01), y = 57, y1 = 78 },
new data { x = new DateTime(2011, 01, 01), y = 70, y1 = 84 },
};
ViewBag.dataSource = chartData;
List<RangeNavigatorPeriod> periods = new List<RangeNavigatorPeriod>();
RangeNavigatorPeriod one = new RangeNavigatorPeriod();
one.Text = "1M";
one.IntervalType = RangeIntervalType.Months;
one.Interval = 1;
RangeNavigatorPeriod two = new RangeNavigatorPeriod();
two.Text = "3M";
two.IntervalType = RangeIntervalType.Months;
two.Interval = 3;
RangeNavigatorPeriod three = new RangeNavigatorPeriod();
three.Text = "6M";
three.IntervalType = RangeIntervalType.Months;
three.Interval = 6;
RangeNavigatorPeriod four = new RangeNavigatorPeriod();
four.Text = "YTD";
RangeNavigatorPeriod five = new RangeNavigatorPeriod();
five.Text = "1Y";
five.Interval = 1;
RangeNavigatorPeriod six = new RangeNavigatorPeriod();
six.Text = "2Y";
six.Interval = 2;
six.Selected = true;
RangeNavigatorPeriod seven = new RangeNavigatorPeriod();
seven.Text = "ALL";
periods.Add(one);
periods.Add(two);
periods.Add(three);
periods.Add(four);
periods.Add(five);
periods.Add(six);
periods.Add(seven);
ViewBag.periods = periods;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
1070
Visibility of range navigator
The “disableRangeSelector” property allows users to render the period selector without range
navigator.
razor
visible.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.DisableRangeSelector("true")
.PeriodSelectorSettings(ps => ps.Position(Syncfusion.EJ2.Charts.Per
iodSelectorPosition.Top).Periods(ViewBag.periods))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1071
three.Interval = 6;
RangeNavigatorPeriod four = new RangeNavigatorPeriod();
four.Text = "YTD";
RangeNavigatorPeriod five = new RangeNavigatorPeriod();
five.Text = "1Y";
five.Interval = 1;
RangeNavigatorPeriod six = new RangeNavigatorPeriod();
six.Text = "2Y";
six.Interval = 2;
six.Selected = true;
RangeNavigatorPeriod seven = new RangeNavigatorPeriod();
seven.Text = "ALL";
periods.Add(one);
periods.Add(two);
periods.Add(three);
periods.Add(four);
periods.Add(five);
periods.Add(six);
periods.Add(seven);
ViewBag.periods = periods;
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
1072
Labels
Multilevel labels
The second level labels for the range navigator can be enabled by setting the “enableGrouping”
property to true. This is restricted to date-time axis alone.
razor
multi.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.EnableGrouping(true)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Grouping
1073
The second level axis labels can be grouped using “groupBy” property with the following interval
types:
Auto
Years
Quarter
Months
Weeks
Days
Hours
Minutes
Seconds
razor
group.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy").RangeIntervalType.Months")
.EnableGrouping(True)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1074
}
Smart labels
The “labelIntersectAction” property is used to avoid overlapping of labels.
The following code sample shows setting the labelIntersectAction property to Hide.
razor
smart.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.EdgeLabelPlacement(Syncfusion.EJ2.Chart.EdgeLabelPlacement.Shift)
.LabelIntersectAction(Syncfusion.EJ2.Chart.LabelIntersectAction.Hid
e)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1075
Label positioning
By default, the labels can be placed at outside of the range navigator. You can place the labels
inside the range navigator using the labelPosition property.
razor
position.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Labels customization
The font size, color, family, etc. can be customized using the “labelStyle” property.
razor
custom.cs
1076
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1077
Grid and Tick Lines
razor
grid.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.MajorGridLines(ViewBag.lineWidth)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1078
Tick line customization
You can customize the width, color, and height of the major tick lines using the majorTickLines
property.
razor
tick.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.MajorTickLines(ViewBag.lineWidth)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1079
Customization
Navigator appearance
The navigator can be customized using the “navigatorStyleSettings” property. The
“selectedRegionColor” property is used to specify the color for selected region whereas the
“unSelectedRegionColor” property is used to specify the color for unselected region.
razor
appearance.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.NavigatorStyleSettings( style => {
style.unselectedRegionColor("Skyblue").selectedRegionColor("black")
})
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1080
Thumb
The thumb property provides options to customize the border, fill, size, and type of thumb. The
types of thumb can be “Circle” and “Rectangle”.
razor
thumb.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.NavigatorStyleSettings( style => {
style.unselectedRegionColor("Skyblue").selectedRegionColor("black")
.Thumb("ViewBag.thumb)
})
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Border customization
1081
Using the “navigatorBorder” property, you can customize the “width” and “color” of the range
navigator.
razor
border.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.NavigatorBorder("ViewBag.border")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Deferred update
If the “enableDeferredUpdate” property is set to true, then the changed event will be fired after
dragging the slider. If the “enableDeferredUpdate” is false, then the changed event will be fired
when dragging the slider. By default, the “enableDeferredUpdate” is set to false.
razor
1082
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.EnableDeferredUpdate(true)
})
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
Allow snapping
The “allowSnapping” property toggles the placement of the slider exactly to the left or on the
nearest interval.
razor
snap.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.AllowSnapping(true)
})
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1083
}
public class data
{
public double y;
public double y1;
}
Animation
The speed of the animation can be controlled using the “animationDuration” property. The default
value of the “animationDuration” property is 500 milliseconds.
razor
animation.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("{value}K")
.AnimationDuration("2000")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
})
1084
public double y1;
}
1085
Tooltip
The range navigator supports tooltips for sliders. Sliders are used to select data at a range in the
range navigator. Tooltips display the selected start and end values.
Customization
Tooltips can be customized using the following properties:
razor
tooltip.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd"))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1086
public class data
{
public DateTime x;
public double y;
public double y1;
}
Label Format
You can format and parse the date to all globalize format using labelFormat property in an axis.
razor
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Tooltip(tl=>tl.Enable(true).Format("yyyy/MM/dd").DisplayMode(Sy
ncfusion.EJ2.Charts.TooltipDisplayMode.Always))
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
The following table describes the result of applying some common date time formats to the
labelFormat property
Label Format
Label Value Result Description
Property Value
new
The Date is displayed in day
Date(2000, EEEE Monday
format
03, 10)
new
The Date is displayed in
Date(2000, yMd 04/10/2000
month/date/year format
03, 10)
new
The Shorthand month for the
Date(2000, MMM Apr
date is displayed
03, 10)
new
Time of the date value is
Date(2000, hm 12:00 AM
displayed as label
03, 10)
new
12:00:00 The Label is displayed in
Date(2000, hms
AM hours:minutes:seconds format
03, 10)
1087
RTL
The range navigator provides RTL (right-to-left) support. This can be enabled using the
“enableRtl” property.
razor
rtl.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.EnableRtl(true)
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
1088
Export and print
Export
The rendered range navigator can be exported to JPEG, PNG, SVG, or PDF format using the
export method in the range navigator. The input parameters for this method are Export Type for
format and fileName for result.
razor
export.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
@Html.EJS().Button("export").Content("Primary").IsPrimary(true).Render();
<script>
document.getElementById('export').onclick = function () {
var control = document.getElementById('export').ej2_instances[0];
control.export("PNG", "range");
};
</script>
1089
public class data
{
public DateTime x;
public double y;
public double y1;
}
Print
The rendered range navigator can be printed directly from the browser by calling the public
method print. The ID of the range navigator div element must be passed as argument to that
method.
razor
print.cs
@(Html.EJS().RangeNavigator("container")
.ValueType(Syncfusion.EJ2.Charts.RangeValueType.DateTime)
.LabelFormat("MMM-yy")
.Series(sr =>
{
sr.XName("x").YName("y").DataSource(ViewBag.dataSource).Add();
}).Render()
)
@Html.EJS().Button("print").Content("Primary").IsPrimary(true).Render();
<script>
document.getElementById('print').onclick = function () {
var chart = document.getElementById('print-container').ej2_instances[0]
;
chart.print();
};
</script>
1090
return View();
}
public class data
{
public DateTime x;
public double y;
public double y1;
}
1091
Overview
The Schedule component is an event calendar which facilitates user with the common Outlook-
calendar features, thus allowing the users to plan and manage their events/appointments and its
time in an efficient way.
Key Features
Views - Schedule is now availed with 6 different view modes – day, week, work week,
month, agenda and month agenda. It is possible to configure view-based settings on each
view mode. The Week view is set as active view by default.
Data binding - Seamless data binding with various client- side and remote data sources
thus allowing the data to load on demand by default to reduce the data transfer and loading
time.
Recurrence - Allows the user to repeat a set of events on a daily, weekly, monthly, or yearly
basis.
Template - The key elements like events, date header, work cells and event tooltip comes
with the default template support which allows the flexible end-user customization to embed
any kind of text, images, or styles to it.
Time zone - Regardless of whatever time zone your system follows, Schedule supports
setting your own required time zone value to it as well as to each event – thus allowing the
events to display on its exact local time.
Customizable working days and hours - Users can set specific work hour range which is
visually differentiated with active colour. Also, the working days collection can be customized
with specific days, so that the remaining days will be considered as weekend.
Custom editor template - Template option is availed for event editor, thus allowing the
users to add their own custom editor design and also provides option to add additional fields
onto the default event editor.
Adaptive rendering - Adapts with optimal user interfaces for mobile and desktop form-
factors, thus helping the user’s application to scale elegantly across all the form-factors
without any additional effort.
Keyboard interaction - All the common actions such as traversing through the
appointments, multiple cell selection, add/edit/delete the appointments, navigate to other
views, dates and much more can be performed through keyboard inputs.
Localization - All the static text and date content can be localized to any desired language.
Also, it can be displayed with appropriate time mode and date-format as per the localized
language.
RTL - Supports displaying the component to display in the direction from right to left.
1092
Getting Started
This section briefly explains about how to include a simple Schedule in your ASP.NET MVC
application. You can refer the ASP.NET MVC Getting Started documentation page for
introduction part of the system requirements and common component configurations.
razor
@Html.EJS().Schedule("schedule").Render()
Running the above code will display the empty Schedule on the browser.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Height("550px").EventSettings(
new ScheduleEventSettings { DataSource = ViewBag.appointments }).SelectedDate(new DateT
ime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
1093
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult WorkDays()
{
ViewBag.appointments = GetScheduleData();
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{Id = 1, Subject = "Explosion of Betelgeuse Star", StartTime = new DateTime(
2018, 2, 11, 9, 30, 0), EndTime = new DateTime(2018, 2, 11, 11, 0, 0) });
appData.Add(new AppointmentData
{ Id = 2, Subject = "Thule Air Crash Report", StartTime = new DateTime(2018
, 2, 12, 12, 0, 0), EndTime = new DateTime(2018, 2, 12, 14, 0, 0) });
appData.Add(new AppointmentData
{ Id = 3, Subject = "Blue Moon Eclipse", StartTime = new DateTime(2018, 2,
13, 9, 30, 0), EndTime = new DateTime(2018, 2, 13, 11, 0, 0) });
appData.Add(new AppointmentData
{ Id = 4, Subject = "Meteor Showers in 2018", StartTime = new DateTime(2018
, 2, 14, 13, 0, 0), EndTime = new DateTime(2018, 2, 14, 14, 30, 0) });
appData.Add(new AppointmentData
{ Id = 5, Subject = "Milky Way as Melting pot", StartTime = new DateTime(20
18, 2, 15, 12, 0, 0), EndTime = new DateTime(2018, 2, 15, 14, 0, 0) });
return appData;
}
}
1094
Appointments
Appointment Types
The types of appointments available within Scheduler can be categorized as follows
Normal
Represents an appointment that is created for a certain time interval in one or more number of
days. If the normal appointment is created for more than 24 hours, then those longer
appointments will be rendered on the all-day row.
If the normal appointment is to be created for two days (say from November 25, 2015 –
11.00 PM to November 26, 2015 2.00 AM) but less than 24 hour time interval, then the
appointment is split into two partitions and will be displayed appropriately on both the days.
All-Day
Represents an appointment that is created for an entire day such as holiday events. It renders
separately in an All-day row, a separate place for all-day appointments. In Timeline (horizontal)
view, all-day appointment renders in the usual work cells, as no all-day cells are present in that
view.
Recurrence
Represents an appointment that is created for a certain time interval that occurs repeatedly in a
daily, weekly, monthly, yearly or every weekday basis at the same time interval based on the
recurrence rule. The other available options and validations that can be performed on recurrence
appointments can be referred from here.
Appointment Fields
The Schedule dataSource usually holds the event instances, where each of the instance are
defined with the set of fields depicted here. It is mandatory to map these fields with the equivalent
fields of database, when remote data is bound to it. When the local JSON data is bound, then the
field names defined within the instances needs to be mapped with the availed properties
correctly.
1095
The subject field is optional, and usually assigns the subject text
subject
to each of the events.
It maps the location field from the dataSource and the location
location field value will be displayed over events, while given it for an event
object.
The below example depicts the local JSON data assigned to Schedule's dataSource.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
1096
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Height("550px").EventSettings(e => e.Field
s(f => f.Subject(sub => sub.Name("Subject")).Id("Id").IsAllDay(allday => allday.Name("I
sAllDay")).Location(loc => loc.Name("Location")).Description(des => des.Name("Descripti
on")).StartTime(st => st.Name("StartTime")).EndTime(et => et.Name("EndTime")).StartTime
zone(stz => stz.Name("StartTimezone")).EndTimezone(etz => etz.Name("EndTimezone")).Recu
rrenceRule(recRule => recRule.Name("RecurrenceRule")).RecurrenceID(recId => recId.Name(
"RecurrenceID"))).DataSource(ViewBag.appointments)).SelectedDate(new DateTime(2018, 2,
15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult appointment-fields()
{
ViewBag.appointments = GetScheduleData();
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
Id = 2,
Subject = "Paris",
StartTime = new DateTime(2018, 2, 15, 10, 0, 0),
EndTime = new DateTime(2018, 2, 15, 12, 30, 0),
IsAllDay = false,
RecurrenceID = 10,
RecurrenceRule = "FREQ=DAILY;INTERVAL=1;COUNT=5",
Location = "London",
Description = "Summer vacation planned for outstation.",
StartTimezone = "Asia/Yekaterinburg",
EndTimezone = "Asia/Yekaterinburg"
});
return appData;
1097
}
}
public class AppointmentData
{
public int Id { get; set; }
public string Subject { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAllDay { get; set; }
public int RecurrenceID { get; set; }
public string RecurrenceRule { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public string StartTimezone { get; set; }
public string EndTimezone { get; set; }
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Height("550px").EventSettings(e => e.Field
s(f => f.Subject(sub => sub.Name("TravelSummary")).Id("TravelId").IsAllDay(allday => al
lday.Name("FullDay")).Location(loc => loc.Name("Source")).Description(des => des.Name("
Comments")).StartTime(st => st.Name("DepartureTime")).EndTime(et => et.Name("ArrivalTim
e")).StartTimezone(stz => stz.Name("Origin")).EndTimezone(etz => etz.Name("Destination"
))).DataSource(ViewBag.appointments)).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
1098
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult custom-field()
{
ViewBag.appointments = GetScheduleData();
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
TravelId = 2,
TravelSummary = "Paris",
DepartureTime = new DateTime(2018, 2, 15, 10, 0, 0),
ArrivalTime = new DateTime(2018, 2, 15, 12, 30, 0),
FullDay = false,
Source = "London",
Comments = "Summer vacation planned for outstation.",
Origin = "Asia/Yekaterinburg",
Destination = "Asia/Yekaterinburg"
});
return appData;
}
}
public class AppointmentData
{
public int TravelId { get; set; }
public string TravelSummary { get; set; }
public DateTime DepartureTime { get; set; }
public DateTime ArrivalTime { get; set; }
public bool FullDay { get; set; }
public string Source { get; set; }
public string Comments { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
}
}
1099
Scheduler provides option to include 'n' custom fields for appointments and those field values can
be accessed with in sample end. The following code example will include the custom fields
Status and Priority with in appointment collection.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Height("550px").EventSettings(e => e.Field
s(f => f.Subject(sub => sub.Name("Subject")).Id("Id").IsAllDay(allday => allday.Name("I
sAllDay")).StartTime(st => st.Name("StartTime")).EndTime(et => et.Name("EndTime"))).Dat
aSource(ViewBag.appointments)).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult additioinal-fields()
{
ViewBag.appointments = GetScheduleData();
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
Id = 2,
Subject = "Meeting",
StartTime = new DateTime(2018, 2, 15, 10, 0, 0),
EndTime = new DateTime(2018, 2, 15, 12, 30, 0),
IsAllDay = false,
1100
Status = "Completed",
Priority = "High"
});
return appData;
}
}
public class AppointmentData
{
public int Id { get; set; }
public string Subject { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAllDay { get; set; }
public string Status { get; set; }
public string Priority { get; set; }
}
}
Field validation
It is possible to validate the required fields of the appointment window from client-side before
submitting it, by adding appropriate validation rules to each fields. The appointment fields have
been extended to accept both String and object type values. Therefore, in order to perform
validations, it is necessary to specify object values for the appointment fields.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@{
var validationRules = new Dictionary<string, object>() { { "required", true } }
;
var descriptionValidationRules = new Dictionary<string, object>() { { "required", t
rue }, { "minLength", 5 } };
}
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").
EventSettings(e => e.Fields(f => f.Id("Id").Subject(sub => sub.Name("Subject").Validati
on(validationRules)).Location(loc => loc.Name("Location").Validation(locationValidation
Rules)).Description(des => des.Name("Description").Validation(descriptionValidationRule
s)).StartTime(st => st.Name("StartTime").Validation(validationRules)).EndTime(et => et.
1101
Name("EndTime").Validation(validationRules))).DataSource(ViewBag.datasource)).SelectedD
ate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult field-validation()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Recurrence options
There are scenarios where you require the same appointments to be repeatedly created for
multiple days on daily, weekly, monthly, and yearly or on every weekday basis. While creating or
binding the recurrence appointment, recurrenceRule contains recurrence pattern in string
format.
Recurrence rule
The recurrence appointments are created based on the recurrence rule. The recurrenceRule is
a string value that contains the details of the recurrence appointments like
It has the following properties based on which the recurrence appointments are rendered in the
Schedule control with its respective time period.
1102
Property Purpose
Maintains the Repeat type (Daily, Weekly, Monthly, Yearly, Every week day)
FREQ
value of the appointment. Example: FREQ=DAILY;INTERVAL=1
Maintains the interval value of the appointments. When you create the daily
appointment at an interval of 2, the appointments are rendered on the days
INTERVAL
Monday, Wednesday and Friday (Creates an appointment on all days by
leaving the interval of one day gap). Example: FREQ=DAILY;INTERVAL=2
It holds the appointment’s count value. When the COUNT value is 10, then 10
COUNT instances of appointments are created in the recurrence series. Example:
FREQ=DAILY;INTERVAL=1;COUNT=10
This property holds the end date value (in ISO format) denoting when the
UNTIL recurrence actually ends. Example:
FREQ=DAILY;INTERVAL=1;UNTIL=20180530T041343Z;
This property is used to store the date value of the Month, while creating the
Month recurrence appointment. When you create a Monthly recurrence
BYMONTHDAY appointment for every 3rd day of the month, then BYMONTHDAY holds the
value 3 and creates the appointment on 3rd day of every month. Example:
FREQ=MONTHLY;BYMONTHDAY=3;INTERVAL=1;COUNT=10
This property is used to store the index value of the selected Month while
creating the yearly appointments. When you create the yearly appointment on
BYMONTH June month, the index value of June month 6 will get stored in the BYMONTH
field. The appointment is created on every 6th month of a year. Example:
FREQ=YEARLY;BYMONTHDAY=16;BYMONTH=6;INTERVAL=1;COUNT=10
This property is used to store the index value of the week. When you create
the monthly appointment in second week of a month, the index value of the
BYSETPOS
second week (2) is stored in BYSETPOS. Example:
FREQ=MONTHLY;BYDAY=MO;BYSETPOS=2;COUNT=10
The default recurrence validation has been included for recurrence appointments similar to
the one available in outlook. The validation occurs during the recurrence appointment
creation, drag and drop or resizing of the recurrence appointments and also if any single
occurrence changes.
Single occurrence
Entire series
1103
Single occurrence
When an option EDIT EVENT is selected, a single occurrence of the recurrence appointment
alone will be edited. Once it is edited then
recurrenceID field will be added which holds the id value of its parent recurrence
appointment. It is applicable only for the edited occurrence appointments.
recurrenceException field will be added to its parent recurrence appointment which holds
the edited occurrence appointment date in string type.
When an option DELETE EVENT is selected, a single occurrence of the recurrence appointment
alone will be deleted. Once it is edited then recurrenceException field will be added to its parent
recurrence appointment which holds the deleted occurrence appointment date in string type.
Entire series
When an option EDIT SERIES is selected, entire recurrence series will be edited. Once this
option is chosen then the whole recurrence appointment collection including its edited occurrence
will be re-rendered with the new value.
When an option DELETE SERIES is selected, entire recurrence series will be deleted. Once this
option is chosen then the whole recurrence appointment collection including its edited occurrence
will be removed from Schedule.
Event customization
The field names that are mapped from the dataSource to the appropriate field properties within
the eventSettings can be accessed within the template. The following code example will
customize the appointment default color and time format.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").
EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource, Template = V
iewBag.template }).Readonly(true).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<style>
.e-schedule .e-vertical-view .e-content-wrap .e-appointment {
border-radius: 8px;
1104
}
.e-schedule .template-wrap {
height: 100%;
white-space: normal;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
1105
{
public partial class ScheduleController : Controller
{
public IActionResult event-customization()
{
ViewBag.datasource = new ScheduleData().GetWebinarData();
ViewBag.template = "<div class='template-wrap' style='background:${Secondar
yColor}'><div class='subject' style='background:${PrimaryColor}'>${Subject}</div><div c
lass='time' style='background:${PrimaryColor}'>Time: ${getTimeString(data.StartTime)} -
${getTimeString(data.EndTime)}</div><div class='image'><img src = '../../Content/sched
ule/images/${ImageName}.svg' alt='${ImageName}'/></div><div class='description'>${Descr
iption}</div><div class='footer' style='background:${PrimaryColor}'></div></div>";
return View();
}
}
}
Tooltip
The tooltip can be applied with the customized template design. By making use of template
feature with tooltip, all the field names that are mapped from the dataSource to the appropriate
field properties within the eventSettings can be accessed.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@{
var template = "<div class='tooltip-wrap'>"+
"<div class='content-area'><div class='name'>${Subject}</></div>" +
"${if(City !== null && City !== undefined)}<div class='city'>${City}</div>${/if}" +
"<div class='time'>From : ${StartTime.toLocaleString()} </div>" +
"<div class='time'>To : ${EndTime.toLocaleString()} </div></div></div>";
}
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").
EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource, EnableToolti
p = true, TooltipTemplate = template }).SelectedDate(new DateTime(2018, 2, 15)).Render(
)
</div>
</div>
}
1106
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult tooltip()
{
ViewBag.datasource = new ScheduleData().GetEventsData();
return View();
}
}
}
1107
Data-binding
The Schedule uses DataManager , which supports both RESTful JSON data services binding and
local JavaScript object array binding. The dataSource property can be assigned either with the
instance of DataManager or JavaScript object array collection. It supports two kinds of data
binding method:
Local data
Remote data
Local data
To bind local data to the Schedule, you can assign a JavaScript object array to the dataSource
property. The local data source can also be provided as an instance of the DataManager .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(new ScheduleEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateT
ime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult local-data()
{
1108
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Remote data
To bind remote data to Schedule component, assign service data as an instance of
DataManager to the dataSource property. To interact with remote data source, provide the
endpoint url .
OData
OData is a standardized protocol for creating and consuming data. You can retrieve data from
OData service using the DataManager. Refer to the following code example for remote Data
binding using OData service.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Readonly(true
).EventSettings(e => e.DataSource(d => d.Url("https://js.syncfusion.com/demos/ejservice
s/api/Schedule/LoadData").Adaptor("ODataAdaptor").CrossDomain(true))).SelectedDate(new
DateTime(2017, 6, 11)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
1109
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult Odata()
{
return View();
}
}
}
Web API
You can use WebApiAdaptor to bind Schedule with Web API created using OData endpoint.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Readonly(true
).EventSettings(e => e.DataSource(d => d.Url("https://js.syncfusion.com/demos/ejservice
s/api/Schedule/LoadData").Adaptor("WebApiAdaptor").CrossDomain(true))).SelectedDate(new
DateTime(2017, 6, 11)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
1110
public IActionResult web-api()
{
return View();
}
}
}
UrlAdaptor
UrlAdaptor also used to bind appointment in Schedule as shown below.
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.DataSource(d => d.Url("Home/GetData").Adaptor("UrlAdaptor").CrossDomain(true))
).SelectedDate(new DateTime(2017, 6, 11)).Render()
</div>
</div>
}
@using Syncfusion.EJ2
@{
var dataManager = new DataManager() { Url = "Home/GetData", Adaptor = "UrlAdaptor",
CrossDomain = true };
}
@section ControlsSection{
<div class="control-section">
<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTim
e(2017, 6, 11)" readonly="true">
<e-schedule-eventsettings dataSource="dataManager">
</e-schedule-eventsettings>
</ejs-schedule>
</div>
}
1111
To add a custom parameter to the data request, use the addParams method of Query class.
Assign the Query object with additional parameters to the Schedule query property.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Read.EventSe
ttings(e => e.DataSource(d => d.Url("https://js.syncfusion.com/demos/ejservices/api/Sch
edule/LoadData").Adaptor("ODataAdaptor"))).SelectedDate(new DateTime(2017, 6, 11)).Rend
er()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult additional-parameter()
{
return View();
}
}
}
The parameters added using the query property will be sent along with the data request
for every Schedule action.
1112
During server interaction from the Schedule, some server-side exceptions may occur, and you
can acquire those error messages or exception details in client-side using the
actionFailure event.
The argument passed to the actionFailure event contains the error details returned from the
server.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.DataSource(d => d.Url("http://some.com/invalidUrl").Adaptor("UrlAdaptor").Cros
sDomain(true))).ActionFailure("onActionFailure").SelectedDate(new DateTime(2017, 6, 11)
).Render()
</div>
</div>
<script type="text/javascript">
function onActionFailure(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var span = document.createElement('span');
scheduleObj.element.parentNode.insertBefore(span, scheduleObj.element);
span.style.color = '#FF0000';
span.innerHTML = 'Server exception: 404 Not found';
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult failure-actions()
{
return View();
1113
}
}
}
The actionFailure event will be triggered not only for the server errors, but also when
there is an exception while processing the Schedule actions.
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.DataSource(d => d.Url("Home/GetData").CrudUrl("Home/UpdateData").Adaptor("UrlA
daptor").CrossDomain(true))).SelectedDate(new DateTime(2017, 6, 5)).Render()
</div>
</div>
}
@using Syncfusion.EJ2
@{
var dataManager = new DataManager() { Url = "Home/GetData", Adaptor = "UrlAdaptor",
CrudUrl = "Home/UpdateData", CrossDomain = true };
}
@section ControlsSection{
<div class="control-section">
<ejs-schedule id="schedule" width="100%" height="550" selectedDate="new DateTim
e(2017, 6, 5)">
<e-schedule-eventsettings dataSource="dataManager">
</e-schedule-eventsettings>
</ejs-schedule>
</div>
}
The server-side controller code to handle the CRUD operations are as follows.
using System;
1114
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScheduleCRUD.Models;
using System.Collections;
namespace ScheduleCRUD.Controllers
{
public class HomeController : Controller
{
ScheduleDataDataContext db = new ScheduleDataDataContext();
// ScheduleDataDataContext is a LINQ-to-SQL data class name that is defined in the .dbm
l file to access the tables from the database
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetData() // To initially bind the appointments with Schedule
r
{
List<MultipleResource> data = new ScheduleDataDataContext().MultipleResourc
es.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
1115
// this block of code will execute while removing the appointment
if (param.action == "remove" || param.deleted != null)
{
if (param.action == "remove")
{
int key = Convert.ToInt32(param.key);
MultipleResource app = db.MultipleResources.Where(c => c.Id == key)
.FirstOrDefault();
if (app != null) db.MultipleResources.DeleteOnSubmit(app);
}
else
{
foreach (var apps in param.deleted)
{
MultipleResource app = db.MultipleResources.Where(c => c.Id ==
apps.Id).FirstOrDefault();
if (apps != null) db.MultipleResources.DeleteOnSubmit(app);
}
}
db.SubmitChanges();
}
// this block of code will execute while updating the appointment
if ((param.action == "batch" && param.changed != null) || param.action == "
update")
{
var value = param.action == "update" ? param.value : param.changed[0];
var filterData = db.MultipleResources.Where(c => c.Id == Convert.ToInt3
2(value.Id));
if (filterData.Count() > 0)
{
DateTime startTime = Convert.ToDateTime(value.StartTime);
DateTime endTime = Convert.ToDateTime(value.EndTime);
MultipleResource appoint = db.MultipleResources.Single(A => A.Id ==
Convert.ToInt32(value.Id));
appoint.StartTime = startTime;
appoint.EndTime = endTime;
appoint.Subject = value.Subject;
appoint.AllDay = value.AllDay;
}
db.SubmitChanges();
}
var data = db.MultipleResources.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
}
1116
Editor customization
Each field defined through it should contain the e-field class, so as to allow the processing of
those fields in the default event object from internal source. The ID of this customized script
template section is assigned to the editorTemplate option, so that this customized fields will be
replaced onto the default editor window.
As we are using our Syncfusion sub-components within this editor in the below demo, the custom
defined form elements needs to be configured as required Syncfusion components such as
DropDownList and DateTimePicker which needs to be done within the popupOpen event. This
particular step can be skipped, if the user needs to simply use the normal form design with
applicable fields.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).PopupOpen("onPopupOpen").EventSettings(new ScheduleEventSettings { DataSource =
ViewBag.datasource }).EditorTemplate("#EventEditorTemplate").ShowQuickInfo(false).Sele
ctedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<style>
.custom-event-editor .e-textlabel {
padding-right: 15px;
text-align: right;
}
.custom-event-editor td {
padding: 7px;
padding-right: 16px;
}
</style>
1117
<script id="EventEditorTemplate" type="text/template">
<table class="custom-event-editor" width="100%" cellpadding="5">
<tbody>
<tr>
<td class="e-textlabel">Summary</td>
<td colspan="4">
<input id="Subject" class="e-field e-input" type="text" value=""
name="Subject" style="width: 100%" />
</td>
</tr>
<tr>
<td class="e-textlabel">Status</td>
<td colspan="4">
<input type="text" id="EventType" name="EventType" class="e-fie
ld" style="width: 100%" />
</td>
</tr>
<tr>
<td class="e-textlabel">From</td>
<td colspan="4">
<input id="StartTime" class="e-field" type="text" name="StartTi
me" />
</td>
</tr>
<tr>
<td class="e-textlabel">To</td>
<td colspan="4">
<input id="EndTime" class="e-field" type="text" name="EndTime"
/>
</td>
</tr>
<tr>
<td class="e-textlabel">Reason</td>
<td colspan="4">
<textarea id="Description" class="e-field e-input" name="Descri
ption" rows="3" cols="50"
style="width: 100%; height: 60px !important; resize:
vertical"></textarea>
</td>
</tr>
</tbody>
</table>
</script>
<script type="text/javascript">
function onPopupOpen(args) {
if (args.type === 'Editor') {
var statusElement = args.element.querySelector('#EventType');
if (!statusElement.classList.contains('e-dropdownlist')) {
1118
var dropDownListObject = new ej.dropdowns.DropDownList({
placeholder: 'Choose status', value: statusElement.value,
dataSource: ['New', 'Requested', 'Confirmed']
});
dropDownListObject.appendTo(statusElement);
statusElement.setAttribute('name', 'EventType');
}
var startElement = args.element.querySelector('#StartTime');
if (!startElement.classList.contains('e-datetimepicker')) {
new ej.calendars.DateTimePicker({ value: new Date(startElement.value
) || new Date() }, startElement);
}
var endElement = args.element.querySelector('#EndTime');
if (!endElement.classList.contains('e-datetimepicker')) {
new ej.calendars.DateTimePicker({ value: new Date(endElement.value)
|| new Date() }, endElement);
}
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult custom-editor-template()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
1119
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).ActionBegin("onActionBegin").PopupOpen("onPopupOpen").EventSettings(new Schedul
eEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2,
15)).Render()
</div>
</div>
<script type="text/javascript">
function onActionBegin(args) {
if (args.requestType === 'eventCreate') {
var eventData = args.data;
eventData.Description = document.getElementById("DescriptionValue").inn
erText;
}
}
function onPopupOpen(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
if (args.type === 'QuickInfo') {
if (args.target.classList.contains("e-work-cells")) {
if (!args.element.querySelector('.custom-field-row')) {
var row = ej.base.createElement('div', { className: 'custom-fie
ld-row' });
var formElement = args.element.querySelector('.e-schedule-form'
);
formElement.appendChild(row);
var container = ej.base.createElement('div', { className: 'cust
om-field-container' });
var classNames = 'e-field e-custom-description';
var inputEle = ej.base.createElement('input', {
1120
className: classNames, attrs: { type: 'text', value: '', na
me: 'Description' }
});
container.appendChild(inputEle);
row.appendChild(container);
ej.inputs.Input.createInput({
element: inputEle, floatLabelType: 'Auto',
properties: {
enableRtl: scheduleObj.enableRtl,
placeholder: "Description"
}
});
var element = document.querySelector(".e-custom-description");
element.addEventListener("keypress", function (e) {
document.getElementById("DescriptionValue").innerHTML = e.t
arget.value;
});
}
}
else if (args.target.classList.contains("e-appointment")) {
var eventData = args.data;
var row = ej.base.createElement('div', { className: 'e-event-descri
ption' });
row.textContent = eventData.Description;
var element = args.element.querySelector('.e-subject-wrap');
element.parentNode.insertBefore(row, element.nextSibling);
}
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult custom-quick-popup()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
1121
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
}
};
ViewBag.view = viewOption;
return View();
}
}
}
1122
Timezone
The Scheduler makes use of the System time zone by default. If it needs to follow some other
user-specific time zone, then the API timezone can be used. Apart from the default action of
applying specific timezone to the entire Scheduler, it is also possible to set different time zone
values for each appointments through the properties startTimezone and endTimezone which
can be defined as separate fields within the appointment collection.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-12 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Timezone("Am
erica/New_York").EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasou
rce }).SelectedDate(new DateTime(2018, 6, 17)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
1123
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult schedule-timezone()
{
ViewBag.datasource = new ScheduleData().GetFifaEventsData();
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-12 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Timezone("UT
C").EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Select
edDate(new DateTime(2018, 6, 17)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult sametime()
{
1124
ViewBag.datasource = new ScheduleData().GetFifaEventsData();
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-12 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(new ScheduleEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateT
ime(2018, 6, 17)).Render()
</div>
</div>
}
@section PreScripts {
<script type="text/javascript">
var data = [{ Value: 'America/New_York', Text: '(UTC-05:00) Eastern Time' }, {
Value: 'UTC', Text: 'UTC' }, { Value: 'Asia/Kolkata', Text: '(UTC+05:30) India Standard
Time' }];
var timezoneData = ej.schedule.timezoneData;
timezoneData.splice.apply(timezoneData, [0, timezoneData.length].concat(data));
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
1125
{
public ActionResult timezone-collection()
{
ViewBag.datasource = new ScheduleData().GetResourceData();
List<OwnerResources> owners = new List<OwnerResources>();
owners.Add(new OwnerResources { OwnerText = "Nancy", Id = 1, OwnerColor = "
#ffaa00" });
owners.Add(new OwnerResources { OwnerText = "Steven", Id = 2, OwnerColor =
"#f8a398" });
owners.Add(new OwnerResources { OwnerText = "Michael", Id = 3, OwnerColor =
"#7499e1" });
ViewBag.Owners = owners;
string[] resources = new string[] { "Owners" };
ViewBag.Resources = resources;
return View();
}
}
public class OwnerResources
{
public string OwnerText { set; get; }
public int Id { set; get; }
public string OwnerColor { set; get; }
}
}
1126
Views
Schedule allows to display the events on all its available views such as
Day
Week
Work week
Month
Agenda
Month-Agenda
Except Month-Agenda view, all the other views are displayed by default on the Schedule.
View-specific settings
The fields available are as follows.
Applicable
Property Type Description
views
Day,
Week,
It accepts the schedule
Work
view name, based on
week,
option View which we can define with
Month,
its related properties in a
Agenda,
single object.
Month-
Agenda.
Day,
To denote whether the
Week,
view name given on the
Work
option is active or not.
week,
isSelected Boolean It acts similar to the
Month,
currentView property
Agenda,
and defines the active
Month-
view of Schedule.
Agenda.
By default, Schedule
follows the date-format
as per the default culture
assigned to it. It is also
possible to manually set
specific date format by Day,
using the dateFormat Week,
property. The format of Work
the date range label in week,
dateFormat Date
the header bar depends Month,
on the dateFormat Agenda,
value or else based on Month-
the locale assigned to Agenda.
1127
the Schedule. It gets
applied only to the view
objects on which it is
defined.
Day,
When set to true ,
Week,
prevents the CRUD
Work
actions on the respective
week,
readonly Boolean views. By default, it is set
Month,
to false . It gets applied
Agenda,
only to the view objects
Month-
on which it is defined.
Agenda.
It is used to allow or
disallow the virtual
allowVirtualScrolling Boolean Agenda.
scrolling functionality on
Agenda View.
1128
accessible via template
is date . It gets applied
only to the view objects
on which it is defined.
1129
working days on
Schedule. The only days
Day,
that are defined in this
Week,
collection will be Work
rendered on the
workDays Number[] week,
workWeek view whereas
Month,
on other views, it will Month-
display all the usual days Agenda.
and simply highlights the
working days with
different shade.
Day,
Week,
Allows to set different Work
resource grouping week,
group GroupModel
options on all available Month,
schedule view modes. Agenda,
Month-
Agenda.
Extended views
Views can be extended to display n number of days, weeks and months on a single view using
interval property. Refer the below code example to display 3 days, 2 weeks and 4 months on
the respective views.
razor
data.cs
1130
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).DisplayName("3 Days").Interval(3).Add(); view.Option(View.Wee
k).DisplayName("2 Weeks").Interval(2).IsSelected(true).Add(); view.Option(View.Month).D
isplayName("4 Months").Interval(4).Add(); }).EventSettings(new ScheduleEventSettings {
DataSource = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult extended-views()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
To configure Schedule with simply 2 views but with different configurations, refer the below code
example.
razor
1131
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Views(ViewBag.view).Height("
550px").CellTemplate("#apptemplate").SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script id="apptemplate" type="text/template">
${if (type === "monthCells")}
<div class="templatewrap">
${getCellContent(data.date)}
</div> ${/if}
</script>
<script type="text/javascript">
function getCellContent(date) {
var weekEnds = [0, 6];
if (weekEnds.indexOf(date.getDay()) >= 0) {
return "<img src='weekend.png' /><span class='caption'>Weekend</span>";
}
return '';
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult specific-views()
{
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week, Sho
wWeekend = false },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month}
1132
};
ViewBag.view = viewOption;
return View();
}
}
}
Above code example display Schedule with 2 views namely Week and Month – on which
weekend days are set to hidden in Week view and cell templates are applied on Month
view.
1133
Resources
The Scheduler provides Resources support, with which the single Scheduler is shared by
multiple resources simultaneously. Each resource in the Scheduler is arranged in a column/row
wise, with individual spacing to display all its respective appointments on a single page. It also
supports the grouping of resources, thus enabling the categorization of resources in a
hierarchical structure and shows it either in expandable groups (Horizontal view) or else vertical
hierarchy one after the other (Vertical view).
One or more resources can be assigned to the Scheduler appointments by making selection of
the resource options available in the appointment window.
Resources fields
The default options available within the resources collection are as follows,
field (String)
title (String)
It holds the title name of the resource field to be displayed on the Schedule appointment window.
name (String)
A unique resource name used for differentiating various resource objects while grouping.
allowMultiple (Boolean)
When set to true , allows multiple selection of resource names, thus creating multiple instances
of same appointment for the selected resources.
resourceColorField (String)
Binds the resource level name, whose color will be applied to events.
dataSource (Object)
Assigns the resource dataSource , where data can be passed either as an array of JavaScript
objects, or else can create an instance of DataManager in case of processing remote data and
can be assigned to the dataSource property. With the remote data assigned to dataSource ,
check the available adaptors to customize the data processing.
query (Query)
Defines the external query that will be executed along with the data processing.
1134
idField (String)
textField (String)
groupIDField (String)
colorField (String)
startHourField (String)
endHourField (String)
workDaysField (String)
cssClassField (String)
Binds the custom CSS class field name from the dataSource .
The appointments belonging to all the resources will be displayed on the Scheduler which will be
differentiated based on the resource color assigned in the resources (depicting to which
resource that particular appointment belongs).
Example: To display default Scheduler with multiple resource options in the appointment
window,
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
1135
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group
=> group.ByGroupID(false).Resources(ViewBag.Resources)).Resources(res =>
{
res.AllowMultiple(false).DataSource(ViewBag.Rooms).Field("RoomId").Title("Ro
om").Name("Rooms").TextField("RoomText").IdField("Id").GroupIDField("RoomGroupId").Colo
rField("RoomColor").Add();
res.AllowMultiple(true).DataSource(ViewBag.Owners).Field("OwnerId").Title("O
wner").Name("Owners").TextField("OwnerText").IdField("Id").GroupIDField("OwnerGroupId")
.ColorField("OwnerColor").Add();
}).Views(view => { view.Option(View.Week).Add(); view.Option(View.Month).Add();
view.Option(View.Agenda).Add(); }).EventSettings(e => e.DataSource(ViewBag.datasource))
.SelectedDate(new DateTime(2018, 4, 1)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult Demo()
{
ViewBag.datasource = new ScheduleData().GetResourceData();
1136
"#7499e1" });
ViewBag.Owners = owners;
Setting allowMultiple to true in the above code snippet allows the user to select
multiple resources in the appointment window and also creates multiple copies of the same
appointment in the Scheduler for each resources while saving.
Group by levels
Scheduler supports both single and multiple levels of resource grouping that can be customized
either in horizontal or vertical Scheduler views. In Vertical view - the levels are displayed in a tree
structure one after the other, but in horizontal view – the levels are grouped in a vertically
expandable/collapsible structure. Scheduler also provides
Single level
This type of grouping allows the Scheduler to display all the resources at a single level
simultaneously. The appointments will make use of the colorField defined for the first resource
instance as its background color.
Example: To display the Scheduler with single level resource grouping options,
1137
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group
=> group.Resources(ViewBag.Resources)).Resources(res => { res.AllowMultiple(true).DataS
ource(ViewBag.Owners).Field("OwnerId").Title("Owner").Name("Owners").TextField("OwnerTe
xt").IdField("Id").ColorField("OwnerColor").Add(); }).Views(view => { view.Option(View.
Week).Add(); view.Option(View.Month).Add(); view.Option(View.Agenda).Add(); }).EventSet
tings(e => e.DataSource(ViewBag.datasource)).SelectedDate(new DateTime(2018, 4, 1)).Ren
der()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult single-level()
{
ViewBag.datasource = new ScheduleData().GetResourceData();
List<OwnerResources> owners = new List<OwnerResources>();
owners.Add(new OwnerResources { OwnerText = "Nancy", Id = 1, OwnerColor = "
#ffaa00" });
owners.Add(new OwnerResources { OwnerText = "Steven", Id = 2, OwnerColor =
"#f8a398" });
owners.Add(new OwnerResources { OwnerText = "Michael", Id = 3, OwnerColor =
"#7499e1" });
ViewBag.Owners = owners;
string[] resources = new string[] { "Owners" };
ViewBag.Resources = resources;
return View();
}
}
1138
public class OwnerResources
{
public string OwnerText { set; get; }
public int Id { set; get; }
public string OwnerColor { set; get; }
}
}
The name field mentioned in the resource object needs to be specified within the group
property in order to enable the grouping option in Scheduler.
Multi-Level
This type of grouping displays the resources in the Scheduler at multiple levels with a set of
resources grouped under each parent. The appointments will make use of the colorField
defined for the first/top level resource instance as its background color.
Example: To display the Scheduler with multiple level resource grouping options,
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group
=> group.ByGroupID(false).Resources(ViewBag.Resources)).Resources(res =>
{
res.AllowMultiple(false).DataSource(ViewBag.Rooms).Field("RoomId").Title("Ro
om").Name("Rooms").TextField("RoomText").IdField("Id").GroupIDField("RoomGroupId").Colo
rField("RoomColor").Add();
res.AllowMultiple(true).DataSource(ViewBag.Owners).Field("OwnerId").Title("O
wner").Name("Owners").TextField("OwnerText").IdField("Id").GroupIDField("OwnerGroupId")
.ColorField("OwnerColor").Add();
}).Views(view => { view.Option(View.Week).Add(); view.Option(View.Month).Add();
view.Option(View.Agenda).Add(); }).EventSettings(e => e.DataSource(ViewBag.datasource))
.SelectedDate(new DateTime(2018, 4, 1)).Render()
</div>
</div>
}
using System;
1139
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult Demo()
{
ViewBag.datasource = new ScheduleData().GetResourceData();
1140
Group all child resources
This type of grouping displays the same child resources under different parent resource(s). To
enable such grouping, it is necessary to set byGroupID to false within the group whereby
allowing all the resources available in each child level to group under its parent resources. With
this option available, we can avoid the need to provide multiple definitions of the same data to be
grouped under different parent.
Example: To display the Scheduler with same set of child resource under different parent
grouping options,
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").CurrentView(
View.WorkWeek).SelectedDate(new DateTime(2018, 6, 5)).Group(group => group.ByGroupID(fa
lse).Resources(ViewBag.Resources)).Resources(res =>
{
res.DataSource(ViewBag.Projects).Field("ProjectId").Title("Project").Name("P
rojects").TextField("text").IdField("id").ColorField("color").Add();
res.DataSource(ViewBag.Categories).Field("CategoryId").Title("Category").Nam
e("Categories").TextField("text").IdField("id").ColorField("color").AllowMultiple(true)
.Add();
}).EventSettings(e => e.DataSource(ViewBag.datasource)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
1141
public ActionResult group-child()
{
ViewBag.datasource = new ScheduleData().GetResourceTeamData();
Group by date
This type of grouping displays the resource group on day basis. To enable such grouping, it is
necessary to set byDate to true within the group whereby allowing all the resource group
under the date.
Example: To display the Scheduler with resource group under date option,
razor
data.cs
1142
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group
=> group.ByDate(true).Resources(ViewBag.Resources)).Resources(res => { res.DataSource(V
iewBag.Owners).Field("OwnerId").Title("Assignee").Name("Owners").TextField("text").IdFi
eld("id").ColorField("color").AllowMultiple(true).Add(); }).Views(view => { view.Option
(View.Week).Add(); view.Option(View.Month).Add(); view.Option(View.Agenda).Add(); }).Ev
entSettings(e => e.Fields(f => f.Subject(sub => sub.Name("Subject").Title("Task")).Loca
tion(loc => loc.Name("Location").Title("Project Name")).Description(des => des.Name("De
scription").Title("Comments"))).DataSource(ViewBag.datasource)).SelectedDate(new DateTi
me(2018, 4, 1)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult GroupByDate()
{
ViewBag.datasource = new ScheduleData().GetResourceData();
1143
public int id { set; get; }
public string color { set; get; }
}
}
Linked events
This type of option allow us to edit all resource events simultaneously and to enable such option,
it is necessary to set allowGroupEdit to true within the group . With this property enabled, a
single appointment object will be maintained within the appointment collection, even if it is shared
by more than one resource – whereas the resource fields of such appointment object will hold the
IDs of the multiple resources separated by commas. Any actions such as create, edit or delete
held on any one of the event, will be reflected on all other related instances visible on the UI.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").CurrentView(
View.WorkWeek).Group(group => group.AllowGroupEdit(true).Resources(ViewBag.Resources)).
Resources(res => { res.DataSource(ViewBag.Conferences).Field("ConferenceId").Title("Att
endees").Name("Conferences").TextField("text").IdField("id").ColorField("color").AllowM
ultiple(true).Add(); }).EventSettings(e => e.Fields(f => f.Subject(sub => sub.Name("Sub
ject").Title("Conference Name")).Description(des => des.Name("Description").Title("Summ
ary")).StartTime(st => st.Name("StartTime").Title("From")).EndTime(et => et.Name("EndTi
me").Title("To"))).DataSource(ViewBag.datasource)).Views(ViewBag.view).SelectedDate(new
DateTime(2018, 6, 5)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
1144
public partial class ScheduleController : Controller
{
public ActionResult GroupEditing()
{
ViewBag.datasource = new ScheduleData().GetResourceConferenceData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month },
};
ViewBag.view = viewOption;
Example: To display the Scheduler with each individual resources having different work-hours
and work-days,
1145
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group
=> group.Resources(ViewBag.Resources)).Resources(res => { res.DataSource(ViewBag.Doctor
s).Field("DoctorId").Title("Doctor Name").Name("Doctors").TextField("text").IdField("id"
).ColorField("color").WorkDaysField("workDays").StartHourField("startHour").EndHourFiel
d("endHour").Add(); }).Views(view => { view.Option(View.WorkWeek).Add(); view.Option(Vi
ew.Month).Add(); }).EventSettings(e => e.DataSource(ViewBag.datasource)).SelectedDate(n
ew DateTime(2018, 4, 1)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult custom-workdays()
{
ViewBag.datasource = new ScheduleData().GetDoctorData();
List<DoctorRes> doctors = new List<DoctorRes>();
doctors.Add(new DoctorRes { text = "Will Smith", id = 1, color = "#ea7a57",
workDays = new List<int> { 1, 2, 4, 5 }, startHour = "07:00", endHour = "13:00" });
doctors.Add(new DoctorRes { text = "Alice", id = 2, color = "rgb(53, 124, 2
10)", workDays = new List<int> { 1, 3, 5 }, startHour = "09:00", endHour = "17:00" });
doctors.Add(new DoctorRes { text = "Robson", id = 3, color = "#7fa900", sta
rtHour = "08:00", endHour = "16:00" });
ViewBag.Doctors = doctors;
1146
}
}
public class DoctorRes
{
public string text { set; get; }
public int id { set; get; }
public string color { set; get; }
public List<int> workDays { set; get; }
public string startHour { set; get; }
public string endHour { set; get; }
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<table id="property" title="Show / Hide Resource" style="width: 100%">
<tbody>
<tr style="height: 100%">
<td style="width: 25%">
@Html.EJS().CheckBox("personal").Change("onChange").Checked(true
).Disabled(true).Label("My Calendar").Value("1").Render()
</td>
<td style="width: 25%">
@Html.EJS().CheckBox("company").Change("onChange").Checked(false
).Label("Company").Value("2").Render()
</td>
<td style="width: 25%">
@Html.EJS().CheckBox("birthdays").Change("onChange").Checked(fa
1147
lse).Label("Birthday").Value("3").Render()
</td>
<td style="width: 25%">
@Html.EJS().CheckBox("holidays").Change("onChange").Checked(fal
se).Label("Holiday").Value("4").Render()
</td>
</tr>
</tbody>
</table>
</div>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Group(group => g
roup.Resources(ViewBag.Resources)).Resources(res =>
{
res.DataSource(ViewBag.Calendars).Field("CalendarId").Title("Calendars"
).Name("Calendars").TextField("CalendarName").IdField("CalendarId").ColorField("Calenda
rColor").AllowMultiple(true).Add();
}).EventSettings(e => e.DataSource(ViewBag.datasource)).Views(ViewBag.view)
.SelectedDate(new DateTime(2018, 4, 1)).Render()
</div>
<style>
.property-panel-content .e-checkbox-wrapper.personal .e-label {
color: #808080;
}
1148
.highcontrast .property-panel-content .e-checkbox-wrapper .e-frame.e-check,
.bootstrap .property-panel-content .e-checkbox-wrapper .e-frame.e-check {
color: #fff;
}
</style>
<script type="text/javascript">
function onChange(args) {
var calendarCollections = [
{ CalendarName: 'My Calendar', CalendarId: 1, CalendarColor: '#c43081'
},
{ CalendarName: 'Company', CalendarId: 2, CalendarColor: '#ff7f50' },
{ CalendarName: 'Birthday', CalendarId: 3, CalendarColor: '#AF27CD' },
{ CalendarName: 'Holiday', CalendarId: 4, CalendarColor: '#808000' }
];
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var value = parseInt(args.event.target.getAttribute('value'), 10);
var resourceData = calendarCollections.filter(function (calendar) { return
calendar.CalendarId === value; });
if (args.checked) {
scheduleObj.addResource(resourceData[0], 'Calendars', value - 1);
} else {
scheduleObj.removeResource(value, 'Calendars');
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult AddRemoveResources()
{
List<CalendarRes> calendarCollections = new List<CalendarRes>();
calendarCollections.Add(new CalendarRes { CalendarName = "My Calendar", Cal
endarId = 1, CalendarColor = "#c43081" });
ViewBag.Calendars = calendarCollections;
1149
List<ScheduleData.ResourceEventsData> birthdayData = data.GetBirthdayData()
;
List<ScheduleData.ResourceEventsData> companyData = data.GetCompanyData();
List<ScheduleData.ResourceEventsData> personalData = data.GetPersonalData()
;
ViewBag.datasource = holidayData.Concat(birthdayData).Concat(companyData).C
oncat(personalData);
return View();
}
public class CalendarRes
{
public string CalendarName { set; get; }
public int CalendarId { set; get; }
public string CalendarColor { set; get; }
}
}
}
1150
Read Only
An interaction with the appointments of the Scheduler can be enabled/disabled through the
readonly property. When the readonly property is set to true , it is not possible to do any
actions on the appointments, but you can navigate between the schedule dates, views and can
also be able to see the appointment details in the quick window. By default, this property is set to
false .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").
EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Readonly(t
rue).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult read-only()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
1151
How to prevent the pop-ups from opening
When readonly is set to true , only the CRUD action will be prevented but still popup will be
displayed with appointment details, which can be allowed only to view. Refer the below code
example to disable the popup when readonly is set to true .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).Readonly(true).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.d
atasource }).PopupOpen("onPopupOpen").EventRendered("onEventRendered").EventClick("onEv
entClick").SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<style>
.e-schedule .e-read-only {
opacity: .8;
}
</style>
<script type="text/javascript">
var isReadOnly = function (data) {
return data.ReadOnly || (data.EndTime < new Date());
};
function onEventClick(args) {
if ((args.element).classList.contains('e-read-only')) {
args.cancel = true;
}
}
function onEventRendered(args) {
if (isReadOnly(args.data)) {
args.element.setAttribute('aria-readonly', 'true');
args.element.classList.add('e-read-only');
}
}
function onPopupOpen(args) {
if (args.type === 'editor' && isReadOnly(args.data)) {
args.cancel = true;
}
}
</script>
1152
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult prevent-popup()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
1153
TimeScale
The timeScale allows the user to set the required time slot duration for the work cells that
displays on the Scheduler. It includes the below properties such as,
enable - It accepts true or false value, denoting whether to show or hide the time slots. Its
default value is true.
slotCount – Specifies the value, based on which the minor time slots are divided into
appropriate count.
The interval and slotCount can be set on the Scheduler with the following code example.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").SelectedDate(
new DateTime(2018, 2, 15)).Views(view => { view.Option(View.Day).Add(); view.Option(Vie
w.Week).Add(); view.Option(View.WorkWeek).Add(); }).TimeScale(ts => ts.Enable(true).Int
erval(60).SlotCount(6)).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.
datasource }).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult timescale()
1154
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").SelectedDate(
new DateTime(2018, 2, 15)).Views(view => { view.Option(View.Day).Add(); view.Option(Vie
w.Week).Add(); view.Option(View.WorkWeek).Add(); }).TimeScale(ts => ts.Enable(true).Int
erval(60).SlotCount(6)).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.
datasource }).Render()
</div>
</div>
<script id="majorSlotTemplate" type="text/x-template">
<div>${majorSlotTemplate(data.date)}</div>
</script>
<script id="minorSlotTemplate" type="text/x-template">
<div style="text-align: right; margin-right: 15px">${minorSlotTemplate(data.dat
e)}</div>
</script>
<script type="text/javascript">
window.majorSlotTemplate = function (date) {
var instance = new ej.base.Internationalization();
return instance.formatDate(date, { skeleton: 'hm' });
};
window.minorSlotTemplate = function (date) {
1155
var instance = new ej.base.Internationalization();
return instance.formatDate(date, { skeleton: 'ms' }).replace(':00', '');
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult custom-timecells()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
On/Off timescale
The time cells can be enabled / disabled on Schedule, by setting true / false to the enable
property available within timeScale . It's default value is true .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").SelectedDate(
new DateTime(2018, 2, 15)).Views(view => { view.Option(View.Day).Add(); view.Option(Vie
w.Week).Add(); view.Option(View.WorkWeek).Add(); }).TimeScale(ts => ts.Enable(false)).E
ventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Render()
</div>
</div>
1156
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult on-off-timescale()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).ShowTimeIndicator(false).SelectedDate(new DateTime(2018, 6, 5)).Render()
</div>
</div>
}
using System;
1157
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult time-indicator()
{
return View();
}
}
}
1158
Header bar customization
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Sh
owHeaderbar(false).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult show-hide-headerbar()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
}
1159
};
ViewBag.view = viewOption;
return View();
}
}
}
[src/app/app.ts]
Now, run the application in the browser using the following command.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="col-lg-9 control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).ActionComplete("onActionComplete").ActionBegin("onActionBegin").EventSettings(n
ew ScheduleEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateTime(
2018, 2, 15)).Render()
</div>
</div>
<style>
.e-schedule .e-schedule-toolbar .user-icon {
background-image: url('./content/schedule/images/nancy.png');
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
border-radius: 50%;
height: 24px;
min-width: 24px !important;
width: 24px !important;
}
1160
min-height: 24px !important;
}
.e-profile-wrapper {
width: 210px;
height: 80px;
background-color: #fafafa;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.e-profile-wrapper .profile-container {
display: flex;
padding: 10px;
}
.e-profile-wrapper .profile-image {
background-image: url('./content/schedule/images/nancy.png');
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
border-radius: 50%;
box-shadow: inset 0 0 1px #e0e0e0, inset 0 0 14px rgba(0, 0, 0, 0.2);
width: 60px;
height: 60px;
}
.e-profile-wrapper .content-wrap {
padding-left: 10px;
}
.e-profile-wrapper .name {
font-size: 14px;
line-height: 20px;
1161
font-weight: 500;
margin-top: 2px;
}
.e-profile-wrapper .destination {
font-size: 12px;
}
.e-profile-wrapper .status-icon {
height:6px;
width:6px;
background:green;
border-radius:100%;
float:left;
margin-right:4px;
margin-top:4px;
}
.e-profile-wrapper .status {
font-size: 11px;
}
</style>
<script type="text/javascript">
var profilePopup;
function onActionBegin(args) {
if (args.requestType === 'toolbarItemRendering') {
var userIconItem = {
align: 'Right', prefixIcon: 'user-icon', text: 'Nancy', cssClass: '
e-schedule-user-icon'
};
args.items.push(userIconItem);
}
}
function onActionComplete(args) {
var scheduleElement = document.getElementById('schedule');
if (args.requestType === 'toolBarItemRendered') {
var userIconEle = scheduleElement.querySelector('.e-schedule-user-icon'
);
userIconEle.onclick = function () {
profilePopup.relateTo = userIconEle;
profilePopup.dataBind();
if (profilePopup.element.classList.contains('e-popup-close')) {
profilePopup.show();
} else {
profilePopup.hide();
}
};
}
var userContentEle = ej.base.createElement('div', {
1162
className: 'e-profile-wrapper'
});
scheduleElement.parentElement.appendChild(userContentEle);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult custom-headerbar()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
1163
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).RenderCell("onRenderCell").EventSettings(new ScheduleEventSettings { DataSource
= ViewBag.datasource }).CssClass("schedule-date-header-template").DateHeaderTemplate("
#template").SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<style>
.schedule-date-header-template.e-schedule .e-vertical-view .e-header-cells {
padding: 0;
text-align: center !important;
}
.schedule-date-header-template.e-schedule .date-text {
font-size: 14px;
}
.schedule-date-header-template.e-schedule.e-device .date-text {
font-size: 12px;
}
.schedule-date-header-template.e-schedule .weather-image {
width: 20px;
height: 20px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
1164
.schedule-date-header-template.e-schedule .weather-text {
font-size: 11px;
}
1165
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult custom-dateheader()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
1166
Working Days and Hours
The Scheduler can be customized in various aspects like -
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource
}).StartHour("07:00").EndHour("18:00").SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
1167
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Working Hours
Working hours indicates the work hour limit within the Scheduler, which is highlighted visually
with white color work cells. workHours is a object property which contains the below specified
options,
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource
}).WorkHours(wh => wh.Highlight(true).Start("11:00").End("20:00")).SelectedDate(new Dat
eTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
1168
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Working Days
The working days of a week can be set on Schedule using the workDays property which accepts
the collection of day indexes (from 0 to 6) of a week. By default, it is set to [1, 2, 3, 4, 5] and in
the below demo, it has been set to [1, 3, 5] which means that Monday, Wednesday, Friday is
being set as working days of a week and is visually differentiated from non-working days. The
working hours usually applies only on these given working days.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Week).Add(); view.Option(View.Month).Add(); }).EventSettings(new S
cheduleEventSettings { DataSource = ViewBag.datasource }).WorkDays(ViewBag.workday).Sel
ectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
1169
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
ViewBag.workday = new int[] { 1, 3, 5 };
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource
}).FirstDayOfWeek(1).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
1170
return View();
}
}
}
Here, the working days are defined as [1, 3, 4, 5] on Schedule and the remaining days (0, 2, 6 –
Sunday, Tuesday and Saturday) are considered as weekend days and will be hidden from the
views as the showWeekend property is set to false .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource
}).ShowWeekend(false).WorkDays(ViewBag.workday).SelectedDate(new DateTime(2018, 2, 15))
.Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
1171
ViewBag.datasource = new ScheduleData().GetScheduleData();
ViewBag.workday = new int[] { 1, 3, 4, 5 };
return View();
}
}
}
1172
Globalization
Globalization is the combination of internalization and localization. You can adapt the component
to various languages by parsing and formatting the date or number ( Internationalization ),
adding culture specific customization and translation to the text ( Localization ).
Internationalization
Internationalization library provides support for formatting and parsing the number, date, and time
by using the official Unicode CLDR JSON data and also provides the loadCldr method to load
the culture specific CLDR JSON data.
By default, all the Essential JS 2 component are specific to English culture ('en-US'). If you want
to go with the different culture other than English, follow the below steps.
Install the CLDR-Data package by using the below command (it installs the CLDR JSON
data). For more information about CLDR-Data, refer to this link.
Once the package installed, you can find the culture specific JSON data under the location
\scripts\cldr-data .
Now use the loadCultureFiles method to load the culture specific CLDR JSON data.
In ASP.NET MVC refer the culture files directly from \scripts\cldr-data location. In ASP.NET
Core refer the culture files directly from \wwwroot\scripts\cldr-data location as like the below
code examples for both ASP.NET Core and MVC
function loadCultureFiles(de) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
<!--For ASP.NET MVC -->
ajax = new ej.base.Ajax(location.origin + '/../scripts/cldr-data/main/' + n
ame + '/' + files[prop], 'GET', false);
<!--For ASP.NET Core-->
ajax = new ej.base.Ajax(location.origin + '/../wwwroot/scripts/cldr-data/ma
in/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
1173
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
Before changing to a culture other than English , ensure that locale text for the concerned
culture is loaded through load method of L10n class.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); view.Option(View.Month).Add(); }).EventSettings(new ScheduleEventSettings { D
ataSource = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var scheduleObject = document.getElementById('schedule').ej2_instances[0];
loadCultureFiles('fr-CH');
scheduleObject.locale = 'fr-CH';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
1174
ajax = new ej.base.Ajax(location.origin + '/../scripts/cldr-data/main/'
+ name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Localization
Localization library allows users to localize the default text contents of the Schedule to
different cultures using the locale property.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
1175
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); view.Option(View.Month).Add(); }).EventSettings(new ScheduleEventSettings { D
ataSource = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var scheduleObject = document.getElementById('schedule').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
"fr-CH": {
"schedule": {
"day": "journée",
"week": "La semaine",
"workWeek": "Semaine de travail",
"month": "Mois",
},
}
});
loadCultureFiles('fr-CH');
scheduleObject.locale = 'fr-CH';
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + '/../scripts/cldr-data/main/'
+ name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
}
using System;
using System.Collections.Generic;
1176
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Date format
Scheduler can be used with all valid date formats and the default date format is "MM/dd/yyyy". If
the dateFormat property is not specified particularly, then it will be taken based on the locale
that is assigned to the Scheduler. The default locale applied on the Scheduler is "en-US", which
makes it to follow the "MM/dd/yyyy" pattern.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").DateFormat("
yyyy/MM/dd").Views(view => { view.Option(View.Day).Add(); view.Option(View.Week).Add();
view.Option(View.WorkWeek).Add(); view.Option(View.Month).Add(); }).EventSettings(new
ScheduleEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateTime(20
18, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
1177
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
Time mode
The time mode of the Scheduler can be either 12 or 24 hours format which is based on the
locale set to the Scheduler. Since the default locale value of the Scheduler is en-US, the
time mode will be set to 12 hours format automatically.
RTL
The Schedule layout and behavior can be changed as per the common RTL conventions by
setting enableRtl to true as shown below. Its default value is false .
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(view =
> { view.Option(View.Day).Add(); view.Option(View.Week).Add(); view.Option(View.WorkWee
k).Add(); }).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource
}).EnableRtl(true).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
1178
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult display-hours()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
return View();
}
}
}
1179
Schedule dimensions
The dimension normally refers to the height and width of the element. The Schedule height
and width properties accepts the following values.
auto
When height and width properties are set to auto , Schedule elements default height and width
will be assigned. It is the default value for both the properties.
pixel
Schedule height and width will be adjusted as per the given pixel values. It accepts both string
and number values.
percentage
When height and width properties are given as percentage, then the Schedule parent element
height and width will be assigned.
1180
Customization
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Views(ViewBag.view).ActionCo
mplete("onActionComplete").Created("onCreated").EventSettings(new ScheduleEventSettings
{ DataSource = ViewBag.datasource }).CssClass("schedule-cell-dimension").Height("550px"
).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<style>
.schedule-cell-dimension.e-schedule .e-vertical-view .e-date-header-wrap table
col,
.schedule-cell-dimension.e-schedule .e-vertical-view .e-content-wrap table col
{
width: 200px;
}
1181
height: 200px;
}
</style>
<script type="text/javascript">
function onCreated(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
scheduleObj.adjustEventWrapper();
}
function onActionComplete(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
if (args.requestType === 'dateNavigate' || args.requestType === 'viewNaviga
te') {
scheduleObj.adjustEventWrapper();
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult cell-dimensions()
{
ViewBag.datasource = new ScheduleData().GetEmployeeEventData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
1182
Scroll to specific time
You can manually scroll to specific time on Schedule by making use of the scrollTo method as
shown below.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<table style="width: 100%">
<tbody>
<tr style="height: 50px">
<td>
<div>
Scroll To
</div>
</td>
<td>
<div>
@Html.EJS().TimePicker("ScrollToHour").Width("120").Cha
nge("onChange").Value(new DateTime(2000, 1, 1, 9, 0, 0)).Format("HH:mm").Render()
</div>
</td>
</tr>
</tbody>
</table>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(Vi
ewBag.view).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }
).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
function onChange(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
scheduleObj.scrollTo(args.text);
}
</script>
}
using System;
using System.Collections.Generic;
1183
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult scrollto-specific-time()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
};
ViewBag.view = viewOption;
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Po
pupOpen("onPopupOpen").EventRendered("onEventRendered").EventClick("onEventClick").Rend
er()
</div>
</div>
1184
<style>
.e-schedule .e-read-only {
opacity: .8;
}
</style>
<script type="text/javascript">
var isReadOnly = function (data) {
return data.ReadOnly || (data.EndTime < new Date());
};
function onEventClick(args) {
if ((args.element).classList.contains('e-read-only')) {
args.cancel = true;
}
}
function onEventRendered(args) {
if (isReadOnly(args.data)) {
args.element.setAttribute('aria-readonly', 'true');
args.element.classList.add('e-read-only');
}
}
function onPopupOpen(args) {
if (args.type === 'editor' && isReadOnly(args.data)) {
args.cancel = true;
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult read-only()
{
ViewBag.datasource = new ScheduleData().GetReadonlyEventsData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
1185
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
}
};
ViewBag.view = viewOption;
return View();
}
}
}
The event editor is prevented to open on the read-only events by setting args.cancel to
true within the popupOpen event.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).ActionBegin("onActionBegin").EventSettings(new ScheduleEventSettings { DataSour
ce = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
function onActionBegin(args) {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
if (args.requestType === 'eventCreate' && args.data.length > 0) {
var eventData = args.data[0];
var eventField = scheduleObj.eventFields;
var startDate = eventData[eventField.startTime];
var endDate = eventData[eventField.endTime];
args.cancel = !scheduleObj.isSlotAvailable(startDate, endDate);
}
}
</script>
}
1186
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult cell-availability()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
}
};
ViewBag.view = viewOption;
return View();
}
}
}
Cell customization
The cellTemplate option which accepts the template string is used to customize the cell
background with specific images / appropriate text on the given date values.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Views(ViewBag.view).Height("
550px").CellTemplate("#apptemplate").SelectedDate(new DateTime(2017, 12, 15)).Render()
</div>
</div>
<style>
1187
.e-schedule .e-month-view .e-work-cells {
position: relative;
}
.e-schedule .templatewrap {
text-align: center;
position: absolute;
width: 100%;
}
.e-schedule .templatewrap img {
width: 25px;
height: 25px;
}
.e-schedule .caption {
overflow: hidden;
text-overflow: ellipsis;
vertical-align: middle;
}
</style>
<script id="apptemplate" type="text/template">
${if (type === "monthCells")}
<div class="templatewrap">
${getCellContent(data.date)}
</div> ${/if}
</script>
<script type="text/javascript">
function getCellContent(date) {
if (date.getMonth() === 9 && date.getDate() === 31) {
return '<div class="caption">Thanksgiving day</div>';
} else if (date.getMonth() === 11 && date.getDate() === 9) {
return '<div class="caption">Party time</div>';
} else if (date.getMonth() === 11 && date.getDate() === 13) {
return '<div class="caption">Party time</div>';
} else if (date.getMonth() === 11 && date.getDate() === 22) {
return '<div class="caption">Happy birthday</div>';
} else if (date.getMonth() === 11 && date.getDate() === 24) {
return '<div class="caption">Christmas Eve</div>';
} else if (date.getMonth() === 11 && date.getDate() === 25) {
return '<div class="caption">Christmas Day</div>';
} else if (date.getMonth() === 0 && date.getDate() === 1) {
return '<div class="caption">New Year"s Day</div>';
} else if (date.getMonth() === 0 && date.getDate() === 14) {
return '<div class="caption">Get together</div>';
}
return '';
}
</script>
}
1188
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult cell-customization()
{
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Views(ViewBag.view).Height("
550px").RenderCell("onRenderCell").SelectedDate(new DateTime(2017, 12, 15)).Render()
</div>
</div>
<script type="text/javascript">
function onRenderCell(args) {
if (args.element.classList.contains('e-work-hours') && (args.date.getDate()
=== 12 || args.date.getDate() === 14)) {
args.element.style.background = '#deecfc';
1189
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult cell-customization()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
}
};
ViewBag.view = viewOption;
return View();
}
}
}
In month view, date header is not applicable and therefore renderCells event is used to
display custom text in Cells as shown here.
1190
Recurrence editor
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper recurrence-editor-wrap">
<div style="padding-bottom:15px;">
<label>Rule Output</label>
<div class="rule-output-container">
<div id="rule-output">FREQ=DAILY;INTERVAL=1;</div>
</div>
</div>
@Html.EJS().RecurrenceEditor("RecurrenceEditor").SelectedType(1).Change("on
Change").Render()
</div>
</div>
<style>
.recurrence-editor-wrap {
margin: 0 25%;
}
.rule-output-container {
height: auto;
border: 1px solid #969696;
}
#rule-output {
padding: 8px 4px;
text-align: center;
min-height: 20px;
overflow: hidden;
overflow-wrap: break-word;
}
1191
@@media (max-width: 580px) {
.recurrence-editor-wrap {
margin: 0 5%;
}
}
</style>
<script type="text/javascript">
function onChange(args) {
var element = document.querySelector('#rule-output');
element.innerText = args.value;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult rule-generation()
{
return View();
}
}
}
1192
viewDate Date Current view range's first date. It is optional.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper recurrence-editor-wrap">
<div style="padding-bottom:15px;">
<label id="rule-label">Date Collections</label>
<div class="rule-output-container">
<div id="rule-output"></div>
</div>
</div>
@Html.EJS().RecurrenceEditor("RecurrenceEditor").Render()
</div>
</div>
<style>
.recurrence-editor-wrap {
margin: 0 25%;
}
.rule-output-container {
height: auto;
border: 1px solid #969696;
}
#rule-output {
padding: 8px 4px;
text-align: center;
min-height: 20px;
overflow: hidden;
overflow-wrap: break-word;
}
#RecurrenceEditor {
display: none;
}
</style>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var outputElement = document.querySelector('#rule-output');
var labelElement = document.querySelector('#rule-label');
var recObject = document.getElementById('RecurrenceEditor').ej2_instances[0
];
1193
var dates = recObject.getRecurrenceDates(new Date(2018, 0, 7, 10, 0), 'FREQ
=DAILY;INTERVAL=1', '20180108T114224Z,20180110T114224Z', 4, new Date(2018, 0, 7));
var dateCollection = [];
for (var index = 0; index < dates.length; index++) {
dateCollection.push(new Date(dates[index]));
}
outputElement.innerText = dateCollection;
});
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public IActionResult date-genaration()
{
return View();
}
}
}
Above demo will generate two dates January 7 & 9 by excluding the January 8 & 10 since
those dates were given in exclusion list. Generated dates are good to create appointment
collections.
1194
Accessibility
Accessibility is achieved in the Schedule component through WAI-ARIA standard and keyboard
navigation. The Schedule features can be effectively accessed through assistive technologies
such as screen readers.
WAI-ARIA
WAI-ARIA (Accessibility Initiative – Accessible Rich Internet Applications) defines a way to
increase the accessibility of web pages, dynamic content, and user interface components
developed with Ajax, HTML, JavaScript,and related technologies. ARIA provides additional
semantics to describe the role, state, and functionality of web components.
Property Functionalities
aria-label It indicates the disabled state of the Schedule and its items.
aria-
It indicates editor dialog title to the user through assistive technologies.
labelledby
aria- It indicates editor dialog content description to the user through assistive
describedby technologies.
Keyboard navigation
All the Schedule actions can be controlled via keyboard keys and is availed by using
allowKeyboardInteraction property which is set to true by default. The applicable key
combinations and its relative functionalities are listed below.
Interaction
Description
Keys
Focuses the first or active item on the schedule header bar and then move
Tab the focus to the next available event elements. If no events present, then
focus moves out of the component.
1195
Shift + elements from the last one and then move onto the first or active item on
Tab Schedule header bar and then moves out of the component.
Arrow To move onto the next available cells in either of the needed directions (left,
right, top and right)
Shift +
For multiple cell selection on either direction.
Arrow
Ctrl +
Click on To select multiple events.
events
Alt +
Number
To switch between the views on Schedule.
(from 1 to
6)
Ctrl +
Left To navigate to the previous date period.
Arrow
Ctrl +
Right To navigate to the next date period.
Arrow
Left or
On pressing any of these keys when focus is currently on the Schedule
Right
header bar, moves the focus to the previous or next items in the header bar.
Arrow
Space or
It activates any of the focused items.
Enter
Page Up &
Page To scroll through the work cells area.
Down
1196
How To
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").CurrentView(
View.WorkWeek).SelectedDate(new DateTime(2018, 6, 5)).Group(group => group.ByGroupID(fa
lse).Resources(ViewBag.Resources)).Resources(res =>
{
res.DataSource(ViewBag.Projects).Field("ProjectId").Title("Project").Name("P
rojects").TextField("text").IdField("id").ColorField("color").Add();
res.DataSource(ViewBag.Categories).Field("CategoryId").Title("Category").Nam
e("Categories").TextField("text").IdField("id").ColorField("color").AllowMultiple(true)
.Add();
}).EventSettings(e => e.DataSource(ViewBag.datasource)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult resource-color()
{
1197
ViewBag.datasource = new ScheduleData().GetResourceTeamData();
The resourceColorField field value should be as same as the name field value given with
in resources property.
razor
data.cs
@using Syncfusion.EJ2
1198
@using Syncfusion.EJ2.Schedule
@using Syncfusion.EJ2.Buttons
@section ControlsSection{
<div class="control-section">
<div>
@Html.EJS().Button("btn1").Content("Click to open Editor").Render()
@Html.EJS().Button("btn2").Content("Click to open Event Editor").Render()
</div>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").Views(ViewBa
g.view).EventSettings(new ScheduleEventSettings { DataSource = ViewBag.datasource }).Se
lectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
document.getElementById('btn1').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var cellData = {
startTime: new Date(2018, 1, 15, 10, 0),
endTime: new Date(2018, 1, 15, 11, 0),
};
scheduleObj.openEditor(cellData, 'Add');
};
document.getElementById('btn2').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var eventData = {
Id: 4,
Subject: 'Meteor Showers in 2018',
StartTime: new Date(2018, 1, 14, 13, 0),
EndTime: new Date(2018, 1, 14, 14, 30)
};
scheduleObj.openEditor(eventData, 'Save');
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
1199
{
public ActionResult event-editor()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
[src/app/app.ts]
Now, run the application in the browser using the following command.
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@using Syncfusion.EJ2.Buttons
@section ControlsSection{
<div class="control-section">
<div>
@Html.EJS().Button("btn1").Content("Change the work hours").Render()
</div>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").WorkHours(wh
=> wh.Highlight(true).Start("09:00").End("11:00")).Views(ViewBag.view).SelectedDate(new
DateTime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
1200
document.getElementById('btn1').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var dates = [new Date(2018, 1, 15), new Date(2018, 1, 17)];
scheduleObj.setWorkHours(dates, '11:00', '20:00');
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult different-workhours()
{
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
razor
data.cs
1201
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@using Syncfusion.EJ2.Buttons
@section ControlsSection{
<div class="control-section">
<div>
@Html.EJS().Button("btn1").Content("ADD").Render()
@Html.EJS().Button("btn2").Content("EDIT").Render()
@Html.EJS().Button("btn3").Content("DELETE").Render()
</div>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.DataSource(ViewBag.datasource)).Views(ViewBag.view).SelectedDate(new DateTime(
2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
document.getElementById('btn1').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = [{
Id: 1,
Subject: 'Conference',
StartTime: new Date(2018, 1, 12, 9, 0),
EndTime: new Date(2018, 1, 12, 10, 0),
IsAllDay: false
}, {
Id: 2,
Subject: 'Meeting',
StartTime: new Date(2018, 1, 15, 10, 0),
EndTime: new Date(2018, 1, 15, 11, 30),
IsAllDay: false
}];
scheduleObj.addEvent(Data);
};
document.getElementById('btn2').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = {
Id: 3,
Subject: 'Testing-edited',
StartTime: new Date(2018, 1, 11, 10, 0),
EndTime: new Date(2018, 1, 11, 11, 0),
IsAllDay: false
};
scheduleObj.saveEvent(Data);
};
document.getElementById('btn3').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
1202
scheduleObj.deleteEvent(4);
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult dynamic-appointments()
{
ViewBag.datasource = GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
Id = 3,
Subject = "Testing",
StartTime = new DateTime(2018, 2, 11, 9, 0, 0),
EndTime = new DateTime(2018, 2, 11, 10, 0, 0),
IsAllDay = false,
});
appData.Add(new AppointmentData
{
Id = 4,
Subject = "Vacation",
StartTime = new DateTime(2018, 2, 13, 9, 0, 0),
EndTime = new DateTime(2018, 2, 13, 10, 0, 0),
1203
IsAllDay = false,
});
return appData;
}
}
public class AppointmentData
{
public int Id { get; set; }
public string Subject { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAllDay { get; set; }
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").CurrentView(
View.WorkWeek).Navigating("onNavigating").Views(ViewBag.view).EventSettings(new Schedul
eEventSettings { DataSource = ViewBag.datasource }).SelectedDate(new DateTime(2018, 2,
15)).Render()
</div>
</div>
<script type="text/javascript">
function onNavigating(args) {
if (args.previousView === 'Week') {
args.cancel = true;
}
}
</script>
}
1204
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult navigating()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.Fields(f => f.Subject(sub => sub.Title("Event Name").Name("Subject").Default("
Add Name")).Location(loc => loc.Title("Event Location").Name("Location")).Description(d
1205
es => des.Title("Summary").Name("Description")).StartTime(st => st.Title("From").Name("
StartTime")).EndTime(et => et.Title("To").Name("EndTime"))).DataSource(ViewBag.datasour
ce)).Views(ViewBag.view).SelectedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult default-subject()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
razor
data.cs
1206
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@section ControlsSection{
<div class="control-section">
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").PopupOpen("o
nPopupOpen").EventSettings(e => e.DataSource(ViewBag.datasource)).Views(ViewBag.view).S
electedDate(new DateTime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
function onPopupOpen(args) {
args.duration = 40;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult event-duration()
{
ViewBag.datasource = new ScheduleData().GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
}
}
1207
Dynamically add, edit and remove appointments
CRUD actions can be manually performed on appointments using addEvent , saveEvent and
deleteEvent methods as shown below.
Normal event
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@using Syncfusion.EJ2.Buttons
@section ControlsSection{
<div class="control-section">
<div>
@Html.EJS().Button("btn1").Content("ADD").Render()
@Html.EJS().Button("btn2").Content("EDIT").Render()
@Html.EJS().Button("btn3").Content("DELETE").Render()
</div>
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSetting
s(e => e.DataSource(ViewBag.datasource)).Views(ViewBag.view).SelectedDate(new DateTime(
2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
document.getElementById('btn1').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = [{
Id: 1,
Subject: 'Conference',
StartTime: new Date(2018, 1, 12, 9, 0),
EndTime: new Date(2018, 1, 12, 10, 0),
IsAllDay: false
}, {
Id: 2,
Subject: 'Meeting',
StartTime: new Date(2018, 1, 15, 10, 0),
EndTime: new Date(2018, 1, 15, 11, 30),
IsAllDay: false
}];
scheduleObj.addEvent(Data);
};
document.getElementById('btn2').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = {
1208
Id: 3,
Subject: 'Testing-edited',
StartTime: new Date(2018, 1, 11, 10, 0),
EndTime: new Date(2018, 1, 11, 11, 0),
IsAllDay: false
};
scheduleObj.saveEvent(Data);
};
document.getElementById('btn3').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
scheduleObj.deleteEvent(4);
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult dynamic-appointments()
{
ViewBag.datasource = GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
Id = 3,
Subject = "Testing",
1209
StartTime = new DateTime(2018, 2, 11, 9, 0, 0),
EndTime = new DateTime(2018, 2, 11, 10, 0, 0),
IsAllDay = false,
});
appData.Add(new AppointmentData
{
Id = 4,
Subject = "Vacation",
StartTime = new DateTime(2018, 2, 13, 9, 0, 0),
EndTime = new DateTime(2018, 2, 13, 10, 0, 0),
IsAllDay = false,
});
return appData;
}
}
public class AppointmentData
{
public int Id { get; set; }
public string Subject { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAllDay { get; set; }
}
}
Recurrence event
razor
data.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Schedule
@using Syncfusion.EJ2.Buttons
@section ControlsSection{
<div class="control-section">
<div>
@Html.EJS().Button("btn1").Content("ADD").Render()
@Html.EJS().Button("btn2").Content("EDIT").Render()
@Html.EJS().Button("btn3").Content("DELETE").Render()
<div class="content-wrapper">
@Html.EJS().Schedule("schedule").Width("100%").Height("550px").EventSet
tings(e => e.DataSource(ViewBag.datasource)).Views(ViewBag.view).SelectedDate(new DateT
ime(2018, 2, 15)).Render()
</div>
</div>
<script type="text/javascript">
document.getElementById('btn1').onclick = function () {
1210
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = [{
Id: 1,
Subject: 'Conference',
StartTime: new Date(2018, 1, 15, 9, 0),
EndTime: new Date(2018, 1, 15, 10, 0),
IsAllDay: false,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=2'
}];
scheduleObj.addEvent(Data);
};
document.getElementById('btn2').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = {
Id: 3,
Subject: 'Testing-edited',
RecurrenceID: 3,
StartTime: new Date(2018, 1, 11, 10, 0),
EndTime: new Date(2018, 1, 11, 11, 0),
IsAllDay: false,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3'
};
scheduleObj.saveEvent(Data, 'EditOccurrence');
};
document.getElementById('btn3').onclick = function () {
var scheduleObj = document.getElementById('schedule').ej2_instances[0];
var Data = {
Id: 4,
Subject: 'Vacation',
RecurrenceID: 4,
StartTime: new Date(2018, 1, 12, 11, 0),
EndTime: new Date(2018, 1, 12, 12, 0),
IsAllDay: false,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3'
};
scheduleObj.deleteEvent(Data, 'DeleteSeries');
};
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
1211
namespace WebApplication1.Controllers
{
public partial class ScheduleController : Controller
{
public ActionResult DateHeader()
{
ViewBag.datasource = GetScheduleData();
List<ScheduleViewsModel> viewOption = new List<ScheduleViewsModel>()
{
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Day },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Week },
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.WorkWeek
},
new ScheduleViewsModel {Option = Syncfusion.EJ2.Schedule.View.Month }
};
ViewBag.view = viewOption;
return View();
}
public List<AppointmentData> GetScheduleData()
{
List<AppointmentData> appData = new List<AppointmentData>();
appData.Add(new AppointmentData
{
Id = 3,
Subject = "Testing",
StartTime = new DateTime(2018, 2, 11, 9, 0, 0),
EndTime = new DateTime(2018, 2, 11, 10, 0, 0),
IsAllDay = false,
RecurrenceRule = "FREQ=DAILY;INTERVAL=1;COUNT=3",
});
appData.Add(new AppointmentData
{
Id = 4,
Subject = "Vacation",
StartTime = new DateTime(2018, 2, 12, 11, 0, 0),
EndTime = new DateTime(2018, 2, 12, 12, 0, 0),
IsAllDay = false,
RecurrenceRule = "FREQ=DAILY;INTERVAL=1;COUNT=2"
});
return appData;
}
}
public class AppointmentData
{
public int Id { get; set; }
public string Subject { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public bool IsAllDay { get; set; }
1212
public string RecurrenceRule { get; set; }
}
}
When a single occurrence of the recurrence appointment is edited, recurrenceID field will
be added which holds the id value of its parent recurrence appointment. It is applicable
only for the edited occurrence appointments. Therefore the collection passing to the
saveEvent with action as EditOccurrence should have RecurrenceID field as shown
above.
1213
Overview
The Sidebar is an expandable and collapsible component that typically acts as a side container
to place primary or secondary content alongside the main content.
There is a flexible option to show and hide Sidebar as per user interactions. Any type of HTML
content and component can be placed in the Sidebar for quick access and for easy navigation
like quick references, menu, list, and tree view.
Key features
1. Context: The Sidebar can be initialized in any HTML element other than the body element.
2. Types and positions: Supports Push , Over , Slide , and Auto to expand or collapse
the sidebar, and also allows to position it in the Left or Right direction.
3. Auto close: Allows to set the Sidebar in an expanded or collapsed state only in certain
resolutions.
4. Dock: By default, supports display of short notifications about the content on docked mode.
1214
Context
By default, Sidebar initializes context to the body element. Using the target property, set
context element to initialize Sidebar inside any HTML element apart from the body element.
razor
context.cs
@{Html.EJS().Sidebar("default-sidebar").Type(Syncfusion.EJ2.Navigations.SidebarType.Pus
h).Width("280px").Target("maincontent").ContentTemplate(@<div>
<div class="title"> Sidebar content</div>
<div class="sub-title">
Click the button to close the Sidebar.
</div>
<div class="center-align">
@Html.EJS().Button("close").Content("CloseSidebar").Render()
</div>
</div>).Render();}
<div id="head">
@Html.EJS().Button("toggle").Content("Open").IsToggle(true).CssClass("e-info").Ic
onCss("e-icons burg-icon").Render()
</div>
<div class="maincontent" style="height:335px;border:1px solid gray">
<div>
<div class="title">Main content</div>
<div class="sub-title"> content goes here.</div>
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('toggle').onclick = function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
var togglebtn = document.getElementById("toggle").ej2_instances[0];
if (document.getElementById('toggle').classList.contains('e-active')) {
togglebtn.content = 'Close';
defaultSidebar.show();
} else {
togglebtn.content = 'Open';
defaultSidebar.hide();
}
}
// Close the sidebar
document.getElementById('close').onclick = function () {
1215
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
var togglebtn = document.getElementById("toggle").ej2_instances[0];
defaultSidebar.hide();
document.getElementById('toggle').classList.remove('e-active');
togglebtn.content = 'Open'
}
});
</script>
<style>
.header {
width: 100%;
height: 40px;
font-size: 20px;
line-height: 40px;
font-weight: 500;
background: #eee;
display: inline-block;
}
.center-align {
text-align: center;
padding: 20px;
}
.burg-icon:before {
content: '\e7f6';
font-size: 16px;
}
.title {
text-align: center;
font-size: 20px;
padding: 15px;
}
#head {
border: 1px solid #424242;
border-bottom-color: transparent;
background: #00897B;
}
1216
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
display: flex;
justify-content: center;
}
.radiobutton {
display: inline-block;
padding: 10px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
#wrapper {
display: block;
}
.right {
1217
float: right;
}
body {
margin: 0;
}
#default-sidebar {
background-color: #26A69A;
color: #ffffff;
}
.close-btn:hover {
color: #fafafa;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult context()
{
return View();
}
}
}
1218
Types
The Sidebar component's expand behaviour can be modified based on the purpose of use.
Item Description
Push
Sidebar pushes the main content area to appear side-by-side, and shrinks the
main content within the screen width.
Sidebar translates the x and y positions of main content area based on the
Slide Sidebar width. The main content area will not be adjusted within the screen
width.
Sidebar with Over type in mobile resolution, and Push type in other higher
Auto
resolutions.
razor
types.cs
@{Html.EJS().Sidebar("default-sidebar").Type(Syncfusion.EJ2.Navigations.SidebarType.Pus
h).Target("maincontent").ContentTemplate(@<div>
<div class="title"> Sidebar content</div>
<div class="sub-title">
Click the button to close the Sidebar.
</div>
<div class="center-align">
@Html.EJS().Button("close").Content("CloseSidebar").Render()
</div>
</div>).Render(); }
<div id="head">
@Html.EJS().Button("toggle").Content("Open").IsToggle(true).CssClass("e-inf
o").IconCss("e-icons burg-icon").Render()
</div>
<div class="maincontent" style="height:335px;border:1px solid gray">
<div class="content">
<div class="title">Main content</div>
<div class="sub-title">
1219
<div class="radiobutton">
@Html.EJS().RadioButton("over").Label("Over").Name("state").Che
cked(true).Change("positionChange").Render()
</div>
<div class="radiobutton">
@Html.EJS().RadioButton("push").Label("Push").Name("state").Cha
nge("positionChange").Render()
</div>
<div class="radiobutton">
@Html.EJS().RadioButton("slide").Label("Slide").Name("state").C
hange("positionChange").Render()
</div>
<div class="radiobutton">
@Html.EJS().RadioButton("auto").Label("Auto").Name("state").Cha
nge("positionChange").Render()
</div>
</div>
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2
_instances[0];
var togglebtn = document.getElementById("toggle").ej2_instances[0];
document.getElementById("toggle").addEventListener('click', functio
n () {
if (document.getElementById('toggle').classList.contains('e-act
ive')) {
togglebtn.content = 'Close';
defaultSidebar.show();
} else {
togglebtn.content = 'Open';
defaultSidebar.hide();
}
});
// Close the sidebar
document.getElementById("close").addEventListener('click', function
() {
var defaultSidebar = document.getElementById("default-sidebar")
.ej2_instances[0];
var togglebtn = document.getElementById("toggle").ej2_instances[
0];
defaultSidebar.hide();
document.getElementById('toggle').classList.remove('e-active');
togglebtn.content = 'Open'
});
});
1220
function positionChange(args) {
var defaultSidebar = document.getElementById("default-sidebar").ej2_ins
tances[0];
if (args.event.target.id == "over") {
defaultSidebar.type = "Over"
} else if (args.event.target.id == "push") {
defaultSidebar.type = "Push"
}
else if (args.event.target.id == "slide") {
defaultSidebar.type = "Slide"
}
else {
defaultSidebar.type = "Auto"
}
}
</script>
<style>
.header {
width: 100%;
height: 40px;
font-size: 20px;
line-height: 40px;
font-weight: 500;
background: #eee;
display: inline-block;
}
.center-align {
text-align: center;
padding: 20px;
}
.burg-icon:before {
content: '\e7f6';
font-size: 16px;
}
.title {
text-align: center;
font-size: 20px;
padding: 15px;
}
#head {
border: 1px solid #424242;
border-bottom-color: transparent;
background: #00897B;
}
1221
#toggle, #toggle:hover, #toggle:focus { /* csslint allow: adjoining-classes
*/
background: #00695C;
box-shadow: none;
border-radius: 0;
height: 39px;
width: 100px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
display: flex;
justify-content: center;
}
.radiobutton {
display: inline-block;
padding: 10px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
#wrapper {
display: block;
}
1222
display: block;
}
.right {
float: right;
}
body {
margin: 0;
}
#default-sidebar {
background-color: #26A69A;
color: #ffffff;
}
.close-btn:hover {
color: #fafafa;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult types()
{
return View();
1223
}
}
}
1224
Auto-close
Sidebar often behaves differently on a mobile versus a desktop display. It has an effective
feature that offers to set it in opened or closed state corresponding to the specified resolution.
This is achieved through mediaQuery property that allows you to set the Sidebar in an expanded
state or collapsed state only in user-defined resolution.
razor
autoclose.cs
@{Html.EJS().Sidebar("default-sidebar").Width("280px").Created("onCreated").ContentTemp
late(@<div>
<div class="title-header">
<div style="display:inline-block"> Sidebar </div>
</div>
</div>).Render();}
<div>
<div class="title default">Main content</div>
<div class="sub-title">
Place your primary content here.
</div>
</div>
<script type="text/javascript">
function onCreated() {
var obj = document.getElementById("default-sidebar").ej2_instances[0];
obj.mediaQuery = window.matchMedia('(min-width: 600px)');
}
</script>
<style>
.center-align {
text-align: center;
padding: 20px;
}
.title {
text-align: center;
font-size: 20px;
padding: 15px;
}
.column {
display: inline-block;
padding: 10px;
}
1225
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
body {
padding-top: 0px;
padding-bottom: 0px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
.sb-content-tab .center {
display: block;
}
.sb-content-tab #wrapper {
display: none;
}
#default-sidebar {
background-color: rgb(25, 118, 210);
color: #ffffff;
}
#default-sidebar .close-btn:hover {
color: rgba(0, 0, 0, .87);
background-color: #fafafa;
}
1226
}
.title-header {
text-align: center;
font-size: 18px;
padding: 15px;
}
.title.default {
padding: 25px 15px 15px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult autoclose()
{
return View();
}
}
}
In this sample,the Sidebar will be in an expanded state only in resolution below 400px .
razor
autoclose.cs
@{Html.EJS().Sidebar("default-sidebar").Width("280px").Created("onCreated").ContentTemp
late(@<div>
<div class="title-header">
<div style="display:inline-block"> Sidebar </div>
</div>
</div>).Render();}
<div>
<div class="title default">Main content</div>
<div class="sub-title">
Place your primary content here.
</div>
</div>
1227
<script type="text/javascript">
function onCreated() {
var obj = document.getElementById("default-sidebar").ej2_instances[0];
obj.mediaQuery = window.matchMedia('(max-width: 400px)');
}
</script>
<style>
.center-align {
text-align: center;
padding: 20px;
}
.title {
text-align: center;
font-size: 20px;
padding: 15px;
}
.column {
display: inline-block;
padding: 10px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
body {
padding-top: 0px;
padding-bottom: 0px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
.sb-content-tab .center {
display: block;
}
.sb-content-tab #wrapper {
display: none;
1228
}
#default-sidebar {
background-color: rgb(25, 118, 210);
color: #ffffff;
}
#default-sidebar .close-btn:hover {
color: rgba(0, 0, 0, .87);
background-color: #fafafa;
}
.title-header {
text-align: center;
font-size: 18px;
padding: 15px;
}
.title.default {
padding: 25px 15px 15px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
1229
public IActionResult autoclose()
{
return View();
}
}
}
1230
Dock
Dock state of the Sidebar reserves some space on the page that always remains in a visible
state when the Sidebar is collapsed. It is used to show the short term of a content like icons
alone instead of lengthy text.
razor
dock.cs
@{Html.EJS().Sidebar("dockSidebar").Width("220px").DockSize("72px").EnableDock(true).Co
ntentTemplate(@<div>
<div class="dock">
<ul>
<li class="sidebar-item" id="toggle">
<span class="e-icons expand"></span>
<span class="e-text" title="menu">Menu</span>
</li>
<li class="sidebar-item">
<span class="e-icons home"></span>
<span class="e-text" title="home">Home</span>
</li>
<li class="sidebar-item">
<span class="e-icons profile"></span>
<span class="e-text" title="profile">Profile</span>
</li>
<li class="sidebar-item">
<span class="e-icons info"></span>
<span class="e-text" title="info">Info</span>
</li>
<li class="sidebar-item">
<span class="e-icons settings"></span>
<span class="e-text" title="settings">Settings</span>
</li>
</ul>
</div>
</div>).Render();}
1231
dockBar = document.getElementById("dockSidebar").ej2_instances[0];
document.getElementById("toggle").addEventListener('click', function () {
dockBar.toggle();
});
});
function positionChange(args) {
dockBar.position = args.event.target.id == "Left" ? "Left" : "Right";
}
</script>
<style>
.title {
text-align: center;
font-size: 20px;
padding: 15px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
#wrapper .column {
display: inline-block;
padding: 10px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
.sb-content-tab .center {
display: block;
}
/* end of content area styles */
/* Sidebar styles */
.sb-content-tab #wrapper {
display: none;
}
1232
#dockSidebar.e-sidebar.e-right.e-close {
visibility: visible;
transform: translateX(0%);
}
#dockSidebar .e-icons::before {
font-size: 25px;
}
/* dockbar icon Style */
#dockSidebar .home::before {
content: '\e7a4';
}
#dockSidebar .profile::before {
content: '\e7d4';
}
#dockSidebar .info::before {
content: '\e7e7';
}
#dockSidebar .settings::before {
content: '\e7cf';
}
#dockSidebar.e-sidebar .expand::before,
#dockSidebar.e-sidebar.e-right.e-open .expand::before {
content: '\e85c';
}
#dockSidebar.e-sidebar.e-open .expand::before,
#dockSidebar.e-sidebar.e-right .expand::before {
content: '\e98f';
}
/* end of dockbar icon Style */
#dockSidebar.e-close .sidebar-item {
padding: 5px 20px;
}
#dockSidebar.e-dock.e-close span.e-text {
display: none;
}
#dockSidebar.e-dock.e-open span.e-text {
display: inline-block;
}
1233
#dockSidebar li {
list-style-type: none;
cursor: pointer;
}
#dockSidebar ul {
padding: 0px;
}
#dockSidebar.e-sidebar.e-open .e-text {
overflow: hidden;
text-overflow: ellipsis;
line-height: 23px;
font-size: 15px;
}
#dockSidebar.e-sidebar.e-open .e-icons {
margin-right: 16px;
}
#dockSidebar.e-sidebar span.e-icons {
color: #c0c2c5;
line-height: 2
}
.sidebar-item {
text-align: center;
border-bottom: 1px #e5e5e58a solid;
}
#dockSidebar.e-sidebar.e-open .sidebar-item {
text-align: left;
padding-left: 15px;
1234
color: #c0c2c5;
}
#dockSidebar.e-sidebar {
background: #2d323e;
overflow: hidden;
}
/* end of sidebar styles */
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult dock()
{
return View();
}
}
}
1235
How To
In the following example, the Sidebar is rendered with ListView component in its content area.
Add the HTML div tag with its id attribute as default in your index.html file to initialize
the Sidebar.
razor
sidebar.cs
@{Html.EJS().Sidebar("default-sidebar").Type(Syncfusion.EJ2.Navigations.SidebarType.Ove
r).Width("100%").ContentTemplate(@<div>
<div class="title1"> Menu </div>
<div class="closebtn">
@Html.EJS().Button("close").CssClass("e-btn close-btn").IconCss("e-icons cl
ose-icon").Render();
</div>
<div id="listcontainer">
@Html.EJS().ListView("list").DataSource((IEnumerable<object>)ViewBag.dataSo
urce).Render()
</div>
<div class="sub-title">
* ListView component is placed inside the sidebar content area.
</div>
</div>).Render();}
<div>
<div class="title2">Main content</div>
<div class="sub-title"> Click the button to open/close the Sidebar.</div>
<div style="padding:20px" class="center-align">
@Html.EJS().Button("toggle").Content("Toggle Sidebar").IsToggle(true).CssClass(
"e-info").Render()
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('toggle').onclick = function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
defaultSidebar.toggle();
1236
}
// Close the sidebar
document.getElementById('close').onclick = function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
defaultSidebar.hide();
}
});
</script>
<style>
#container {
visibility: hidden;
}
#loader {
color: #008cff;
height: 40px;
width: 30%;
position: absolute;
top: 45%;
left: 45%;
}
.center-align {
text-align: center;
padding: 20px;
}
.header {
width: 100%;
height: 40px;
font-size: 20px;
line-height: 40px;
font-weight: 500;
background: #eee;
display: inline-block;
}
.close-btn {
box-shadow: none;
}
.closebtn {
top: 15px;
1237
line-height: 36px;
height: 42px;
color: black;
position: absolute;
right: 10px;
}
#listcontainer {
width: 100%;
}
#list {
margin: 0 auto;
width: 30%;
}
.close-icon::before {
content: '\e945';
}
.e-listview .e-list-item {
text-align: center;
font-size: 14px;
padding: 0;
}
.title1 {
text-align: center;
font-size: 20px;
padding: 15px;
}
.title2 {
text-align: center;
font-size: 20px;
padding: 15px;
}
.sub-title {
text-align: center;
1238
font-size: 12px;
padding: 10px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
#wrapper {
display: block;
}
.sb-content-tab .center {
display: block;
}
.sb-content-tab #wrapper {
display: none;
}
.right {
float: right;
}
body {
margin: 0;
}
.close-btn:hover {
color: #fafafa;
}
using System;
1239
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult sidebar()
{
List<object> data = new List<object>();
data.Add(new { text = "Home", id = "list-01" });
data.Add(new { text = "Offers", id = "list-02" });
data.Add(new { text = "Support", id = "list-03" });
data.Add(new { text = "Logout", id = "list-04" });
ViewBag.dataSource = data;
return View();
}
}
}
In the following sample, toggle method has been used to show or hide the Sidebar on button
click.
razor
open.cs
@{Html.EJS().Sidebar("default-sidebar").ShowBackdrop(false).ContentTemplate(@<div>
<div class="title"> Sidebar content</div>
<div class="sub-title">
Click the button to close the Sidebar.
</div>
<div class="center-align">
@Html.EJS().Button("close").Content("CloseSidebar").Render()
</div>
</div>).Render();
}
<div>
1240
<div class="title">Main content</div>
<div class="sub-title"> Click the button to open/close the Sidebar.</div>
<div style="padding:20px" class="center-align">
@Html.EJS().Button("toggle").Content("Toggle Sidebar").CssClass("e-info").Ren
der()
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('toggle').onclick = function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
defaultSidebar.toggle();
}
// Close the sidebar
document.getElementById('close').onclick = function () {
var defaultSidebar = document.getElementById("default-sidebar").ej2_instanc
es[0];
defaultSidebar.hide();
}
});
</script>
<style>
.header {
width: 100%;
height: 40px;
font-size: 20px;
line-height: 40px;
font-weight: 500;
background: #eee;
display: inline-block;
}
.center-align {
text-align: center;
padding: 20px;
}
.title {
text-align: center;
1241
font-size: 20px;
padding: 15px;
}
.sub-title {
text-align: center;
font-size: 16px;
padding: 10px;
}
.center {
text-align: center;
display: none;
font-size: 13px;
font-weight: 400;
margin-top: 20px;
}
#wrapper {
display: block;
}
.right {
float: right;
}
body {
margin: 0;
}
#default-sidebar {
background-color: rgb(25, 118, 210);
color: #ffffff;
}
1242
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class SidebarController : Controller
{
public IActionResult open()
{
return View();
}
}
}
1243
Overview
The Slider component allows the user to select a value or range of values in-between the min
and max range, by dragging the handle over the slider bar.
Key Features
Types: Provided three types of Slider.
Buttons: Provided built-in support to render the buttons in both edges of the Slider.
Limits and Drag Interval: Slider thumb movement restriction and interval dragging.
1244
Getting Started
This section briefly explains about how to render Slider component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x , if you reference Syncfusion assemblies from trial setup or from
the NuGet feed, you also have to include a license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP .NET MVC application to
use our components.
@Html.EJS().Slider("slider").Type(SliderType.MinRange).Value(40).Render()
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("slider").Type(SliderType.MinRange).Value(40).Render()
}
1245
1246
Ticks
The Ticks in Slider supports you to easily identify the current value/values of the Slider. It
contains smallStep and largeStep . The value of the major ticks alone will be displayed in the
slider. In order to enable/disable the small ticks, use the showSmallTicks property.
razor
ticks.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Value("30").Ticks( new SliderTicksData { Placement =
Placement.After, LargeStep = 20, SmallStep = 10, ShowSmallTicks = true }).Tooltip(new S
liderTooltipData { IsVisible = true, Placement = TooltipPlacement.Before, ShowOn = Tool
tipShowOn.Always }).Render()
}
Step
When the Slider is moved, it increases/decreases the value based on the step value. By default,
the value is increased/decreased by 1. Use the step property to change the increment step
value.
razor
step.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Value("30").Step(10).Ticks( new SliderTicksData { Pla
cement = Placement.After, LargeStep = 20, SmallStep = 10, ShowSmallTicks = true }).Tool
tip(new SliderTooltipData { IsVisible = true, Placement = TooltipPlacement.Before, Show
On = TooltipShowOn.Always }).Render()
}
1247
{
return View();
}
razor
min-max.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(100).Max(1100).Value("300").Tooltip(new SliderToo
ltipData { IsVisible = true, ShowOn = TooltipShowOn.Always, Placement = TooltipPlacemen
t.Before }).Ticks(new SliderTicksData { Placement = Placement.After, LargeStep = 200, S
mallStep = 100, ShowSmallTicks = true }).Render()
}
1248
Formatting
The format feature used to customize the units of Slider values to desired format. The
formatted values will also be applied to the ARIA attributes of the slider. There are two ways of
achieving formatting in slider.
Use the format API of slider which utilizes our Internationalization to format values.
razor
format.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(0).Max(100).Value("30").Step(1).Tooltip(new Slide
rTooltipData { IsVisible = true, Format = "C2" }).Ticks(new SliderTicksData { Placement
= Placement.After, LargeStep = 20, SmallStep = 10, ShowSmallTicks = true, Format = "C2"
}).Render()
}
razor
format-api.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(0).Max(1).Value("0.3").Step(0.01).Tooltip(new Sli
derTooltipData { IsVisible = true, ShowOn = TooltipShowOn.Always, Format = "P0" ,Placem
ent=TooltipPlacement.Before}).Ticks(new SliderTicksData { Placement = Placement.After,
LargeStep = 0.2, SmallStep = 0.1, ShowSmallTicks = true, Format = "P0" }).Render()
1249
}
Using Events
In this method, we will be retrieving the values from the slider events then process them to
desired formatted the values. In this sample we have customized the ticks values into weekdays
as one formatting and tooltip values into day of the week as another formatting.
razor
events.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(0).Max(6).Value("0").Step(1).Tooltip(new SliderTo
oltipData { IsVisible = true, Placement = TooltipPlacement.Before }).Ticks(new SliderTi
cksData { Placement = Placement.After, LargeStep = 1 }).TooltipChange("tooltipChangeHan
dler").RenderingTicks("renderingTicksHandler").Render()
}
<script>
function renderingTicksHandler(args) {
// Weekdays Array
var daysArr = ['Sunday','Monday','Tuesday','Wednesday','Thrusday','Friday','Saturda
y'];
// Customizing each ticks text into weeksdays
args.text = daysArr[parseFloat(args.value)];
}
function tooltipChangeHandler(args) {
// Customizing tooltip to display the Day (in numeric) of the week
args.text = 'Day ' + (Number(args.value) + 1).toString();
}
</script>
1250
Movement Limits and Drag Interval
The slider limits restrict the slider thumb between a particular range. This is used if higher or
lower value affects the process or product where the slider is being used.
The following are the six options in the slider's limits object. Each API in the limits object is
optional.
razor
default-limits.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(0).Max(100).Value(25).Type(SliderType.Default).En
abled(true).Tooltip(new SliderTooltipData { IsVisible = true }).Limits(new SliderLimitD
ata { Enabled = true, MinStart = 10, MinEnd = 40 }).Render()
}
return View();
}
1251
In the range slider, both handles can be restricted and locked from the limit's object. In this
sample, the first handle is limited between 10 and 40, and the second handle is limited between
60 and 90.
razor
range-limits.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@Html.EJS().Slider("default").Min(0).Max(100).Value(ViewBag.range).Type(SliderType.Rang
e).Enabled(true).Tooltip(new SliderTooltipData { IsVisible = true }).Limits(new SliderL
imitData { Enabled = true, MinStart = 10, MinEnd = 40, MaxStart = 60, MaxEnd = 90 }).Re
nder()
Handle lock
The movement of slider handles can be locked by enabling the startHandleFixed and
endHandleFixed properties in the limit's object. In this sample, the movement of both slider
handles has been locked.
razor
handle-lock.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(0).Max(100).Value(ViewBag.range).Type(SliderType.
Range).Enabled(true).Tooltip(new SliderTooltipData { IsVisible = true }).Limits(new Sli
derLimitData { Enabled = true, StartHandleFixed = true, EndHandleFixed = true }).Render
()
}
1252
Accessibility
The Slider is characterized with complete ARIA Accessibility support that helps to access by on-
screen readers and other assistive technology devices. This component is designed with the
reference of guidelines document given in the WAI ARAI Accessibility Practices.
The Slider component uses the Slider role and the following ARIA properties for its element
based on the state.
Properties Functionalities
aria-label Slider left and right button label text (increment and decrement).
aria-labelledby It indicates the name of the Slider.
Keyboard interaction
The Keyboard interaction of the Slider component is designed based on the WAI-ARIA Practices
described for Slider. Users can use the following shortcut keys to interact with the Slider.
Keyboard
Actions
shortcuts
Right
Arrow Up Increase the Slider value.
Arrow
Left
Arrow Down Decrease the Slider value.
Arrow
Home Moves to the start value (for Range Slider when the second thumb is
focused and the Home key is pressed, it moves to the first thumb value).
End Moves to the end value (for Range Slider when the first thumb is focused
and the End key is pressed, it moves to the second thumb value).
1253
accessbility.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("minRangeObj").Value(30).Step(10).Type(SliderType.MinRange).Show
Buttons(true).Ticks(new SliderTicksData { Placement = Placement.After, LargeStep = 20,
SmallStep = 10, ShowSmallTicks = true }).Tooltip(new SliderTooltipData { IsVisible = tr
ue, Placement = TooltipPlacement.Before, ShowOn = TooltipShowOn.Always }).Render()
@Html.EJS().Slider("weekdaysObj").Min(0).Max(6).Step(1).Ticks(new SliderTicksData {
Placement = Placement.After, LargeStep = 1 }).Tooltip(new SliderTooltipData { IsVisibl
e = true, Placement = TooltipPlacement.Before }).RenderingTicks("renderingTicks").Toolt
ipChange("onTooltipChange").Render()
}
<script>
function renderingTicks(args) {
// Weekdays Array
var daysArr = ['Sunday','Monday','Tuesday','Wednesday','Thrusday','Friday','Saturda
y'];
// Customizing each ticks text into weeksdays
args.value = daysArr[parseFloat(args.value)];
}
function onTooltipChange(args) {
// Customizing tooltip to display the Day (in numeric) of the week
args.tooltipText = 'Day ' + (Number(args.tooltipText) + 1).toString();
}
</script>
1254
How To
Date Format
The Date formatting can be achieved in ticks and tooltip using renderingTicks and
tooltipChange events respectively. The process of formatting is explained in the below sample.
razor
date-format.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(1371081600000).Max(1371772800000).Step(86400000).
TooltipChange("tooltipChangeHandler").RenderingTicks("renderingTicksHandler").ShowButto
ns(true).Tooltip(new SliderTooltipData { Placement = TooltipPlacement.Before, IsVisible
= true }).Ticks(new SliderTicksData { Placement = Placement.After, LargeStep = 1728000
00, }).Render()
}
<script>
function tooltipChangeHandler(args) {
var totalMiliSeconds = Number(args.text);
// Converting the current milliseconds to the respective date in desired format
var custom = { year: "numeric", month: "short", day: "numeric" };
args.text = new Date(totalMiliSeconds).toLocaleDateString("en-us", custom);
}
function renderingTicksHandler(args) {
var totalMiliSeconds = Number(args.value);
// Converting the current milliseconds to the respective date in desired format
var custom = { year: "numeric", month: "short", day: "numeric" };
args.text = new Date(totalMiliSeconds).toLocaleDateString("en-us", custom);
}
</script>
Time Format
1255
The time formatting can be achieved same as the date formatting using renderingTicks and
change events. The process of time formatting is explained in the below sample.
razor
time-format.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
@section ControlsSection{
@Html.EJS().Slider("default").Min(1373693400000).Max(1373715000000).Step(3600000).R
enderingTicks("renderingTicksHandler").TooltipChange("tooltipChangeHandler").Tooltip(new
SliderTooltipData { Placement = TooltipPlacement.Before, IsVisible = true }).Ticks(new
SliderTicksData { Placement = Placement.After, LargeStep = 7200000 }).ShowButtons(true
).Render()
}
<script type="text/javascript">
function tooltipChangeHandler(args) {
var totalMiliSeconds = Number(args.text);
var custom = { hour: '2-digit', minute: '2-digit' };
args.text = new Date(totalMiliSeconds).toLocaleTimeString("en-us", custom);
}
function renderingTicksHandler(args) {
var totalMiliSeconds = Number(args.value);
var custom = { hour: '2-digit', minute: '2-digit' };
args.text = new Date(totalMiliSeconds).toLocaleTimeString("en-us", custom);
}
</script>
razor
numeric-value.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Inputs
1256
@section ControlsSection{
<div id='kilometer'>
@Html.EJS().Slider("kilometer").Min(0).Max(100).Step(1).Value("30").Tooltip(new
SliderTooltipData { IsVisible = true, Format = "##.## Km" }).Ticks(new SliderTicksData
{ Placement = Placement.After, LargeStep = 20, SmallStep = 10, ShowSmallTicks = true,
Format = "##.## Km" }).Render()
</div>
<div id='decimal'>
@Html.EJS().Slider("decimalobj").Min(0.1).Max(0.2).Value("0.15").Step(0.01).Too
ltip(new SliderTooltipData { IsVisible = true, Format = "##.#00" }).Ticks(new SliderTic
ksData { Placement = Placement.After, LargeStep = 0.02, SmallStep = 0.01, ShowSmallTick
s = true, Format = "##.#00" }).Render()
</div>
<div id='slider'>
@Html.EJS().Slider("sliderobj").Min(0).Max(100).Value("5").Step(1).Tooltip(new
SliderTooltipData { IsVisible = true, Format = "##.## Km" }).Ticks(new SliderTicksData
{ Placement = Placement.After, LargeStep = 20, SmallStep = 10, ShowSmallTicks = true, F
ormat = "##.## Km" }).Render()
</div>
}
1257
Overview
Split button triggers default action when primary button is clicked and toggle contextual overlays
for displaying list of action items when dropdown button is clicked. It can contain both text and
images.
Key Features
Icons
Popup Items
Accessibility
How To
1258
Getting Started
This section briefly explains about how to include a simple SplitButton in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)ViewBag.
items).Render()
ViewBag.items variable is used for bounding the items property in view page.
Bind dataSource
Populate the action items in SplitButton by using the items property. Here, the JSON values
are passed to the SplitButton component are generated in HomeController.cs and assigned to
ViewBag variable.
1259
Output be like the below.
razor
default.cs
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)ViewBag.
items).Render()
1260
Icons
SplitButton Icons
SplitButton can have an icon to provide the visual representation of the action. To place the icon
on a SplitButton, set the iconCss property to e-icons with the required icon CSS. By default,
the icon is positioned to the left side of the SplitButton. You can customize the icon's position by
using the iconPosition property
razor
iconbutton.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).IconCss("e-icons e-paste").Render()
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).IconCss("e-icons e-paste".iconPosition("Top")).Render()
}
<style>
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
.e-paste::before {
content: '\e71f';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult IconButton()
1261
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
The Essential JS 2 provides a set of icons that can be loaded by applying e-icons class
name to the element. You can also use third party icons on the SplitButton using the
iconCss property.
Vertical Button
Vertical Button in SplitButton can be achieved by adding e-vertical class using cssClass
property.
razor
verticalbutton.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).IconCss("e-icons e-paste").CssClass("e-vertical").Render()
}
<style>
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
.e-paste::before {
content: '\e71f';
1262
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult VerticalButton()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
1263
Popup Items
Icons
The Popup action item have an icon or image to provide visual representation of the action. To
place the icon on a popup item, set the iconCss property to e-icons with the required icon
CSS. By default, the icon is positioned to the left side of the popup action item.
In the following sample, the icons for Cut, Copy, Paste, Undo and Redo menu items are added
using the iconCss property.
razor
popupicons.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)ViewB
ag.items).IconCss("e-icons e-paste").Render()
<style>
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
1264
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult PopupIcons()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut",
iconCss = "e-icons e-cut"
});
items.Add(new
{
text = "Copy",
iconCss = "e-icons e-copy"
});
items.Add(new
{
text = "Paste",
iconCss = "e-icons e-paste"
});
ViewBag.items = items;
return View();
}
}
}
Template
Item Templating
Popup items can be customized by using the beforeItemRender event. The item render event
triggers while rendering each Popup action item. The event argument will be used to identify the
action item and customize it based on the requirement.
razor
itemtemplate.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Items((IEnumerable<object>)ViewBag.items).IconCss
("e-icons e-paste").beforeItemRender("beforeItemRender").Render()
1265
<scripts>
function beforeItemRender(args) {
var shortCutSpan = createElement('span');
var text = args.item.text;
args.element.appendChild(shortCutSpan);
shortCutSpan.setAttribute('class','shortcut');
shortCutSpan.classList.add('e-icons');
(text === 'Cut') ? shortCutSpan.classList.add('e-cut') : (text === 'Paste') ? s
hortCutSpan.classList.add('e-paste') : shortCutSpan.classList.add('e-copy');
}
</scripts>
<style>
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult ItemTemplate()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut"
1266
});
items.Add(new
{
text = "Copy"
});
items.Add(new
{
text = "Paste"
});
ViewBag.items = items;
return View();
}
}
}
Popup Templating
The whole popup can be customized as per the requirement. In the following example, the popup
can be customized by handling it in target property.
razor
popuptemplate.cs
@section ControlsSection{
<div id='dropdowntarget'>
<div id= "first">
<div id='black'></div>
<div id='red'></div>
<div id='green'></div>
<div id='gray'></div>
<div id='blue'></div>
<div id='violet'></div>
<div id='brown'></div>
<div id='darkgoldenrod'></div>
<div id='aquamarine'></div>
</div>
</div>
@Html.EJS().SplitButton("element").Target("#dropdowntarget").IconCss("e-icons e-col
or").Render()
<style>
.shortcut {
float: right;
margin-top: 9px;
1267
padding-left: 30px;
}
.e-color::before {
content: '\e778';
color:black;
}
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
#dropdowntarget {
border: 0.5px solid grey;
height: 110px;
width: 110px;
}
#black {
width: 30px;
height: 30px;
background-color: black;
margin: 5px 5px;
float:left;
}
#red{
width: 30px;
height: 30px;
background-color: red;
margin: 5px 0px;
float:left;
}
#green{
width: 30px;
height: 30px;
background-color: green;
margin: 5px 5px;
float:left;
}
#gray{
width: 30px;
height: 30px;
background-color: gray;
margin: 0px 5px;
float:left;
}
1268
#blue{
width: 30px;
height: 30px;
background-color: blue;
float:left;
}
#violet{
width: 30px;
height: 30px;
background-color: violet;
margin: 0px 5px;
float:left;
}
#brown{
width: 30px;
height: 30px;
background-color: brown;
margin: 5px 5px;
float:left;
}
#darkgoldenrod{
width: 30px;
height: 30px;
background-color: darkgoldenrod;
margin: 5px 0px;
float:left;
}
#aquamarine{
width: 30px;
height: 30px;
background-color: aquamarine;
margin: 5px 5px;
float:left;
}
#icon{
width: 10px;
height: 10px;
background-color: aquamarine;
position: absolute;
}
</style>
1269
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult PopupTemplate()
{
return View();
}
}
}
1270
Accessibility
ARIA attributes
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies. SplitButton provides
built-in compliance with WAI-ARIA specifications. WAI-ARIA support is achieved through the
attributes like aria-expanded , aria-owns and aria-haspopup applied for action item in
SplitButton. It helps the people with disabilities by providing information about the widget for
assistive technology in the screen readers. SplitButton component contains the menuItem role.
Properties Functionality
aria-
Indicates the availability and type of interactive SplitButton popup element.
haspopup
Keyboard interaction
Keyboard
Actions
shortcuts
Esc Closes the opened popup.
Enter Opens the popup, or activates the highlighted item and closes the
popup.
razor
accessibility.cs
1271
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)ViewB
ag.items).IconCss("e-icons e-paste").Render()
<style>
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
.e-cut::before {
content: '\e759';
}
.e-copy::before {
content: '\e70a';
}
.e-paste::before {
content: '\e71f';
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult Accessibility()
{
List<object> items = new List<object>();
items.Add(new
{
text = "Cut",
iconCss = "e-icons e-cut"
});
items.Add(new
{
text = "Copy",
iconCss = "e-icons e-copy"
1272
});
items.Add(new
{
text = "Paste",
iconCss = "e-icons e-paste"
});
ViewBag.items = items;
return View();
}
}
}
1273
How To
The following section explains how to customize various aspects of the SplitButton.
The following example illustrates how to set the disable state in SplitButton component.
razor
disabled.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).IconCss("e-icons e-sigma").Disabled(true).Render()
<styles>
.e-sigma::before {
content: '\e7d3';
}
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
</styles>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult Disabled()
{
1274
//define the array of JSON
List<object> items = new List<object>();
items.Add(new
{
text = "Autosum"
});
items.Add(new
{
text = "Average"
});
items.Add(new
{
text = "Count numbers"
});
items.Add(new
{
text = "Min"
});
items.Add(new
{
text = "Max"
});
ViewBag.items = items;
return View();
}
}
}
The following example illustrates how to enable right-to-left support in SplitButton component.
razor
rtl.cs
@section ControlsSection{
@Html.EJS().SplitButton("element").Content("Paste").Items((IEnumerable<object>)View
Bag.items).IconCss("e-icons e-sigma").EnableRtl(true).Render()
<styles>
.e-sigma::before {
1275
content: '\e7d3';
}
.e-split-btn-wrapper{
margin: 20px 20px 5px 5px;
}
</styles>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class SplitButtonController : Controller
{
public IActionResult Rtl()
{
//define the array of JSON
List<object> items = new List<object>();
items.Add(new
{
text = "Autosum"
});
items.Add(new
{
text = "Average"
});
items.Add(new
{
text = "Count numbers"
});
items.Add(new
{
text = "Min"
});
items.Add(new
{
text = "Max"
});
ViewBag.items = items;
return View();
}
}
1276
}
In the following example, Dialog will open while selecting Update... item:
In this following example, ListView is created and its element is set as target for SplitButton.
1277
Overview
The Switch is a graphical user interface element that allows you to toggle between checked and
unchecked states.
Key Features
Supports text.
Supports small size.
1278
Getting Started
This section briefly explains about how to include a simple Switch in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
default.cs
@Html.EJS().Switch("default").Render()
razor
default.cs
@Html.EJS().Switch("default").Render()
1279
razor
default.cs
@Html.EJS().Switch("default").OnLabel("ON").OffLabel("OFF").Render()
Switch does not have text support for material themes, and does not support long custom
text.
1280
Accessibility
The web accessibility makes web content and web applications more accessible for people with
disabilities. It especially helps in dynamic content change and development of advanced user
interface controls with AJAX, HTML, JavaScript, and related technologies.
Properties Functionality
aria-
Indicates whether the input is checked, unchecked.
checked
aria- Indicates that the element is perceivable but disabled, so it is not editable or
disabled otherwise operable.
Keyboard interaction
Keyboard
Actions
shortcuts
Space When the switch has focus, pressing the Space key changes the state
of the switch.
razor
default.cs
@section ControlsSection {
<div id='container'>
<table class='size'>
<tr>
<td class='lSize'>Checked</td>
<td>
@Html.EJS().Switch("switch1").Checked(true).Render()
</td>
</tr>
<tr>
<td class='lSize'>Unchecked</td>
<td>
@Html.EJS().Switch("switch2").Render()
</td>
</tr>
1281
</table>
</div>
}
<style>
#container {
visibility: hidden;
margin-left: 10px;
}
#loader {
color: #008cff;
height: 40px;
width: 30%;
position: absolute;
top: 45%;
left: 45%;
}
.size tr td {
padding: 10px;
}
.size .lSize {
font-family: "Roboto", "Segoe UI", "GeezaPro", "DejaVu Serif", "sans-serif";
font-size: 13px;
cursor: pointer;
user-select: none;
}
</style>
1282
How To
razor
default.cs
@section ControlsSection {
@Html.EJS().Switch("switch1").cssClass("square").Render()
@Html.EJS().Switch("switch2").cssClass("custom-switch").Render()
@Html.EJS().Switch("switch3").cssClass("handle-text").Render()
}
<style>
/* Square Switch */
.e-switch-wrapper.square .e-switch-inner,
.e-switch-wrapper.square .e-switch-handle {
border-radius: 0;
}
.e-switch-wrapper.custom-switch .e-switch-handle {
width: 20px;
height: 16px;
}
.e-switch-wrapper.custom-switch .e-switch-inner,
.e-switch-wrapper.custom-switch .e-switch-handle {
1283
border-radius: 0;
}
.e-switch-wrapper.custom-switch .e-switch-handle.e-switch-active {
left: 42px;
}
.e-switch-wrapper.handle-text .e-switch-handle {
width: 26px;
height: 20px;
left: 2px;
background-color: #fff;
}
.e-switch-wrapper.handle-text .e-switch-inner,
.e-switch-wrapper.handle-text .e-switch-handle {
border-radius: 0;
}
.e-switch-wrapper.handle-text .e-switch-handle.e-switch-active {
left: 46px;
}
.e-switch-wrapper.handle-text .e-switch-inner.e-switch-active,
.e-switch-wrapper.handle-text:hover .e-switch-inner.e-switch-active .e-switch-on {
background-color: #4d841d;
border-color: #4d841d;
}
.e-switch-wrapper.handle-text .e-switch-inner,
.e-switch-wrapper.handle-text .e-switch-off {
background-color: #e3165b;
border-color: #e3165b;
}
.e-switch-wrapper.handle-text .e-switch-inner:after,
.e-switch-wrapper.handle-text .e-switch-inner:before {
font-size: 10px;
position: absolute;
line-height: 21px;
font-family: "Helvetica", sans-serif;
z-index: 1;
height: 100%;
1284
transition: all 200ms cubic-bezier(0.445, 0.05, 0.55, 0.95);
}
.e-switch-wrapper.handle-text .e-switch-inner:before {
content: "OFF";
color:#e3165b;
left: 3px;
}
.e-switch-wrapper.handle-text .e-switch-inner:after{
content: "ON";
right: 5px;
color: #fff;
}
input[class$='e-switch']:checked + .e-switch-inner:before {
color: #fff;
}
input[class$='e-switch']:checked + .e-switch-inner:after {
color: #4d841d;
}
</style>
razor
default.cs
@section ControlsSection {
@Html.EJS().Switch("switch1").cssClass("bar-color").Render()
@Html.EJS().Switch("switch2").cssClass("handle-color").Render()
@Html.EJS().Switch("switch3").cssClass("custom-iOS").Render()
}
<styles>
/* Custom color Switch */
1285
.e-switch-wrapper.bar-color .e-switch-inner.e-switch-active,
.e-switch-wrapper.bar-color:hover .e-switch-inner.e-switch-active .e-switch-on {
background-color: #4d841d;
border-color: #4d841d;
}
.e-switch-wrapper.bar-color .e-switch-inner,
.e-switch-wrapper.bar-color .e-switch-off {
background-color: #e3165b;
border-color: #e3165b;
}
.e-switch-wrapper.bar-color .e-switch-handle {
background-color: #fff;
}
.e-switch-wrapper.handle-color .e-switch-handle.e-switch-active {
background-color: #4d841d
}
.e-switch-wrapper.handle-color .e-switch-inner.e-switch-active,
.e-switch-wrapper.handle-color:hover .e-switch-inner.e-switch-active .e-switch-on {
background-color: #fff;
border-color: #ccc;
}
.e-switch-wrapper.handle-color .e-switch-inner,
.e-switch-wrapper.handle-color .e-switch-off {
background-color: #fff;
border-color: #ccc;
}
/* iOS Switch */
.e-switch-wrapper.custom-iOS .e-switch-inner.e-switch-active,
.e-switch-wrapper.custom-iOS:hover .e-switch-inner.e-switch-active .e-switch-on {
background-color: #3df865;
border-color: #3df665;
}
.e-switch-wrapper.custom-iOS {
width: 42px;
height: 24px;
}
1286
.e-switch-wrapper.custom-iOS .e-switch-handle {
width: 20px;
height: 20px;
}
.e-switch-wrapper.custom-iOS .e-switch-handle.e-switch-active {
margin-left: -22px;
}
</styles>
Change Size
The different Switch sizes available are default and small. To reduce the size of default Switch to
small, set the cssClass property to e-small .
razor
default.cs
@section ControlsSection {
<div id='container'>
<table class='size'>
<tr>
<td class='lSize'>Small</td>
<td>
@Html.EJS().Switch("switch1").cssClass("e-small").Render()
</td>
</tr>
<tr>
<td class='lSize'>Default</td>
<td>
@Html.EJS().Switch("switch2").Render()
</td>
</tr>
</table>
</div>
}
<style>
#container {
visibility: hidden;
margin-left: 10px;
1287
}
#loader {
color: #008cff;
height: 40px;
width: 30%;
position: absolute;
top: 45%;
left: 45%;
}
.size tr td {
padding: 10px;
}
.size .lSize {
font-family: "Roboto", "Segoe UI", "GeezaPro", "DejaVu Serif", "sans-serif";
font-size: 13px;
cursor: pointer;
user-select: none;
}
</style>
razor
default.cs
@Html.EJS().Switch("default").Disabled(true).Render()
1288
Enable ripple for Switch label
By default, label with ripple effect is not available in Switch. You can achieve this using
rippleMouseHandler method. The following example illustrates how to enable ripple effect for
labels in Switch component.
razor
default.cs
@section ControlsSection {
<div id='container'>
<table class='size'>
<tr>
<td class='lSize'><label for='switch1'>USB Tethering</label></td>
<td>
@Html.EJS().Switch("switch1").Render()
</td>
</tr>
</table>
</div>
}
<style>
#container {
visibility: hidden;
margin-left: 10px;
}
#loader {
color: #008cff;
height: 40px;
width: 30%;
position: absolute;
top: 45%;
left: 45%;
}
.e-switch-wrapper {
margin-top: 18px;
}
.size tr td {
padding: 10px;
}
.size .lSize {
padding-top: 24px;
font-family: "Roboto", "Segoe UI", "GeezaPro", "DejaVu Serif", "sans-serif";
1289
font-size: 13px;
}
</style>
Enable RTL
Switch component has RTL support. This can be achieved by setting enableRtl as true .
The following example illustrates how to enable right-to-left support in Switch component.
razor
default.cs
@Html.EJS().Switch("default").EnableRtl(true).Render()
In the following code snippet, USB and Wi-Fi in the checked state, and Bluetooth is in disabled
state. Values that are in checked state only be sent on form submit.
razor
default.cs
1290
@section ControlsSection {
<div id='container'>
<form>
<table class='size'>
<tr>
<td class='lSize'>USB</td>
<td>
@Html.EJS().Switch("switch1").Checked(true).Render()
</td>
</tr>
<tr>
<td class='lSize'>Wi-Fi</td>
<td>
@Html.EJS().Switch("switch2").Checked(true).Render()
</td>
</tr>
<tr>
<td class='lSize'>Bluetooth</td>
<td>
@Html.EJS().Switch("switch3").Render()
</td>
</tr>
<tr>
<td>
@Html.EJS().Button("switch1").Render()
</td>
</tr>
</table>
</form>
</div>
}
<style>
#container {
visibility: hidden;
}
#loader {
color: #008cff;
height: 40px;
width: 30%;
position: absolute;
top: 45%;
left: 45%;
}
button {
margin: 20px 0 0 5px;
1291
}
.size tr td {
padding: 10px;
}
.size .lSize {
font-family: "Roboto", "Segoe UI", "GeezaPro", "DejaVu Serif", "sans-serif";
font-size: 13px;
}
1292
Overview
The TextBox is an input element that allows to get input from the user. It allows the user to edit or
display the text value.
Key features
Groups: Supports to group the icon element with the input.
Floating Label: Enables floating support to placeholder text of TextBox.
Sizing: Allows to set Small and Normal sized TextBox.
Validation States: Supports to indicate Success , Error , and Warning state.
1293
Getting Started
This section briefly explains about how to include a simple Textbox in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include the license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP.NET MVC application to
use our components.
Prerequisites
To get start with ASP.NET Core application, need to ensure the following software to be installed
on the machine.
Step 1 : Create ASP.NET Core Web Application with default template project in Visual Studio
2017.
1294
Step 2 : Once your project created. We need to add Syncfusion EJ2 package into your
application by using Nugget Package Manager.
1295
Install the Syncfusion.EJ2 package to the application.
After Installation complete this will included in the project. You can refer it from the Project
Assembly Reference.
1296
@addTagHelper *, Syncfusion.EJ2
Step 4 : Add client side resource through CDN or local package in the layout page
_Layout.cshtml.
<ej-scripts> </ej-scripts>
Step 6 : Adding Syncfusion Essential JS2 for ASP.Net Core component in any page you want.
<div class="e-input-group">
<input class="e-input" placeholder="Enter Name" type="text">
</div>
razor
input.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-input-group">
<input class="e-input" name='input' type="text" placeho
lder="Enter Name"/>
</div>
</div>
1297
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
var inputObject = {};
var input = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e
-input-group input');
var focusFn = function (index) {
return function () {
getParentNode(input[index]).classList.add('e-input-focus');
};
};
var blurFn = function (index) {
return function () { getParentNode(input[index]).classList.remove('e-input-
focus'); };
};
for (var i = 0; i < input.length; i++) {
input[i].addEventListener('focus', focusFn(i));
input[i].addEventListener('blur', blurFn(i));
}
function getParentNode(element) {
var parentNode = element.parentNode;
if (parentNode.classList.contains('e-input-in-wrap')) {
return parentNode.parentNode;
}
return parentNode;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
1298
}
}
razor
icon.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-input-group">
<input class="e-input" name='input' type="text" placeho
lder="Enter Date"/>
<span class="e-input-group-icon e-input-popup-date"></s
pan>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
var inputObject = {};
var input = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e
-input-group input');
var inputIcon = document.querySelectorAll('.e-input-group-icon');
var focusFn = function (index) {
return function () {
getParentNode(input[index]).classList.add('e-input-focus');
};
};
var blurFn = function (index) {
return function () { getParentNode(input[index]).classList.remove('e-input-
focus'); };
};
var mouseupFn = function () {
var ele = this; setTimeout(function () {
ele.classList.remove('e-input-btn-ripple');
}, 500);
1299
};
for (var i = 0; i < input.length; i++) {
input[i].addEventListener('focus', focusFn(i));
input[i].addEventListener('blur', blurFn(i));
}
for (var j = 0; j < inputIcon.length; j++) {
inputIcon[j].addEventListener('mousedown', function () {
this.classList.add('e-input-btn-ripple');
});
inputIcon[j].addEventListener('mouseup', mouseupFn);
}
function getParentNode(element) {
var parentNode = element.parentNode;
if (parentNode.classList.contains('e-input-in-wrap')) {
return parentNode.parentNode;
}
return parentNode;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
Floating label
The floating label TextBox floats the label above the TextBox after focusing, or filled with value in
the TextBox. You can create the floating label TextBox by creating the parent div element with
the class e-float-input and append the span, label elements with the class added as e-
1300
float-line and e-float-text accordingly. For detailed information, refer to the Groups
section.
razor
floating.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-float-input e-input-group">
<input type="text" required/>
<span class="e-float-line"></span>
<label class="e-float-text">Enter Date </label>
<span class="e-input-group-icon e-input-popup-date"></s
pan>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
var inputObject = {};
var input = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e
-input-group input');
var inputIcon = document.querySelectorAll('.e-input-group-icon');
var focusFn = function (index) {
return function () {
getParentNode(input[index]).classList.add('e-input-focus');
};
};
var blurFn = function (index) {
return function () { getParentNode(input[index]).classList.remove('e-input-
focus'); };
};
var mouseupFn = function () {
var ele = this; setTimeout(function () {
ele.classList.remove('e-input-btn-ripple');
}, 500);
};
for (var i = 0; i < input.length; i++) {
input[i].addEventListener('focus', focusFn(i));
input[i].addEventListener('blur', blurFn(i));
}
for (var j = 0; j < inputIcon.length; j++) {
1301
inputIcon[j].addEventListener('mousedown', function () {
this.classList.add('e-input-btn-ripple');
});
inputIcon[j].addEventListener('mouseup', mouseupFn);
}
function getParentNode(element) {
var parentNode = element.parentNode;
if (parentNode.classList.contains('e-input-in-wrap')) {
return parentNode.parentNode;
}
return parentNode;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1302
Groups
The following section explains you the steps required to create TextBox with icon and
floating label .
TextBox:
Place input element with the class e-input inside the parent div element.
<div class="e-input-group">
<input class="e-input" name='input' type="text" placeholder="Enter Date"/>
</div>
Floating label:
Remove the e-input class and add required attribute to the input element.
Place the span element with class e-float-line after the input element.
Place the label element with class e-float-text after the above created span element.
When you focus or filled with value in the TextBox, the label floats above the TextBox.
Creating the Floating label TextBox, you have to set the required attribute to the Input
element to achieve the floating label functionality which is used for validating the value
existence in TextBox. If you want to render the Floating label TextBox without required
attribute then refer to the Floating label without required attribute section.
And refer to the following sections to add the icons to the TextBox.
1303
For the floating label enabled TextBox add the icon element as first or last element inside the
TextBox wrapper,and based on the element position it will act as prefix or suffix icon.
razor
icon.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<h4> TextBox with icons </h4>
<div class="e-input-group">
<input class="e-input" type="text" placeholder="Enter
Date"/>
<span class="e-input-group-icon e-input-popup-date"><
/span>
</div>
1304
<div class="e-float-input e-input-group e-float-icon-left">
<span class="e-input-group-icon e-input-date"><
/span>
<div class="e-input-in-wrap">
<input required type="text" />
<span class="e-float-line"></span>
<label class="e-float-text"> Enter Date
</label>
</div>
</div>
@section Script{
<script>
ej.base.enableRipple(true);
var inputObject = {};
var input = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e
-input-group input');
var inputIcon = document.querySelectorAll('.e-input-group-icon');
var focusFn = function (index) {
return function () {
getParentNode(input[index]).classList.add('e-input-focus');
};
};
var blurFn = function (index) {
return function () { getParentNode(input[index]).classList.remove('e-input-
focus'); };
};
var mouseupFn = function () {
var ele = this; setTimeout(function () {
ele.classList.remove('e-input-btn-ripple');
}, 500);
};
for (var i = 0; i < input.length; i++) {
1305
input[i].addEventListener('focus', focusFn(i));
input[i].addEventListener('blur', blurFn(i));
}
for (var j = 0; j < inputIcon.length; j++) {
inputIcon[j].addEventListener('mousedown', function () {
this.classList.add('e-input-btn-ripple');
});
inputIcon[j].addEventListener('mouseup', mouseupFn);
}
function getParentNode(element) {
var parentNode = element.parentNode;
if (parentNode.classList.contains('e-input-in-wrap')) {
return parentNode.parentNode;
}
return parentNode;
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
You can add the clear button to the TextBox by placing the span element with the class e-clear-
icon after the input element.
razor
1306
clear.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<h4> TextBox with clear button </h4>
<div class="e-input-group">
<input class='e-input custom-input0' required="true" pl
aceholder="Enter Name" value="John"/>
<span class="e-clear-icon"></span>
</div>
<h4> Floating TextBox with clear button </h4>
<div class="e-float-input e-input-group">
<input required="true" class="custom-input1" value="Joh
n" />
<span class="e-float-line"></span>
<label class="e-float-text">Enter Name </label>
<span class="e-clear-icon"></span>
</div>
</div>
</div>
}
@section Script{
<script>
var inputObject = {};
var input = document.querySelectorAll('.e-input-group .e-input,.e-float-input.e
-input-group input');
var focusFn = function (index) {
return function () {
getParentNode(input[index]).classList.add('e-input-focus');
};
};
var blurFn = function (index) {
return function () { getParentNode(input[index]).classList.remove('e-input-
focus'); };
};
1307
}
return parentNode;
}
// Code to clear the input field when click on clear button
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
You should add the code to handle the click event of clear button.
1308
razor
floating.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-float-input">
<input type="text" id='inpt1' />
<span class="e-float-line"></span>
<label class="e-float-text"> Enter Value </label>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
/* To get the Input element */
var inputElement = document.getElementById('inpt1');
inputElement.addEventListener("focus", function () {
var label = this.parentElement.querySelector('.e-float-text');
label.classList.add('e-label-bottom');
label.classList.remove('e-label-top');
});
inputElement.addEventListener("blur", function () {
updateLabelState(this.value, this.parentElement.querySelector('
.e-float-text'));
});
inputElement.addEventListener("input", function () {
updateLabelState(this.value, this.parentElement.querySelector('
.e-float-text'));
});
1309
function updateLabelState(value,label) {
if (value) {
label.classList.add('e-label-top');
label.classList.remove('e-label-bottom');
} else {
label.classList.add('e-label-bottom');
label.classList.remove('e-label-top');
}
}
</script>
}
<style>
.control-section {
box-sizing: border-box;
margin: 0 auto;
padding: 20px 10px;
width: 260px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1310
Add the floating label support to the multi-line input by creating the floating label structure as
defined in the initial section.
razor
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<textarea class="e-input"> Address </textarea>
<div class="e-float-input">
<textarea required></textarea>
<span class="e-float-line"></span>
<label class="e-float-text"> Address </label>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1311
put-focus');
} else {
this.parentNode.classList.remove('e-input-focus'
);
}
});
}
</script>
}
1312
Sizing
You can render the TextBox in two different sizes.
Property Description
You need to add e-small class to the input element, or else add to the input
Small
container.
razor
sizing.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<h4> Normal Size </h4>
<div class="e-input-group">
<input class="e-input" type="text" placeholder="Enter N
ame" />
</div>
<div class="e-float-input">
<input type='text' required />
<span class="e-float-line"></span>
<label class="e-float-text">Enter Name</label>
</div>
<div class="e-input-group">
<input class="e-input" type="text" placeholder="Enter D
ate" />
<span class="e-input-group-icon e-input-popup-date"></s
pan>
</div>
1313
<span class="e-float-line"></span>
<label class="e-float-text">Enter Name</label>
</div>
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1314
// Add 'e-input-btn-ripple' class to the icon element for achive ripple
effect when click on the icon.
</script>
}
<style>
.e-input-group-icon:before {
font-family: e-icons;
}
1315
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
1316
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1317
Validation
The TextBox supports three types of validation styles namely error , warning , and success .
These states are enabled by adding corresponding classes .e-error , .e-warning , or .e-
success to the input parent element.
razor
validation.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-input-group e-warning">
<input class="e-input" type="text" placeholder="Input with war
ning" />
</div>
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1318
var parentElement = this.parentNode;
if (parentElement.classList.contains('e-input-in-wrap')
) {
parentElement.parentNode.classList.add('e-input
-focus');
} else {
this.parentNode.classList.add('e-input-focus');
}
});
inputElement[i].addEventListener("blur", function () {
var parentElement = this.parentNode;
if (parentElement.classList.contains('e-input-in-wrap')
) {
parentElement.parentNode.classList.remove('e-in
put-focus');
} else {
this.parentNode.classList.remove('e-input-focus'
);
}
});
}
</script>
}
<style>
.e-input-group-icon:before {
font-family: e-icons;
}
1319
.e-input-group.e-small .e-input-group-icon.e-input-popup-date { /* csslint allow: adjoi
ning-classes */
font-size:14px;
}
1320
#input-container .e-float-input { /* csslint allow: adjoining-classes */
margin: 30px 0;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1321
How To
razor
rounded-corner.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div class="e-input-group e-corner">
<input class="e-input" type="text" placeholder="Enter Date" />
<span class="e-input-group-icon e-input-popup-date"></span>
</div>
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1322
if (parentElement.classList.contains('e-input-in-wrap')
) {
parentElement.parentNode.classList.add('e-input
-focus');
} else {
this.parentNode.classList.add('e-input-focus');
}
});
inputElement[i].addEventListener("blur", function () {
var parentElement = this.parentNode;
if (parentElement.classList.contains('e-input-in-wrap')
) {
parentElement.parentNode.classList.remove('e-in
put-focus');
} else {
this.parentNode.classList.remove('e-input-focus'
);
}
});
}
</script>
}
<style>
.e-input-group-icon:before {
font-family: e-icons;
}
1323
.e-input-group.e-small .e-input-group-icon.e-input-popup-date { /* csslint allow: adjoi
ning-classes */
font-size:14px;
}
1324
#input-container .e-float-input { /* csslint allow: adjoining-classes */
margin: 30px 0;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
disabled.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<input class="e-input" type="text" placeholder="Enter Name" dis
abled/>
1325
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
1326
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
read-only.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<input class="e-input" type="text" placeholder="Enter Name" val
ue="John" readonly/>
<div class="e-float-input">
<input type='text' required readonly value="John"/>
<span class="e-float-line"></span>
<label class="e-float-text e-label-top">Enter Name</lab
el>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
1327
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1328
Add TextBox programmatically
Create a TypeScript file and import the Input modules from ej2-inputs library as shown
below.
You can also add the icons on the input by passing buttons property value with the class
name e-input-group-icon as parameter to the createInput method.
razor
textbox.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div id="input-container">
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1329
// Add 'e-input-btn-ripple' class to the icon element for achive ripple
effect when click on the icon.
</script>
}
<style>
.e-input-group .e-input-group-icon.e-input-popup-date { /* csslint allow: adjoining-cla
sses */
font-size:16px;
}
.e-input-group-icon:before {
font-family: e-icons;
}
1330
.e-input-group-icon.e-input-date:before { /* csslint allow: adjoining-classes */
content: "" ;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1331
The Floating Label TextBox floats label above the TextBox after focusing, or entering a value
in the TextBox.
Type Description
The floating label will float above the input after focusing, or entering a value in
Auto
the input.
Always The floating label will always float above the input.
Never By default, never float the label in the input when the placeholder is available.
Create a TypeScript file and import the Input modules from ej2-inputs library as shown
below.
Pass the HTML Input element and floatLabelType property as Auto to the createInput
method.
Set the placeholder value to the input element via element attribute or pass the
parameter to the createInput method.
The watermark label will be updated based on the specified placeholder value of the
Floating Label TextBox .
You can add the icons on the input by passing buttons property value with the class
name e-input-group-icon as parameter to the createInput method.
razor
floating-label.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div id="input-container">
<h4> FloatLabelType as Auto </h4>
</div>
<div id="input-container-01">
<h4> FloatLabelType as Always </h4>
</div>
<div id="input-container-02">
<h4> FloatLabelType as Never </h4>
</div>
<div id="input-container-03">
1332
<h4> Float label input with icons </h4>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
var inputObj;
</script>
}
<style>
.e-input-group-icon:before {
font-family: e-icons;
}
1333
.e-input-group .e-input-group-icon.e-input-popup-date { /* csslint allow: adjoining-cla
sses */
font-size:16px;
}
1334
#input-container-03 .e-float-input { /* csslint allow: adjoining-classes */
margin: 30px 0;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
validation-state.cs
1335
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="control_wrapper accordion-control-section">
<div className="e-float-input e-input-group e-success">
<input type='text' required />
<span className="e-float-line"></span>
<label className="e-float-text">Success</label>
</div>
<div className="e-float-input e-input-group e-warning">
<input type='text' required />
<span className="e-float-line"></span>
<label className="e-float-text">Warning</label>
</div>
</div>
</div>
}
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when
focus on the input field.
1336
} else {
this.parentNode.classList.remove('e-input-focus'
);
}
});
}
</script>
}
<style>
.e-float-input.e-success label.e-float-text{ /* csslint allow: adjoining-classes */
color: #22b24b;
}
.e-float-input.e-success input:focus ~ label.e-float-text{ /* csslint allow: adjoinin
g-classes */
color: #22b24b;
}
.e-float-input.e-success input:valid ~ label.e-float-text { /* csslint allow: adjoini
ng-classes */
color: #22b24b;
}
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#input-container {
width: 240px;
margin: 0 auto;
padding: 20px 0px;
}
.e-input-group-icon:before {
1337
font-family: e-icons;
}
content: "";
}
content: '\e7ba';
}
content: "" ;
}
1338
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
text-color.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control-section">
<div class="wrap">
<div className="e-input-group">
<input className="e-input" id="numericOnly" type="text" placeholder="Enter
numeric values" onkeyup="onKeyup(this)" />
</div>
<div class="e-float-input e-input-group">
<input type="text" onkeyup="onKeyup(this)" required/>
<span class="e-float-line"></span>
<label class="e-float-text">Enter numeric values</label>
</div>
</div>
</div>
1339
}
@section Script{
<script>
ej.base.enableRipple(true);
// Add 'e-input-focus' class to the input for achive ripple effect when focus on th
e input field.
<style>
.e-input-group.e-error input.e-input { /* csslint allow: adjoining-classes */
color: #f44336;
}
1340
color: #f44336;
}
#container {
visibility: hidden;
}
.wrap {
box-sizing: border-box;
margin: 0 auto;
padding: 20px 10px;
width: 340px;
}
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#input-container {
width: 240px;
margin: 0 auto;
padding: 20px 0px;
}
.e-input-group-icon:before {
font-family: e-icons;
}
1341
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class TextboxController : Controller
{
1342
// GET: //
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1343
Overview
TimePicker is an intuitive interface control which provides an options to select a time value from
popup list or to set a desired time value. test
Key Features
The TimePicker provides the following features.
Time Range
Globalization
Time Format
Strict Mode
Accessibility
1344
Getting Started
This section briefly explains about how to include a simple TimePicker component in your
ASP.NET MVC application. You can refer ASP.NET MVC Getting Started documentation page
for introduction part of the system requirements and configure the common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include a license key in your projects. Please refer to this link
to know about registering Syncfusion license key in your ASP.NET MVC application to use
our components.
razor
@Html.EJS().TimePicker("timepicker").Render();
Running the above code will display the basic TimePicker on the browser.
razor
daterange.cs
@Html.EJS().TimePicker("timepicker").Value(ViewBag.value).Min(ViewBag.minVal).Max(ViewB
ag.maxVal).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
1345
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
The following example demonstrates the TimePicker component in 24 hours format with 60
minutes interval. The time interval is set to 60 minutes by using the step property..
razor
format.cs
@Html.EJS().TimePicker("timepicker").Value(ViewBag.value).Format("HH:mm").Step("60").Re
nder()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
1346
ViewBag.value = DateTime.Now;
return View();
}
}
}
1347
Time Range
TimePicker provides an option to select a time value within a specified range by using the min
and max properties. The min value should always be lesser than the max value. Otherwise, only
the min value will be considered. If the value is invalid or out of range, the value sets to null
with an error class ( .e-error ) added to textbox to indicate that the entered time value is invalid.
The value property depends on the min/max with respect to strictMode property.
The following example allows you to select a time value within a range of 9:00 AM to 11:30
AM .
razor
timerange.cs
@Html.EJS().TimePicker("timepicker").Value(ViewBag.value).Min(ViewBag.minVal).Max(ViewB
ag.maxVal).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.
com/fwlink/?LinkID=397860
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
// GET: /<controller>/
public IActionResult DefaultFunctionalities()
{
ViewBag.minVal= new DateTime(2017,08,03, 09,00,00);
ViewBag.maxVal = new DateTime(2017,08,03, 11,30,00);
ViewBag.value = new DateTime(2017,08,03, 11,00,00);
return View();
}
}
}
If the value of min or max property is changed through code behind you have to update
the value property to set within the range.
1348
Globalization
Globalization is the combination of internalization and localization. You can adapt the component
to various languages by parsing and formatting the date or number internationalization , and
also add culture specific customization and translation to the text localization .
By default, TimePicker time format and meridian names are specific to the American English
culture. It utilizes the Essential JavaScript 2 Internationalization package to parse and
format the date object based on the culture by using the official UNICODE CLDR JSON data. It
provides the loadCldr method to load culture specific CLDR JSON data.
To go with the different culture other than English , follow the below steps.
Install the CLDR-Data package by using the below command (it installs the CLDR JSON
data). To know more about CLDR-Data refer the CLDR-Data link.
Once the package installed, you can find the culture specific JSON data under the location
\node_modules\cldr-data .
Now use the loadCldr method to load the culture specific CLDR JSON data.
In ASP.NET MVC refer the culture files directly from \node_modules\cldr-data location. But in
ASP.NET Core, the static file contents are should present under wwwroot folder. For this,
manually copy the CLDR-Data from the node_modules folder and place inside the wwwroot
folder and refer from the \wwwroot\cldr-data location as like the below code examples.
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../wwwroot/
cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
1349
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node_mod
ules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
Before changing to a culture other than English , ensure that locale text for the concerned
culture is loaded through load method of L10n class.
razor
@Html.EJS().TimePicker("timepicker").Placeholder("Select Time").Locale("de").Render()
<script>
document.addEventListener('DOMContentLoaded', function () {
timepicker = document.getElementById('timepicker').ej2_instances[0];
var L10n = ej.base.L10n;
1350
L10n.load({
'de': {
'timepicker': { placeholder: 'Wählen Sie Zeit' }
}
});
loadCultureFiles("de");
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
Right-To-Left
The TimePicker supports RTL (right-to-left) functionality for languages like Arabic and Hebrew to
displays the text in the right-to-left direction. Use enableRtl property to set the RTL direction.
The following code example demonstrates the TimePicker component in Arabic culture. It also
explains how to set localized text to the placeholder using L10n.load method.
The following example demonstrates TimePicker in Arabic culture with right-to-left direction.
razor
@Html.EJS().TimePicker("timepicker").EnableRtl(true).Placeholder("Select a time").Rende
1351
r()
<script>
document.addEventListener('DOMContentLoaded', function () {
timepicker = document.getElementById('timepicker').ej2_instances[0];
var L10n = ej.base.L10n;
L10n.load({
'ar': {
'timepicker': { placeholder: '} 'ﺣﺪد اﻟﻮﻗﺖ
}
});
loadCultureFiles("ar");
timepicker.locale = "ar";
});
function loadCultureFiles(name) {
var files = ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json'];
if (name === 'ar') {
files.push('numberingSystems.json');
}
var loader = ej.base.loadCldr;
var loadCulture = function (prop) {
var val, ajax;
if (name === 'ar' && prop === files.length - 1) {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/supplemental/' + files[prop], 'GET', false);
} else {
ajax = new ej.base.Ajax(location.origin + location.pathname + '/../node
_modules/cldr-data/main/' + name + '/' + files[prop], 'GET', false);
}
ajax.onSuccess = function (value) {
val = value;
};
ajax.send();
loader(JSON.parse(val));
};
for (var prop = 0; prop < files.length; prop++) {
loadCulture(prop);
}
}
</script>
1352
Strict mode
The strictMode is an act that allows you to enter only valid time value within the specified
min/max range in the textbox. If the time value is invalid, the component value sets to the
previous value. If the time value is out of range, the component sets the time value to min/max
value.
The following example demonstrates the TimePicker in strictMode with min/max range of
10:00 AM to 4:00 PM . It allows you to enter only valid time within the specified range. If you
enter the out-of-range value like 8:00 PM , the value sets to the max time 4:00 PM as the value
8:00 PM is greater than max value of 4:00 PM . If you enter invalid time value like 9:00 tt ,
the value sets to the previous value.
razor
strictmode.cs
@Html.EJS().TimePicker("timepicker").Value(ViewBag.value).Min(ViewBag.minVal).Max(ViewB
ag.maxVal).StrictMode(true).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
public IActionResult DefaultFunctionalities()
{
ViewBag.minVal= new DateTime(2017,08,03, 10,00,00);
ViewBag.maxVal = new DateTime(2017,08,03, 04,00,00);
ViewBag.value = new DateTime(2017,08,03, 03,00,00);
return View();
}
}
}
By default, the value of strictMode is false , If the value is invalid or out-of-range, the
component highlights with error class (.e-error) to indicate that value is invalid or out-of-range.
1353
If you are entering the invalid or out-of-range value, then the component gets highlighted with
error class to indicate the value is invalid or out-of-range.
razor
normalmode.cs
@Html.EJS().TimePicker("timepicker").Value(ViewBag.value).Min(ViewBag.minVal).Max(ViewB
ag.maxVal).StrictMode(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
public IActionResult DefaultFunctionalities()
{
ViewBag.minVal= new DateTime(2017,08,03, 10,00,00);
ViewBag.maxVal = new DateTime(2017,08,03, 4,00,00);
ViewBag.value = new DateTime(2017,08,03, 3,00,00);
return View();
}
}
}
If the value of min or max property is changed through code behind, update the value
property to set within the range.
1354
Accessibility
The web accessibility makes web applications and its content more accessible to people with
disabilities without any barriers. It especially it tracks the dynamic value changes and DOM
changes.
The TimePicker component has covered the WAI-ARIA specifications with the following list of
WAI-ARIA attributes: aria-haspopup , aria-selected , aria-disabled , aria-
activedescendant , aria-expanded , aria-owns , and aria-autocomplete .
Here in TimePicker, the combobox plays the role of input element, and the listbox plays the
role of popup element.
Aria-haspopup: Provides the information about whether this element display a pop-up
window or not.
Aria-owns: Attribute that creates a parent/child relationship between two DOM element in
the accessibility layer.
Aria-activedescendent: Attribute that helps in managing the current active child of the
TimePicker component.
Role: Attribute that gives assistive technology information for handling each element in a
widget.
Keyboard Interaction
Keyboard accessibility is one of the most important aspects of web accessibility. Disabled people
like blind and those who have motor disabilities or birth defects use keyboard shortcuts more
than the mouse.
The TimePicker component has built-in keyboard accessibility support by following the WAI-ARIA
practices.
It supports the following list of shortcut keys to interact with the TimePicker control.
Press To do this
1355
Upper Arrow Navigate and select the previous item.
Right Arrow Move the cursor towards arrow key pressed direction.
Enter Select the currently focused item and close the popup.
In the below sample use the alt+t keys to focus the TimePicker component.
razor
<script>
document.onkeyup = function (e) {
var timepicker = document.getElementById('timepicker').ej2_instances[0];
if (e.altKey && e.keyCode === 84 /* t */) {
// press alt+t to focus the control by calling public method.
timepicker.focusIn(e);
}
};
</script>
@Html.EJS().TimePicker("timepicker").Placeholder("Select a time").Render()
1356
How To
The following section explains how to customize the TimePicker component in various aspects.
CSS customization
TimePicker allows you to customize the textbox and popup list appearance to suit your
application by using cssClass property.
The below sample demonstrates customization of text appearance in a textbox, popup button,
and popup list along with hover and active state by using e-custom-style class. Following is the
list of available classes used to customize the entire TimePicker component.
razor
@Html.EJS().TimePicker("timepicker").CssClass("e-custom-style").Placeholder("Select a t
ime").Render()
<style>
1357
/*customize the floating label and popup button text color*/
.e-time-wrapper.e-custom-style .e-float-text.e-label-bottom, /* csslint allow: adjoinin
g-classes */
.e-time-wrapper.e-custom-style .e-input-group-icon.e-time-icon.e-icons { /* csslint all
ow: adjoining-classes */
color: blue;
}
</style>
1358
To achieve client side validation in a TimePicker component, use Essential JavaScript 2
FormValidator. It provides an option to customize feedback error messages to the corresponding
fields for taking action and resolving the issue.
In the following example, the required field validation is implemented by mapping the name
attribute value to the rules property. It validates the TimePicker component and displays the
validation message when the textbox value is empty during form post back or focus out.
razor
validation.cs
<script>
document.addEventListener('DOMContentLoaded', function () {
var options = {
rules: {
//must specify the name attribute value in rules section
'formTest': { required: true }
},
customPlacement: (inputElement, errorElement) => {
//to place the error message in custom position
//inputElement - target element where the error text will be ap
pended
//errorElement - error text which will be displayed.
inputElement.parentElement.parentElement.appendChild(errorEleme
nt);
}
};
var formObject = new ej.inputs.FormValidator('#form-element', options);
});
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
1359
namespace EJ2CoreSampleBrowser.Controllers
{
public partial class HomeController: Controller
{
1360
Overview
The toast is a small container, in which user can show a single or multiple informative lines with
actions.
Key features
1. Position: Enables to position the toast anywhere on the screen. It has a predefined set of
positions and custom inputs for position based on the target.
2. Autohide and TimeOut: Toast can be expired based on the timeOut property; it hides toast
automatically when reaches specific time without user interaction.
3. Multi Toast: Toasts can support to display multiple toasts with various time delay.
4. Progress Bar: Supports to visually indicate time lapse when the toast expires.
5. Action Buttons: Supports to add buttons in the toast for archiving any actions within the
toast.
6. Template: User customized element can be defined for the toast using the template
property.
1361
Getting Started
This section briefly explains about how to render Toast component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
razor
HomeController.cs
1362
Configuring Options
This section explains the steps required to customize the appearance of the toast using built-in
APIs.
The Title or Content property can be given as HTML element/element ID to a string that can
be displayed as a toast.
razor
HomeController.cs
1363
Close button
By default, the showCloseButton is not enabled. You can enable it by setting the true value.
Before expiring the toast, you can use this button to close or destroy toasts manually.
Progress bar
By default, the showProgressBar is not enabled. If it is enabled, it can visually indicate how long
to get toast expires. Based on the timeOut property, progress bar will appear.
Newest on top
By default, the newly created toasts will append next with existing toasts. You can change the
sequence like inserting before the toast by enabling the newestOnTop .
Here, The following sample demonstrates the combination of the target , showCloseButton ,
showProgressBar , and newestOnTop properties in toast.
razor
HomeController.cs
@Html.EJS().Toast("element").Title("File Downloading").Position(p=>p.X("Center")).Conte
nt("<div class='progress'><span style='width: 80%'></span></div>").ShowCloseButton(true
).Target("#toast_target").NewestOnTop(true).ShowProgressBar(true).Render()
@Html.EJS().Button("button").Content("Show Toast").CssClass("e-btn").Re
nder()
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_insta
nces[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("button").addEventListener('click', functio
n () {
var toastObj = document.getElementById('element').ej2_instances
[0];
toastObj.show();
});
</script>
<style>
#loader {
color: #008cff;
height: 40px;
1364
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
.e-toast-message {
width: 100%;
}
.progress {
height: 20px;
position: relative;
margin: 20px 0 20px 0;
background: #555;
-moz-border-radius: 25px;
-webkit-border-radius: 25px;
border-radius: 25px;
box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}
.progress span {
background-color: #f0a3a3;
background-image: -webkit-gradient(linear, left top, left b
ottom, color-stop(0, #f0a3a3), color-stop(1, #f42323));
display: block;
height: 100%;
border-radius: 10px;
width: 50%;
position: relative;
overflow: hidden;
}
.progress span::after {
background-image: -webkit-gradient(linear, 0 0, 100% 10
0%, color-stop(.25, rgba(255, 255, 255, .2)), color-stop(.25, transparent), color-stop(
.5, transparent), color-stop(.5, rgba(255, 255, 255, .2)), color-stop(.75, rgba(255, 25
5, 255, .2)), color-stop(.75, transparent), to(transparent));
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-size: 50px 50px;
-webkit-animation: moveAnimate 2s linear infinite;
overflow: hidden;
}
1365
@@-webkit-keyframes moveAnimate {
0% {
background-position: 0 0;
}
100% {
background-position: 50px 50px;
}
}
</style>
By default, the toast can be rendered with '300px' width with 'auto' height.
In mobile devices, the default width of the toast gets '100%' width of the page. When you
set toast width as '100%', the toast occupies full width and will be displayed at the top or
bottom based on the position Y property.
Both the width and height properties allow setting pixels/numbers/percentage. The number value
is considered as pixels.
razor
HomeController.cs
1366
<td>
<div style='padding:25px 0 0 0;'>
@Html.EJS().RadioButton("bottomAlign").Label("Botto
m").Name("toast").Value("Global").Change("checkboxChange1").Checked(true).Render()
</div>
</td>
</tr>
<tr>
<td>
<div style='padding:25px 0 0 0;'>
@Html.EJS().CheckBox("fullWidth").Change("onChange"
).Label("100% Width").Render()
</div>
</td>
</tr>
</table>
</div>
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn"
).Render()
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_insta
nces[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("show_toast").addEventListener('click', fun
ction () {
var toastObj = document.getElementById('element').ej2_instances[
0];
toastObj.show();
});
var timeDelay = 500;
function checkboxChange(e) {
var toastObj = document.getElementById('element').ej2_instances[
0];
if (e.event.target.checked) {
toastObj.position.Y = "Top";
toastObj.hide();
toastShow(timeDelay);
}
}
function checkboxChange1(e) {
var toastObj = document.getElementById('element').ej2_instances[
0];
if (e.event.target.checked) {
toastObj.position.Y = "Bottom";
toastObj.hide();
1367
toastShow(timeDelay);
}
}
function toastShow(timeOutDelay) {
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_i
nstances[0];
toastObj.show();
}, timeOutDelay);
}
function onChange(e) {
var toastObj = document.getElementById('element').ej2_instances[
0];
if (e.checked) {
toastObj.hide();
toastObj.width = "100%";
toastObj.title = "";
toastObj.content = "<div class='e-custom'>Take a look at ou
r next generation <b>Javascript</b> <a href='https://ej2.syncfusion.com/home/index.html
' target='_blank'>LEARN MORE</a></div>";
toastShow(timeDelay);
} else {
toastObj.hide();
toastObj.width = 300;
toastObj.title = 'Matt sent you a friend request',
toastObj.content = 'You have a new friend request yet t
o accept',
toastShow(timeDelay);
}
}
</script>
1368
Positions
The toast position can be updated based on predefined positions or customizable positions. The
predefined position combinations are updated in the X and Y position properties.
Predefined
X Positions
Left
Center
Right
Y Positions
Top
Bottom
In multiple toast display, the new toast position will not be updated on dynamic change of
property values until the old toast messages removed. The toast occupies full width when
you set the width to '100%', so the X positions will not affect the changes when the width is
'100%'.
Custom
Custom X and Y positions can be given as pixels/numbers/percentage. The number value is
considered as pixels based on the top and left values updated in the toast.
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.DropDowns
@using EJ2MVCSampleBrowser.Models
1369
<td>
<div style="padding:25px 0 0 0;">
@Html.EJS().RadioButton("dropdownRadio"
).Label("Position").Name("toastPos").Value("Position").Change("checkboxChange2").Checke
d(true).Render()
</div>
</td>
<td>
<div style="padding:25px 0 0 0;">
@Html.EJS().RadioButton("customRedio").
Label("Custom").Name("toastPos").Value("Custom").Change("checkboxChange3").Render()
</div>
</td>
</tr>
<tr>
<td id="dropdownChoose" colspan="2">
<div id="dropdown" style="padding-top:25px;"
>
@Html.EJS().DropDownList("position").Pl
aceholder("Select a position").PopupHeight("200px").Index(5).DataSource(
(IEnumerable<Pos>)ViewBag.data).Change("valueChange").Fields(new Dr
opDownListFieldSettings { Text = "Value", Value = "Id" }).Render()
</div>
</td>
</tr>
<tr>
<td colspan="2" id="customChoose" style="displa
y: none">
<form id="formId" class="form-horizontal">
<div class="e-row">
<div class="e-float-input">
<input class="e-input" id="xPos"
name="Digits" value="50" digits="true" data-digits-message="Please enter digits only."
required="">
<span class="e-float-line"></sp
an>
<label class="e-float-text" for=
"Digits">X Position</label>
</div>
</div>
<div class="e-row">
<div class="e-float-input">
<input class="e-input" id="yPos"
name="Digits" value="50" digits="true" data-digits-message="Please enter digits only."
required="">
<span class="e-float-line"></sp
an>
<label class="e-float-text" for=
"Digits">Y Position</label>
1370
</div>
</div>
</form>
</td>
</tr>
<tr>
<td>
<div style="padding:25px 0 0 0;">
@Html.EJS().RadioButton("radio1").Label(
"Target").Name("toast").Value("Target").Change("checkboxChange").Render()
</div>
</td>
<td>
<div style="padding:25px 0 0 0;">
@Html.EJS().RadioButton("radio2").Label(
"Global").Name("toast").Value("Global").Change("checkboxChange1").Checked(true).Render(
)
</div>
</td>
</tr>
</tbody>
</table>
<div id="toast_btn" style="padding-top: 25px">
<button class="e-btn e-control" id="show_Toast" style="
margin-right: 15px"> Show Toast </button>
<button class="e-btn e-control" id="hideTosat"> Hide Al
l </button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('toast_pos').ej2_ins
tances[0];
toastObj.target = document.body;
toastObj.show();
}, 200);
function toastShow() {
setTimeout(
() => {
var toastObj = document.getElementById('toast_pos').ej2
_instances[0];
toastObj.show();
}, 200);
}
1371
btnEle.onclick = function () {
if (customFlag) {
setcustomPosValue();
}
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
toastObj.show();
};
document.getElementById('hideTosat').onclick = function () {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
toastObj.hide('All');
};
function checkboxChange(e) {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
if (this.checked) {
toastObj.hide('All');
toastObj.target = document.getElementById('toast_pos_target'
);
toastShow(1000);
}
}
function checkboxChange1(e) {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
if (this.checked) {
toastObj.hide('All');
toastObj.target = document.body;
toastShow(1000);
}
}
function checkboxChange2(e) {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
1372
var listObj = document.getElementById('position').ej2_instances[
0];
if (this.checked) {
toastObj.hide('All');
document.getElementById('dropdownChoose').style.display = '
table-cell';
document.getElementById('customChoose').style.display = 'no
ne';
setToastPosValue(listObj.value.toString()); customFlag = fa
lse; toastShow(1000);
}
}
function checkboxChange3(e) {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
if (this.checked) {
toastObj.hide('All');
document.getElementById('dropdownChoose').style.display = '
none';
document.getElementById('customChoose').style.display = 'ta
ble-cell';
setcustomPosValue(); customFlag = true; toastShow(1000);
}
}
1373
toastObj.position.X = 'Right'; toastObj.position.Y = 'T
op'; break;
case 'topcenter':
toastObj.position.X = 'Center'; toastObj.position.Y = '
Top'; break;
case 'topfullwidth':
toastObj.width = '100%'; toastObj.position.X = 'Center'
; toastObj.position.Y = 'Top'; break;
case 'bottomleft':
toastObj.position.X = 'Left'; toastObj.position.Y = 'Bo
ttom'; break;
case 'bottomright':
toastObj.position.X = 'Right'; toastObj.position.Y = 'B
ottom'; break;
case 'bottomcenter':
toastObj.position.X = 'Center'; toastObj.position.Y = '
Bottom'; break;
case 'bottomfullwidth':
toastObj.width = '100%'; toastObj.position.X = 'Center'
; toastObj.position.Y = 'Bottom'; break;
}
}
function valueChange(e) {
var toastObj = document.getElementById('toast_pos').ej2_instanc
es[0];
toastObj.hide('All'); setToastPosValue(e.value.toString()); toa
stShow(1000);
}
</script>
<style>
.toast-pos-section #toast_pos_property {
height: 500px;
border: none;
margin: auto;
}
#toast_pos_property td {
width: 50%;
}
.e-toast-icon.e-laura.e-icons {
border-radius: 50%;
background-image: url('./../css/Toast/laura.png');
background-repeat: no-repeat;
background-size: cover;
height: 50px !important;
width: 100px !important;
background-size: 50px 50px;
1374
margin: 0;
}
1375
Action Buttons
You can include action buttons to the toast control by adding the buttons property. The
collection of Essential JS 2 button models can be bound to the model property inside the
buttons property. You can also include the click event callback function for each button.
razor
HomeController.cs
<div class="control-section">
@Html.EJS().Toast("element").Position(p => p.X("Right").Y("Bottom")).Title("Anjolie
Stokes").Content("<p><img src = './laura.png'></p>").Width("230").Height("250").Button
s(ViewBag.ToastButtons).Render()
<div id='templateToast' style="display: none;color:red"> System affected by virus !
!! </div>
<div class="row">
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn").Render
()
</div>
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("show_toast").addEventListener('click', function () {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.show();
});
function btnClick(e) {
var toastEle = ej.base.closest(e.target, '.e-toast');
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.hide(toastEle);
}
</script>
using Syncfusion.EJ2.Notifications;
1376
buttons.Add(new ToastButtonModelProps() { Model = new DefaultButtonModel() { conten
t = "reply" } });
ViewBag.ToastButtons = buttons;
return View();
}
public class DefaultButtonModel
{
public string content { get; set; }
}
1377
Time out
The toast can be expired based on the timeOut property. The toast can live till the time out
reaches without user interaction, a time out value is considered as a millisecond.
The extendedTimeOut property determines how long the toast should be displayed after a
user hovers over it.
You can terminate the process by using the showCloseButton property for destroying the
toast at any time.
razor
HomeController.cs
<div class="control-section">
<div class="e-float-input"><input class="e-input" id="toast_input_index" required=""
value="0"><span class="e-float-line"></span><label class="e-float-text">Enter timeOut<
/label></div>
@Html.EJS().Toast("element").Position(p => p.X("Right").Y("Bottom")).Title("Anjolie
Stokes").Content("<p><img src = './laura.png'></p>").Width("230").Height("250").Button
s(ViewBag.ToastButtons).Render()
<div class="row">
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn").Render
()
</div>
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("show_toast").addEventListener('click', function () {
var toastObj = document.getElementById('element').ej2_instances[0];
var value = parseInt(document.getElementById('toast_input_index').value)
toastObj.show({ timeOut: value });
});
</script>
using Syncfusion.EJ2.Notifications;
1378
public ActionResult Toast()
{
List<ToastButtonModelProps> buttons = new List<ToastButtonModelProps>() { };
buttons.Add(new ToastButtonModelProps() { Click= "btnClick", Model = new DefaultBu
ttonModel() { content = "Ignore" } });
buttons.Add(new ToastButtonModelProps() { Model = new DefaultButtonModel() { conten
t = "reply" } });
ViewBag.ToastButtons = buttons;
return View();
}
public class DefaultButtonModel
{
public string content { get; set; }
}
Static toast
You can prevent auto hiding in a toast as visible like static by setting zero ( 0 ) value in the
timeOut Property.
razor
HomeController.cs
<div class="control-section">
@Html.EJS().Toast("element").Title("Matt sent you a friend request").Content("You h
ave a new friend request yet to accept").TimeOut(0).ShowCloseButton(true).Position(p =>
p.X("Right")).Render()
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn").Render()
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("show_toast").addEventListener('click', function () {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.show();
});
</script>
1379
1380
Template
The Template property can be given as the HTML element ; this can be either a string or
query selector .
The HTML element tag can be given as a string for the Template property.
The Template property allows getting the template content using the query selector . Here, the
element 'ID' attribute is specified in the template.
template: "#Template"
razor
HomeController.cs
<div class="control-section">
<div id="template_toast">
@Html.EJS().Toast("element").TimeOut(120000).ExtendedTimeout(0).Position(p => p
.X("Right").Y("Bottom")).Render()
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn").Render
()
</div>
<br /><br />
<div id='result'></div>
</div>
</div>
<script id="template_toast_ele" type="text/x-template">
<div id='template_toast' style="display: none">
<div class="horizontal-align">
<div class='toast-content'>
<div class='toast-title'>
Weekend Alarm
</div>
<div class='toast-message'>
With traffic, its likely to take 45 minutes to get to jenny's 24th
Birthday Bash at Hillside Bar, 454 E.
Olive Way by 10:00PM
</div>
</div>
</div>
<img src="http://npmci.syncfusion.com/development/demos/src/toast/resource/map.
jpg" width="100%" height="70%">
1381
</div>
</script>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show({ template: document.getElementById('template_toast_ele').inn
erHTML });
}, 1000);
document.getElementById("show_toast").addEventListener('click', function () {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.show();
});
</script>
<style>
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#snooze,
#dismiss {
background-color: #fff;
}
.toast-template-section #reminder {
text-align: center;
margin: 15px;
}
#toast_custom .e-toast-template {
display: inline-flex;
}
#template_toast .toast-icons {
font-size: 35px;
height: auto;
margin: auto;
}
1382
#template_toast .toast-icons.e-alarm::before {
content: "\e702";
}
#template_toast .horizontal-align {
display: inline-flex;
flex-direction: row;
width: 100%;
}
#template_toast .horizontal-align,
#template_toast #snoozedropDown,
#template_toast .snooze,
#template_toast .snoozeBtn {
margin: 10px 0;
}
1383
Animations
The toast control supports custom animations for both shows and hide actions from the provided
animation option of the Animation library.
The default animation is given as FadeIn for showing the toast and FadeOut for hiding the
toast.
The following sample demonstrates some types of animations that suit toast. You can check all
the animation effects here.
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.DropDowns
@using EJ2MVCSampleBrowser.Models
<div class="control-section">
<div id="default" style="padding-bottom:75px;">
<div class='row'>
@Html.EJS().Button("show_toast").Content("Show Toast").CssClass("e-btn").Re
nder()
</div>
<div class='row'>
<div class="col-xs-6 col-sm-6 col-lg-6 col-md-6">
<label> Show Animation </label>
</div>
<div class="col-xs-6 col-sm-6 col-lg-6 col-md-6">
@Html.EJS().DropDownList("showAnimation").Placeholder("Select a animate
type").PopupHeight("200px").Index(0).DataSource(
(IEnumerable<Pos>)ViewBag.data).Change("valueChange").Fields(new Dr
opDownListFieldSettings { Text = "Value", Value = "Id" }).Render()
</div>
</div>
<div class='row'>
<div class="col-xs-6 col-sm-6 col-lg-6 col-md-6">
<label> Hide Animation </label>
</div>
<div class="col-xs-6 col-sm-6 col-lg-6 col-md-6">
@Html.EJS().DropDownList("hideAnimation").Placeholder("Select a animate
type").PopupHeight("200px").Index(0).DataSource(
(IEnumerable<Pos>)ViewBag.data).Change("valueChange1").Fields(new D
ropDownListFieldSettings { Text = "Value", Value = "Id" }).Render()
</div>
</div>
1384
@Html.EJS().Toast("element").Title("Matt sent you a friend request").Content("Y
ou have a new friend request yet to accept").Position(p => p.X("Right").Y("Bottom")).Re
nder()
</div>
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
document.getElementById("show_toast").addEventListener('click', function () {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.show();
});
function valueChange(e) {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.animation.show.effect = e.value;
}
function valueChange1(e) {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.animation.hide.effect = e.value;
}
</script>
<style>
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
.row {
margin: 15px;
}
</style>
1385
public string Value { get; set; }
public string Id { get; set; }
public List<Pos> Positions()
{
List<Pos> position = new List<Pos>();
position.Add(new Pos { Id= "FadeIn", Value = "Fade In" });
position.Add(new Pos { Id= "FadeZoomIn", Value = "Fade Zoom In"});
position.Add(new Pos { Id= "FadeZoomOut", Value = "Fade Zoom Out" });
position.Add(new Pos { Id= "FlipLeftDownIn", Value = "Flip Left Down In"
});
position.Add(new Pos { Id= "FlipLeftDownOut", Value = "Flip Left Down O
ut" });
position.Add(new Pos { Id= "FlipLeftUpIn", Value = "Flip Left Up In" })
;
position.Add(new Pos { Id= "FlipLeftUpOut", Value = "Flip Left Up Out"
});
position.Add(new Pos { Id= "FlipRightDownIn", Value = "Flip Right Down
In" });
position.Add(new Pos { Id = "FlipRightUpIn", Value = "Flip Right Up In"
});
position.Add(new Pos { Id = "FlipRightUpOut", Value = "Flip Right Up Ou
t" });
position.Add(new Pos { Id = "SlideBottomIn", Value = "Slide Bottom In"
});
position.Add(new Pos { Id = "SlideBottomOut", Value = "Slide Bottom Out"
});
position.Add(new Pos { Id = "SlideLeftIn", Value = "Slide Left In" });
position.Add(new Pos { Id = "SlideLeftOut", Value = "Slide Left Out" })
;
position.Add(new Pos { Id = "SlideRightIn", Value = "Slide Right In" })
;
position.Add(new Pos { Id = "SlideRightOut", Value = "Slide Right Out"
});
position.Add(new Pos { Id = "SlideTopIn", Value = "Slide Top In" });
position.Add(new Pos { Id = "SlideTopOut", Value = "Slide Top Out" });
position.Add(new Pos { Id = "ZoomIn", Value = "Zoom In" });
position.Add(new Pos { Id = "ZoomOut", Value = "Zoom Out" });
return position;
}
}
1386
Accessibility
The toast component has been designed with WAI-ARIA specifications in mind by applying the
prompt WAI-ARIA roles, states, and properties with the keyboard support. It helps users who use
assistive WAI-ARIA accessibility support, which is achieved using attributes.
The toast component implements the keyboard navigation support by using the following WAI-
ARIA practices and is tested in major screen readers.
ARIA attributes
Class Description
alert:
role Identifies the element as a container when alert content will be added or
updated.
razor
HomeController.cs
<div class="control-section">
@Html.EJS().Toast("element").Title("Matt sent you a friend request").Content("You
have a new friend request yet to accept").Render()
</div>
<script type="text/javascript">
setTimeout(
() => {
var toastObj = document.getElementById('element').ej2_instances[0];
toastObj.target = document.body;
toastObj.show();
}, 1000);
</script>
1387
Overview
The Tooltip component displays a pop-up containing an information or a message when you
hover, click, focus, or touch an element. The information displayed in the Tooltip can include
simple text, images, hyperlinks, or custom templates. In mobile devices, to display the Tooltip,
you need to tap and hold the target elements.
Key features
Tooltip
1388
Getting Started
This section briefly explains about how to render Tooltip component in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part of the system requirements and configure the common specifications.
Starting with v16.2.0.x , if you reference Syncfusion assemblies from trial setup or from
the NuGet feed, you also have to include a license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP .NET MVC application to
use our components.
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@Html.EJS().Tooltip("Tooltip").Content("Lets go green & Save Earth !!!").ContentTemplat
e(@<span id='target'>Show Tooltip</span>).Render()
return View();
}
1389
In the above sample code, #target is the id of the element in a page to which the
Tooltip is initialized.
Refer to the following code example to create a Tooltip on multiple targets within a container.
razor
HomeController.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@Html.EJS().Tooltip("Tooltip").Target(".e-info").Position(Syncfusion.EJ2.Popups.Positio
n.RightCenter).ContentTemplate(@<form id="details" role="form">
<table>
<tr>
<td class="info"> User Name:</td>
<td> <input type="text" class="e-info" name="firstname"
title="Please enter your name"> </td>
</tr>
<tr>
<td class="info"> Email Address:</td>
<td> <input type="text" class="e-info" name="email" tit
le="Enter a valid email address"></td>
</tr>
<tr>
<td class="info"> Password:</td>
<td> <input type="password" class="e-info" name="passwo
rd" title="Be at least 8 characters length"></td>
</tr>
<tr>
<td class="info"> Confirm Password:</td>
<td> <input type="password" class="e-info" name="Cpwd"
title="Re-enter your password"></td>
1390
</tr>
</table>
<input id="sample" type="submit" value="Submit">
<input id="clear" type="reset" value="Reset">
</form>).Render()
<style>
#container {
visibility: hidden;
}
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#details .info {
font-weight: bold;
}
</style>
return View();
}
In the above sample, #details refers to the container's id, and the target .e-info refers
to the target elements available within that container.
1391
Setting Dimension
The following sample explains how to set dimensions for the Tooltip.
razor
height-width.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").Width("150px").Height("40px").Content("Tooltip wit
h specific width and height").ContentTemplate(@<div>
<div>
<span id='target'>Show Tooltip</span>
</div>
</div>).Render()
}
<style>
#tooltip {
position: absolute;
left: calc( 50% - 60px);
top: 38%;
}
</style>
Scroll mode
When height is specified with a certain pixel value and the Tooltip content overflows, the
scrolling mode gets enabled.
razor
1392
scroll-mode.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltipContent").Width("300px").Height("60px").Target("#target"
).Content("Environmentally friendly</b> or environment-friendly, (also referred to as e
co-friendly, nature-friendly, and green) are marketing and sustainability terms referri
ng to goods and services, laws, guidelines and policies that inflict reduced, minimal,
or no harm upon ecosystems or the environment.").IsSticky(true).ContentTemplate(@<div>
<div id='container'>
<p>
A green home is a type of house designed to be
<a id="target">
<u>environmentally friendly</u>
</a> and sustainable. And also focuses on the efficient use of "energy,
water, and building materials." As green homes
have become more prevalent we have also seen the emergence of green aff
ordable housing.
</p>
</div>
</div>).Render()
}
The scrolling mode can best be seen when the sticky mode of the Tooltip is enabled. To
enable sticky mode, set the isSticky property to true.
1393
Content
A text or a piece of information assigned to the Tooltip's content property will be displayed as
the main text stream of the Tooltip. It can be a string or a template content. If the content
property is not provided with any specific value, then it takes the value assigned to the title
attribute of the target element on which the Tooltip was initialized. The content can also
dynamically be assigned to the Tooltip via AJAX.
Template content
Any text or image can be added to the Tooltip, by default. To customize the Tooltip layout or to
create your own visualized element on the Tooltip, template can be used.
Refer to the following code example to add formatted HTML content to the Tooltip.
razor
template.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltipContent").Content("<div><p><strong>Environmentally frie
ndly</strong> or <strong>environment-friendly</strong>, <i>(also referred to as eco-fri
endly, nature-friendly, and green)</i> are marketing and sustainability terms referring
to goods and services, laws, guidelines and policies that inflict reduced, minimal, or
no harm upon ecosystems or the environment.</p></div>").Target("#target").ContentTempl
ate(@<div>
<div id='container'>
<p>
A green home is a type of house designed to be
<a id="target">
<u>environmentally friendly</u>
</a> and sustainable. And also focuses on the efficient use of "energy,
water, and building materials." As green homes
have become more prevalent we have also seen the emergence of green aff
ordable housing.
</p>
</div>
</div>).Render()
}
1394
{
return View();
}
razor
ajaxcontent.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
<div id='container'>
<h4 class="list-header">National Sports</h4>
<!-- Tooltip element rendering for AjaxContent loading -->
@Html.EJS().Tooltip("Tooltip").Content("Loading...").Target("#countrylist [titl
e]").Position(Syncfusion.EJ2.Popups.Position.RightCenter).BeforeRender("onBeforeRender"
).ContentTemplate(@<div>
@Html.EJS().ListView("countrylist").Enable(true).DataSource((IEnumerable<ob
ject>)ViewBag.data).Fields(new ListViewFieldSettings { Text = "text", Tooltip = "id" })
.Render()
</div>).Render()
</div>
}
<script>
/**
* Process tooltip ajax content.
*/
function onBeforeRender(args) {
var _this = this;
this.content = 'Loading...';
this.dataBind();
var ajax = new ej.base.Ajax("@Url.Content("~/Scripts/tooltip/tooltipdata.js
on")", 'GET', true);
ajax.send().then(function (result) {
result = JSON.parse(result);
for (var i = 0; i < result.length; i++) {
if (result[i].Id === args.target.getAttribute('data-content')) {
_this.content = "<div class='contentWrap'><span class=" + result[i]
.Class + "></span><div class='def'>" + result[i].Sports + "</div></div>";
}
}
1395
_this.dataBind();
}, function (reason) {
_this.content = reason.message;
_this.dataBind();
});
}
</script>
<link href="../Content/tooltip/icons.css" rel="stylesheet" />
<style>
.contentWrap {
padding: 3px 0;
line-height: 16px;
}
.e-bigger [class^="sports-icon-"],
.e-bigger [class*=" sports-icon-"] {
font-size: 18px;
}
[class^="sports-icon-"],
[class*=" sports-icon-"] {
font-family: 'sportsicons';
speak: none;
font-size: 16px;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
padding-right: 6px;
vertical-align: middle;
}
.sports-icon-cricket:before {
content: "\e703";
}
.sports-icon-archery:before {
content: "\e705";
}
.sports-icon-table-tennis:before {
content: "\e702";
}
.sports-icon-baseball:before {
content: "\e706";
}
.sports-icon-hockey:before {
1396
content: "\e701";
}
.sports-icon-shooting:before {
content: "\e700";
}
.def {
float: right;
}
#countrylist {
border: 1px solid #dddddd;
border-radius: 3px;
max-width: 170px;
margin: 0 auto;
overflow: hidden;
}
.list-header {
text-align: center;
color: rgba(0, 0, 0, 0.54);
}
.list-header {
text-align: left;
}
}
</style>
1397
return View();
1398
Tooltip Positioning
Tooltips can be attached to 12 static locations around the target. On initializing the Tooltip, you
can set the position property with any one of the following values:
TopLeft
TopCenter
TopRight
BottomLeft
BottomCenter
BottomRight
LeftTop
LeftCenter
LeftBottom
RightTop
RightCenter
RightBottom
razor
tooltippositions.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
<div class="control-section">
@Html.EJS().Tooltip("Tooltip").Content("Tooltip content").Position(Syncfusion.E
J2.Popups.Position.TopCenter).ContentTemplate(@<div>
<div id='container'>
<div id="tooltip" title="Tooltip content">
<span>Show tooltip</span>
<select id="positions" class="form-control" onchange="onChange(this)">
<option value="TopLeft">Top Left</option>
<option value="TopCenter" selected="">Top Center</option>
<option value="TopRight">Top Right</option>
<option value="BottomLeft">Bottom Left</option>
<option value="BottomCenter">Bottom Center</option>
<option value="BottomRight">Bottom Right</option>
<option value="LeftTop">Left Top</option>
<option value="LeftCenter">Left Center</option>
<option value="LeftBottom">Left Bottom</option>
<option value="RightTop">Right Top</option>
<option value="RightCenter">Right Center</option>
1399
<option value="RightBottom">Right Bottom</option>
</select>
</div>
</div>
</div>).Render()
</div>
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 70px auto;
padding: 20px;
width: 200px;
}
/* csslint ignore:start */
.customtip.e-tooltip-wrap {
padding: 4px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-bottom {
height: 20px;
width: 12px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-top {
height: 20px;
width: 12px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-left {
height: 12px;
width: 20px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-right {
height: 12px;
width: 20px;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-bottom {
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 20px solid #616161;
}
1400
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-top {
border-bottom: 20px solid #616161;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-left {
border-bottom: 6px solid transparent;
border-right: 20px solid #616161;
border-top: 6px solid transparent;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-right {
border-bottom: 6px solid transparent;
border-left: 20px solid #616161;
border-top: 6px solid transparent;
}
</style>
<script>
var tooltip;
window.onload = function () {
tooltip = document.getElementById('Tooltip').ej2_instances[0];
}
function onChange(args) {
tooltip.position = args.value;
}
</script>
auto
start
1401
middle
end
The following code example illustrates how to set the pointer to the start position of the Tooltip.
razor
tippointer.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("Tooltip").Content("Tooltip content").TipPointerPosition(Syncfu
sion.EJ2.Popups.TipPointerPosition.Start).ContentTemplate(@<div>
<div id='target'>
<span>Show Tooltip</span>
</div>
</div>).Render()
}
<style>
#container {
visibility: hidden;
}
#loader {
color: #008cff;
height: 40px;
left: 45%;
position: absolute;
top: 45%;
width: 30%;
}
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 50px auto;
padding: 20px;
width: 250px;
}
</style>
1402
return View();
}
By default, tip pointers are auto adjusted so that the arrow does not point outside the target
element.
Dynamic positioning
The Tooltip and its tip pointer can be positioned dynamically based on the target's location. This
can be achieved by using the refresh method, which auto adjusts the Tooltip over the target.
razor
dynamicposition.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
<div class="control-section">
<!-- Tooltip element -->
@Html.EJS().Tooltip("targetContainer").Content("Drag me").Target("#demoSmart").
ContentTemplate(@<div id="demoSmart">
</div>).Render()
</div>
}
<script type="text/javascript">
var tooltip, ele;
window.onload = function () {
ele = document.getElementById('demoSmart');
tooltip = document.getElementById("targetContainer").ej2_instances[0];
////Initialize Draggable for tooltip element
var drag = new ej.base.Draggable(ele, {
clone: false,
dragArea: '#targetContainer',
drag: function (args) {
if (args.element.getAttribute('data-tooltip-id') === null) {
tooltip.open(args.element);
}
else {
tooltip.refresh(args.element);
}
},
dragStart: function (args) {
if (args.element.getAttribute('data-tooltip-id') !== null) {
return;
}
1403
tooltip.open(args.element);
},
dragStop: function (args) {
tooltip.close();
}
});
}
</script>
<style type="text/css">
#demoSmart {
background: rebeccapurple;
height: 50px;
left: 35%;
position: absolute;
top: 35%;
width: 50px;
}
#targetContainer {
margin: 10px;
min-height: 320px;
width: 100%;
float: left;
border: 1px solid #dddddd;
border-radius: 3px;
}
.control-section {
padding: 3px;
margin-right: 20px;
}
</style>
When mouse trailing option is enabled, the tip pointer position gets auto adjusted based on
the target, and other position values like start, end, and middle are not applied (to prevent
the pointer from moving out of target).
Mouse Trailing
1404
Tooltips can be positioned relative to the mouse pointer. This behavior can be enabled or
disabled by using the mouseTrail property. By default, it is set to false .
razor
mousetrailing.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("Tooltip").MouseTrail(true).Content("Tooltip content").ContentTe
mplate(@<div>
<div id="target" style="margin: 50px;">
Show tooltip
</div>
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 80px auto;
padding: 20px;
width: 200px;
}
</style>
When mouse trailing option is enabled, the tip pointer position gets auto adjusted based on
the target, and other position values like start, end, and middle are not applied (to prevent
the pointer from moving out of target).
offsetX specifies the distance between the target and Tooltip element in X axis.
offsetY specifies the distance between the target and Tooltip element in Y axis.
1405
The following code example illustrates how to set offset values.
razor
offsetvalues.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").OffsetX(30).OffsetY(30).MouseTrail(true).ShowTipPointer(
false).Content("Tooltip content").ContentTemplate(@<div>
<div id="target">Show tooltip</div>
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 80px auto;
padding: 20px;
width: 200px;
}
</style>
By default, collision is handled automatically and therefore when collision is detected the
Tooltip fits horizontally and flips vertically.
1406
Open Mode
You can decide the mode on which the Tooltip is to be opened on a page, i.e., on hovering,
focusing, or clicking on the target elements.
On mobile devices, Tooltips appear when you tap and hold the element, even if the
opensOn option is assigned with Hover . Tooltips are also displayed as long as you
continue to tap and hold the element. On lift, it disappears in the next 1.5 seconds. If there
is another action before that time ends, then the Tooltip disappears.
The opensOn property can take either a single or a combination of multiple values, separated by
space from the following options. The table below explains how the Tooltip opens on both
desktop and mobile based on the value(s) assigned to the opensOn property. By default, it takes
Auto value.
Tooltip appears
Click Tooltip appears when you click a target element. when you single tap
the target element.
To open the Tooltip for multiple actions, say while hovering over or clicking on a target element,
the opensOn property can be assigned with multiple values, separated by space as Hover
Click .
Auto value cannot be used with any combination for multiple values.
The following code example shows how to set the open mode for Tooltips.
razor
open-mode.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
1407
@section ControlsSection{
@Html.EJS().Tooltip("hover").OpensOn("Hover").Content("Tooltip from hover").Content
Template(@<div id="tooltiphover" class="blocks"><span>Hover Me !(Default)</span></div>)
.Render()
@Html.EJS().Tooltip("click").OpensOn("Click").Content("Tooltip from Click").Content
Template(@<div id="tooltipclick" class="blocks"><span>Click Me !</span></div>).Render()
@Html.EJS().Tooltip("focus").OpensOn("Focus").Content("Tooltip from focus").Target(
".e-info").ContentTemplate(@<div class="blocks"><span><input class="e-info" id="tooltip
focus" type="text" placeholder="Focus and blur" /></span></div>).Render()
@Html.EJS().Tooltip("custom").OpensOn("Custom").Content("Tooltip from custom mode")
.ContentTemplate(@<div id="tooltipcustom" class="blocks">
@Html.EJS().Button("open").Content("Click to open tooltip manually").Created("creat
ed").Render()
</div>).Render()
}
<style>
#hover, #click, #focus, #custom, #open {
width: 200px;
}
.blocks {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
display: inline-block;
line-height: 50px;
margin: 0 10px 10px 0;
overflow: hidden;
text-align: center;
vertical-align: middle;
width: 200px;
}
</style>
<script>
function created() {
document.getElementById('open').addEventListener("click", function () {
var customTooltip = document.getElementById('custom').ej2_instances[0];
if (this.getAttribute("data-tooltip-id")) {
customTooltip.close();
} else {
customTooltip.open(this);
}
});
}
</script>
1408
{
ViewBag.hover = "Tooltip from hover";
ViewBag.click = "Tooltip from click";
ViewBag.focus = "Tooltip from focus";
ViewBag.custom = "Tooltip from custom mode";
return View();
}
The following code example shows how to define custom open mode for the Tooltip.
razor
custom-mode.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").OpensOn("Custom").Content("Tooltip from custom mode"
).ContentTemplate(@<div id="box">
Double-click to open Tooltip.
</div>).Created("created").Render()
}
<style>
#box {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 50px auto;
padding: 20px;
width: 250px;
}
</style>
<script>
function created() {
document.getElementById('box').addEventListener("dblclick", function () {
var tooltip = document.getElementById('tooltip').ej2_instances[0];
if (this.getAttribute("data-tooltip-id")) {
tooltip.close();
} else {
tooltip.open(this);
}
1409
});
}
</script>
Sticky mode
With this mode set to true , Tooltips can be made to show up on the screen as long as the
close icon is pressed. In this mode, close icon is attached to the Tooltip located at the top right
corner. This mode can be enabled or disabled using the isSticky property.
razor
sticky-mode.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").IsSticky(true).Content("Click close icon to close me"
).ContentTemplate(@<div id="target">
Show tooltip
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 80px auto;
padding: 20px;
width: 200px;
}
</style>
1410
Open/Close Tooltip with delay
The Tooltips can be opened or closed after some delay by using the openDelay and
closeDelay properties.
razor
delay-mode.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").OpenDelay(1000).CloseDelay(1000).Content("Tooltip wi
th delay").ContentTemplate(@<div id="target">
Show tooltip
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 80px auto;
padding: 20px;
width: 200px;
}
</style>
1411
Animation
To animate the Tooltip, a set of specific animation effects are available, and it can be controlled
using the animation property. The animation property also allows you to set delay, duration,
and various other effects of your choice.
AnimationModel is derived from base to apply the chosen animation effect, duration, etc. on
Tooltips.
By default, Tooltip entrance occurs over 150 ms using the ease-out timing function. It exits also
at 150 ms, but uses ease-in timing function.
razor
animation.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").Content("Tooltip content").Animation(new {
open = new { effect = "ZoomIn", duration = 1000, delay = 0 },
close = new { effect = "ZoomOut", duration = 500, delay = 0 }
}).ContentTemplate(@<div id="target">
Show tooltip
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 50px auto;
padding: 10px;
width: 100px;
}
</style>
1412
The default animation effect for the Tooltip is set to FadeIn for its open action, and FadeOut for
its close action. The default duration is set to 150 ms and delay is set to 0.
Animation effects
The animation effects that are applicable to Tooltips are:
FadeIn
FadeOut
FadeZoomIn
FadeZoomOut
FlipXDownIn
FlipXDownOut
FlipXUpIn
FlipXUpOut
FlipYLeftIn
FlipYLeftOut
FlipYRightIn
FlipYRightOut
ZoomIn
ZoomOut
None
When the effect is specified as None , no effect will be applied to the Tooltip, and animation is
considered to be set to off .
Some of the above animation effects suits the Tooltip better when its tip pointer is hidden.
This can be achieved by setting the showTipPointer to false.
Refer to the code snippet below to apply animations using public methods.
razor
animation-openclose.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").Content("Tooltip content").OpensOn("Custom").Content
1413
Template(@<div id="target">
Show tooltip
</div>).Created("created").Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 50px auto;
padding: 10px;
width: 100px;
}
</style>
<script>
function created() {
document.getElementById('target').addEventListener("click", function () {
var tooltip = document.getElementById('tooltip').ej2_instances[0];
if (this.getAttribute("data-tooltip-id")) {
var closeAnimation = { effect: 'FadeOut', duration: 1000 }
tooltip.close(closeAnimation);
} else {
var openAnimation = { effect: 'FadeIn', duration: 1000 }
tooltip.open(this, openAnimation);
}
});
}
</script>
Apply transition
The transition effect can be applied on Tooltips by using the beforeRender event as given in the
following work-around code example.
razor
animation-transition.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").Target(".circletool").BeforeRender("onBeforeRender")
1414
.AfterClose("onAfterClose").CloseDelay(1000).Animation(new {
open = new { effect = "ZoomIn", duration = 500 },
close = new { effect = "ZoomOut", duration = 500 }
}).ContentTemplate(@<div>
<h3> Transition effect </h3>
<div id="box" class="e-prevent-select">
<div class="circletool" style="top:18%;left:5%" title="This is Turtle !!!">
</div>
<div class="circletool" style="top:30%;left:30%" title="This is Snake !!!">
</div>
<div class="circletool" style="top:80%;left:80%" title="This is Croc !!!"><
/div>
<div class="circletool" style="top:65%;left:50%" title="This is String Ray
!!!"></div>
<div class="circletool" style="top:75%;left:15%" title="This is Blob Fish !
!!"></div>
<div class="circletool" style="top:30%;left:70%" title="This is Mammoth !!!"
></div>
</div>
</div>).Render()
}
<style>
#box {
border: 1px solid #c8c8c8;
box-sizing: border-box;
height: 200px;
margin-left: 10px;
margin-right: 10px;
position: relative;
}
.circletool {
background: yellowgreen;
border-radius: 50px;
height: 20px;
position: absolute;
width: 20px;
}
</style>
<script>
function onBeforeRender(args) {
if (args.element) {
// here prevent animation while apply transition
this.animation = { open: { effect: 'None' } };
args.element.style.display = 'block';
args.element.style.transitionProperty = 'left,top';
args.element.style.transitionDuration = '1000ms';
}
}
1415
function onAfterClose(args) {
// restore the animation effects
this.animation = { open: { effect: 'ZoomIn', duration: 500 }, close: { effect:
'ZoomOut', duration: 500 } };
}
</script>
1416
Customization
The Tooltip can be customized by using the cssClass property, which accepts custom CSS
class names that define specific user-defined styles and themes to be applied on the Tooltip
element.
razor
tooltip-pointer.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("tooltip").CssClass("customtip").Content("Tooltip arrow customiz
ed").ContentTemplate(@<div id="target">
Show tooltip
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 70px auto;
padding: 20px;
width: 200px;
}
/* csslint ignore:start */
.customtip.e-tooltip-wrap {
padding: 4px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-bottom {
height: 20px;
width: 12px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-top {
1417
height: 20px;
width: 12px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-left {
height: 12px;
width: 20px;
}
.customtip.e-tooltip-wrap .e-arrow-tip.e-tip-right {
height: 12px;
width: 20px;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-bottom {
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 20px solid #616161;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-top {
border-bottom: 20px solid #616161;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-left {
border-bottom: 6px solid transparent;
border-right: 20px solid #616161;
border-top: 6px solid transparent;
}
.customtip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-right {
border-bottom: 6px solid transparent;
border-left: 20px solid #616161;
border-top: 6px solid transparent;
}
</style>
Tooltip customization
1418
The complete look and feel of the Tooltip can be customized by changing it's background color,
opacity, content font, etc. The following code example shows the way to achieve it.
razor
tooltip-view.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection{
@Html.EJS().Tooltip("target").CssClass("customtooltip").Content("Tooltip customized"
).ContentTemplate(@<div id="content">
Show tooltip
</div>).Render()
}
<style>
#target {
background-color: #ececec;
border: 1px solid #c8c8c8;
box-sizing: border-box;
margin: 70px auto;
padding: 20px;
width: 200px;
}
/* csslint ignore:start */
.customtooltip.e-tooltip-wrap .e-tip-content {
line-height: 20px;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip.e-tip-bottom {
height: 12px;
left: 50%;
top: 100%;
width: 24px;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip.e-tip-top {
height: 12px;
left: 50%;
top: -9px;
width: 24px;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip.e-tip-left {
height: 24px;
left: -9px;
1419
top: 48%;
width: 12px;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip.e-tip-right {
height: 24px;
left: 100%;
top: 50%;
width: 12px;
}
.customtooltip.e-tooltip-wrap {
border-radius: 4px;
opacity: 1;
}
.customtooltip.e-tooltip-wrap.e-popup {
background-color: #fff;
border: 2px solid #000;
}
.customtooltip.e-tooltip-wrap .e-tip-content {
color: #000;
font-size: 12px;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-bottom {
border-left: 12px solid transparent;
border-right: 14px solid transparent;
border-top: 12px solid #000;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-top {
border-bottom: 12px solid #000;
border-left: 12px solid transparent;
border-right: 12px solid transparent;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-left {
border-bottom: 12px solid transparent;
border-right: 12px solid #000;
border-top: 12px solid transparent;
}
.customtooltip.e-tooltip-wrap .e-arrow-tip-outer.e-tip-right {
border-bottom: 12px solid transparent;
border-left: 12px solid #000;
border-top: 12px solid transparent;
}
1420
.customtooltip.e-tooltip-wrap .e-arrow-tip-inner.e-tip-bottom {
color: #fff;
font-size: 25.9px;
}
</style>
1421
Overview
The uploader component is used to upload images, documents, and other files to the server.
This component is the extended version of HTML5 that is uploaded with multiple file selection,
auto upload, drag and drop, progress bar, preload files, and validation.
Key features
Asynchronous upload - Allows you to upload the files asynchronously. The upload process
requires save and remove action URL to manage upload process in the server.
Drag and drop - Allows you to drag files from the file explorer and drop into the drop area.
By default, the uploader component act as drop area element.
Form supports - The selected or dropped files are received as a collection in a form action
when the form is submitted.
Validation - Validates the selected file size and extension by using the allowedExtensions,
maxFileSize, and minFileSize properties.
Template - You can customize default appearance of the uploader using the template
property along with the buttons property.
Localization - Supports to localize the text content of action buttons, file status, clear icon
title, tooltips, and text content of drag area.
1422
Getting Started
This section briefly explains about how to include a simple Uploader in your ASP.NET MVC
application. You can refer ASP.NET MVC Getting Started documentation page for introduction
part part of the system requirements and configure the common specifications.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the
NuGet feed, you also have to include the license key in your projects. Please refer to this
link to know about registering Syncfusion license key in your ASP.NET MVC application to
use our components.
razor
getting-started.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
drop-area.cs
@section ControlsSection{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
async-settings.cs
@section ControlsSection{
1424
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.Uploade
rAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Sav
e", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Aut
oUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
success_failed.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").Success=("onUploadSuccess").Failure=("onUploadF
ailed").AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings
{ SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl
= "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
<script>
1425
function onUploadSuccess(args) {
var _this = this;
var spinnerElement = document.getElementById('dropArea');
var li = document.getElementById('dropArea').querySelector('[data-file-name="'
+ args.file.name + '"]');
if (!ej.base.isNullOrUndefined(li.querySelector('.progress-bar-container'))) {
ej.base.detach(li.querySelector('.progress-bar-container'));
}
if (args.operation === 'upload') {
li.querySelector('.file-name').classList.add('upload-success');
li.querySelector('.close-icon-container').classList.add('delete-icon');
(li.querySelector('.close-icon-container')).onclick = function () {
generateSpinner(_this.uploadWrapper);
};
li.querySelector('.close-icon-container').onkeydown = function (e) {
if (e.keyCode === 13) {
generateSpinner(e.target.closest('.e-upload'));
}
};
}
if (args.operation === 'remove') {
this.fileList.splice(this.fileList.indexOf(li), 1);
this.filesData.splice(this.fileList.indexOf(li), 1);
ej.base.detach(li);
ej.popups.hideSpinner(spinnerElement);
ej.base.detach(spinnerElement.querySelector('.e-spinner-pane'));
}
ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', re
moveFiles, this);
}
function generateSpinner(targetElement) {
ej.popups.createSpinner({ target: targetElement, width: '25px' });
ej.popups.showSpinner(targetElement);
}
function onUploadFailed(args) {
var li = document.getElementById('dropArea').querySelector('[data-file-name="'
+ args.file.name + '"]');
ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', re
moveFiles, this);
li.querySelector('.file-name ').classList.add('upload-fails');
if (args.operation === 'upload') {
ej.base.detach(li.querySelector('.progress-bar-container'));
}
}
</script>
using System;
1426
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1427
Asynchronous upload
The uploader component allows you to upload the files asynchronously. The upload process
requires save and remove action URL to manage the upload process in the server.
The File can be uploaded automatically or manually. For more information, you can refer to the
Auto Upload section from the documentation.
razor
multiple.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).AsyncSettings(new Syncfusion.
EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/upload
box/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
1428
{
return View();
}
}
}
razor
single.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).Multiple(false).AsyncSettings(
new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusi
on.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/serv
ices/api/uploadbox/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1429
Save action
The save action handler upload the files that needs to be specified in the saveUrl property. The
save handler receives the submitted files and manages the save process in server. After
uploading the files to server location, the color of the selected file name changes to green and
the remove icon is changed as bin icon.
* When the file is uploaded successfully, the event “success” triggers to handle the
operation after upload.
* When the file is failed to upload, the event “failure” triggers with information, w
hich cause this failure.
You can cancel the upload process by setting the upload event argument eventargs.cancel to
true.
razor
save.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).AsyncSettings(new Syncfusion.E
J2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/
api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadb
ox/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
1430
}
[AcceptVerbs("Post")]
public void Save()
{
try
{
if (HttpContext.Current.Request.Files.AllKeys.Length > 0)
{
var httpPostedFile = HttpContext.Current.Request.Files["UploadFiles"];
if (httpPostedFile != null)
{
var fileSave = HttpContext.Current.Server.MapPath("UploadedFiles");
var fileSavePath = Path.Combine(fileSave, httpPostedFile.FileName);
if (!File.Exists(fileSavePath))
{
httpPostedFile.SaveAs(fileSavePath);
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusDescription = "File uploaded succesfully";
Response.End();
}
else
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.Status = "400 File already exists";
Response.StatusCode = 400;
Response.StatusDescription = "File already exists";
Response.End();
}
}
}
}
catch (Exception e)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusCode = 400;
1431
Response.Status = "400 No Content";
Response.StatusDescription = e.Message;
Response.End();
}
}
Remove action
The remove action is optional. Specify the URL to handle remove process from server. The
remove handler receives the posted files and handle the remove operation in server.
* When the files are removed successfully from the server, the success event triggers
to denote the process has completed.
* When remove action fails, the event “failure” triggers with information, which caus
e failure in remove process.
You can differentiate the file operation whether the success event triggers from save or
remove action in its arguments eventArgs.operation.
You can remove the files which is not uploaded locally by clicking the remove icon. In this case,
the success or failure events will not be triggered.
razor
remove.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).AsyncSettings(new Syncfusion.
EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/upload
box/Remove" }).Render()
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
1432
{
return View();
}
}
}
[AcceptVerbs("Post")]
public void Remove()
{
try
{
var fileSave = "";
if (HttpContext.Current.Request.Form["cancel-uploading"] != null)
{
fileSave = HttpContext.Current.Server.MapPath("UploadingFiles");
}
else
{
fileSave = HttpContext.Current.Server.MapPath("UploadedFiles");
}
var fileName = HttpContext.Current.Request.Files["UploadFiles"].FileName;
var fileSavePath = Path.Combine(fileSave, fileName);
if (File.Exists(fileSavePath))
{
File.Delete(fileSavePath);
}
}
catch (Exception e)
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.Status = "404 File not found";
Response.StatusCode = 404;
Response.StatusDescription = "File not found";
Response.End();
}
}
Auto upload
1433
By default, the uploader processes the files to upload once the files are selected and added in
upload queue. To upload manually, disable the autoUpload property. When you disable this
property, you can use the action buttons to call upload all or clear all actions manually. You can
change those buttons text using the buttons property in Uploader component.
razor
auto-upload.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
Preload files
The uploader component allows you to preload the list of files that are uploaded in the server.
The preloaded files are useful to view and remove the files from server that can be achieved by
the files property. By default, the files are configured with uploaded successfully state on
rendering file list. The following properties are mandatory to configure the preloaded files:
* Name
* Size
* Type
razor
1434
preload-files.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).AsyncSettings(new Syncfusion.
EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/upload
box/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
The following code block shows how to add the additional headers with save and remove action
request.
@Html.EJS().Uploader("UploadFiles").DropArea(".control-fluid").Uploading("addHeaders
").Removing("addHeaders").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings
{ SaveUrl = @Url.Content("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove"
) }).Render()
function addHeaders(args) {
1435
args.currentRequest.setRequestHeader('custom-header', 'Syncfusion');
}
1436
Chunk Upload
The Uploader sends the large file split into small chunks and transmits to the server using AJAX.
You can also pause, resume, and retry the failed chunk file.
To enable the chunk upload, set the size to chunkSize option of the upload and it receives the
value in bytes .
razor
chunk.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.Uploade
rAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Sav
e", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove", Chunk
Size = 102400 }).AutoUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1437
The chunk upload functionality separates the selected files into blobs of the data or chunks.
These chunks are transmitted to the server using an AJAX request. The chunks are sent in
sequential order, and the next chunk can be sent to the server according to the success of the
previous chunk. If any one of the chunk failed, then the remaining chunk cannot be sent to the
server. The chunkSuccess or chunkFailure event will be triggered when the chunk is sent to the
server successfully or failed. If all the chunks are sent to the server successfully, the uploader
success event is triggered.
Chunk upload will work when the selected file size is greater than the specified chunk size.
otherwise, it upload the files normally.
Additional configurations
To modify the chunk upload, the following options can be used.
RetryAfterDelay - If error occurs while sending any chunk request from JavaScript, hold the
operation for 500 milliseconds (by default), and retry the operation using chunk. This can be
achieved by using the asyncSettings.retryAfterDelay property. You can modify the holding
time interval in milliseconds.
RetryCount - Specifies the number of retry actions performed when the file fails to upload.
By default, retry action is performed 3 times. If the file fails to upload continuously, the
request is aborted and the uploader failure event will trigger.
The following sample specifies the chunk upload delay with 3000 milliseconds and the retry count
is 5. The failure event is triggered as the wrong saveUrl is used.
razor
retry.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.Uploade
rAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Sav
e", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove", chunk
Size = 102400, retryCount = 5, retryAfterDelay = 3000 }).AutoUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
1438
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
Resumable upload
Allows you to resume an upload operation after a network failure or manually interrupts (pause)
the upload. You can perform pause and resume upload actions using public methods (pause and
resume) and UI interaction. The pause icon is enabled after the upload begins.
This pause and resume features available only when the chunk upload is enabled.
razor
resumable.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.Uploade
rAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Sav
e", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove", chunk
Size = 102400 }).AutoUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
1439
return View();
}
}
}
Cancel upload
The uploader component allows you to cancel the uploading file. This can be achieved by
clicking the cancel icon or using the cancel method. The cancelling event will be fired whenever
the file upload request is canceled. While canceling the upload request, the partially uploaded file
is removed from the server.
When the request fails, the pause icon is changed to retry icon. By clicking the retry icon, sends
the failed chunk request again to the server and upload started from where it is failed. You can
retry the canceled upload request again using retry UI or retry methods. But, if you retry this, the
file upload action again starts from initial.
The following example explains about chunk upload with cancel support.
razor
cancel.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs.Uploade
rAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Sav
e", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove", chunk
Size = 102400 }).AutoUpload=(false).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
1440
}
}
}
The retry action has different working behavior for chunk upload and default upload.
Chunk upload - Retries to upload the failed request where it is failed previously.
Default upload - Retries to upload the failed file again from initial.
Server-Side configurations
The server-side implementation entirely depends on the application requirements and logic. The
following code snippet provides the server-side logic to handle the chunk upload using the
uploader components.
1441
// After all the chunk files completely uploaded, remove the .p
art extension and move this file into save location
System.IO.File.Move(SaveFilePath, originalFilePath);
}
}
HttpResponse ChunkResponse = HttpContext.Current.Response;
ChunkResponse.Clear();
ChunkResponse.ContentType = "application/json; charset=utf-8";
ChunkResponse.StatusDescription = "File uploaded succesfully";
ChunkResponse.End();
}
var httpPostedFile = HttpContext.Current.Request.Files["UploadFiles"];
if (httpPostedFile != null)
{
var fileSave = HttpContext.Current.Server.MapPath("UploadedFiles");
var fileSavePath = Path.Combine(fileSave, httpPostedFile.FileName);
if (!File.Exists(fileSavePath))
{
httpPostedFile.SaveAs(fileSavePath);
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusDescription = "File uploaded succesfully";
Response.End();
}
else
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.Status = "400 File already exists";
Response.StatusCode = 400;
Response.StatusDescription = "File already exists";
Response.End();
}
}
}
}
catch (Exception e)
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.StatusCode = 400;
Response.Status = "400 No Content";
Response.StatusDescription = e.Message;
Response.End();
}
}
1442
// Server configuration for remove a uploaded file
public void Remove()
{
try
{
var fileSave = "";
if (HttpContext.Current.Request.Form["cancel-uploading"] != null)
{
fileSave = HttpContext.Current.Server.MapPath("UploadingFiles");
} else
{
fileSave = HttpContext.Current.Server.MapPath("UploadedFiles");
}
var fileName = HttpContext.Current.Request.Files["UploadFiles"].FileName;
var fileSavePath = Path.Combine(fileSave, fileName);
if (File.Exists(fileSavePath))
{
File.Delete(fileSavePath);
}
}
catch (Exception e)
{
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.Status = "404 File not found";
Response.StatusCode = 404;
Response.StatusDescription = "File not found";
Response.End();
}
}
// Merge the current chunk file with previous uploaded chunk files
public void MergeChunkFile(string fullPath, Stream chunkContent)
{
try
{
using (FileStream stream = new FileStream(fullPath, FileMode.Append, FileAccess
.Write, FileShare.ReadWrite))
{
using (chunkContent)
{
chunkContent.CopyTo(stream);
}
}
}
catch (IOException ex)
{
throw ex;
}
}
1443
1444
Drag and drop
The uploader component allows you to drag and drop the files to upload. You can drag the files
from file explorer and drop into the drop area. By default, the uploader component act as drop
area element. The drop area gets highlighted when you drag the files over drop area.
razor
custom-drop.cs
index.css
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").DropArea("dropAreaElem").AutoUpload=(false).Re
nder()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
#droparea {
padding: 50px 25px;
1445
margin: 30px auto;
border: 1px solid #c3c3c3;
text-align: center;
width: 20%;
display: inline-flex;
}
.e-file-select,
.e-file-drop {
display: none;
}
body .e-upload-drag-hover {
outline: 2px dashed brown;
}
#uploadfile {
width: 60%;
display: inline-flex;
margin-left: 5%;
}
razor
customize-drop.cs
@section ControlsSection{
using System;
using System.Collections.Generic;
using System.Linq;
1446
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1447
Validation
The uploader component validate the selected files size and extension using the
allowedExtensions, minFileSize and maxFileSize properties. The files can be validated before
uploading to the server and can be ignored on uploading. Also, you can validate the files by
setting the HTML attributes to the original input element. The validation process occurs on drag-
and-drop the files also.
File type
You can allow the specific files alone to Upload using the allowedExtensions property. The
extension can be represented as collection by comma separators. The uploader component
filters the selected or dropped files to match against the specified file types and processes the
upload operation. The validation happens when you specify value to inline attribute to accept the
original input element.
razor
type-validation.cs
@using Syncfusion.EJ2
@{
var asyncSettings = new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "ht
tps://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspne
tmvc.syncfusion.com/services/api/uploadbox/Remove" };
@section ControlsSection{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
1448
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
File size
The uploader component allows you to validate the files based on its size. The validation helps to
restrict uploading large files or empty files to the server. The size can be represented in bytes .
By default, the uploader component allows you to upload minimum file size as 0 byte and
maximum file size as 28.4 MB using the minFileSize and maxFileSize properties.
razor
size-validation.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").MinFileSize=("10000").MaxFileSize=("1500000").A
utoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUr
l = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https:
//aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
1449
}
}
razor
max-count-validation.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").Selected=("onFileSelected").AutoUpload=(false).
Selected("onFileSelected").Progress=("onFileUpload").Success=("onUploadSuccess").Failur
e=("onUploadFailed").AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.Uploader
AsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save"
, RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Rende
r()
}
<script>
function onFileSelected(args : SelectedEventArgs) : void {
// Filter the 5 files only to showcase
args.filesData.splice(5);
let filesData : FileInfo[] = uploadObj.getFilesData();
let allFiles : FileInfo[] = filesData.concat(args.filesData);
if (allFiles.length > 5) {
for (let i : number = 0; i < allFiles.length; i++) {
if (allFiles.length > 5) {
allFiles.shift();
}
}
args.filesData = allFiles;
// set the modified custom data
args.modifiedFilesData = args.filesData;
}
args.isModified = true;
}
1450
generateSpinner(this.uploadWrapper);
};
(li.querySelector('.e-file-delete-btn') as HTMLElement).onkeydown = (e: any
) => {
if (e.keyCode === 13) {
generateSpinner(e.target.closest('.e-upload'));
}
};
} else {
hideSpinner(this.uploadWrapper);
detach(this.uploadWrapper.querySelector('.e-spinner-pane'));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
Duplicate files
You can validate the duplicate files before uploading to server using the selected event. Compare
the selected files with the existing files data and filter the file list by removing the duplicate files.
razor
1451
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").Selected("onFileSelected").AutoUpload(false).As
yncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnet
mvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfus
ion.com/services/api/uploadbox/Remove" }).Render()
<script>
function onFileSelect(args : any) {
let existingFiles: FileInfo[] = this.getFilesData();
for (let i: number = 0; i < args.filesData.length; i++) {
for(let j: number = 0; j < existingFiles.length; j++) {
if (!isNullOrUndefined(args.filesData[i])) {
if (existingFiles[j].name == args.filesData[i].name) {
args.filesData.splice(i, 1);
}
}
}
}
existingFiles = existingFiles.concat(args.filesData);
args.modifiedFilesData = existingFiles;
args.isModified = true;
}
</script>
1452
Forms Support (Synchronous Upload)
The Uploader component works with HTML form like default file input. The following configuration
is must to make the Uploader work inside the form.
The selected or dropped files are received as a collection in form action when the form is
submitted. The form action handles the server-side operations that manage the file upload
process. When you reset the form, the file list and data will be cleared.
razor
formsupport.cs
index.css
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
@section ControlsSection {
<div class="col-lg-12 control-section">
<h4 class="form-title">Photo Contest</h4>
<div class="control_wrapper" id="control_wrapper">
<!-- Initialize Uploader -->
<form id="form1" method="post">
<div class="form-group" style="padding-top: 11px;">
<div class="e-float-input">
<input type="text" id="name" name="name" data-required-message=
"* Enter your name" required="" data-msg-containerid="nameError">
<span class="e-float-line"></span>
<label class="e-float-text e-label-top" for="name">Name</label>
</div>
<div id="nameError"></div>
</div>
<div class="form-group" style="padding-top: 11px;">
<div class="e-float-input">
<input type="email" id="email" name="email" data-validation="em
ail" data-required-message="* Enter your email" required="" data-msg-containerid="mailE
rror">
<span class="e-float-line"></span>
<label class="e-float-text e-label-top" for="email">Email</labe
l>
</div>
<div id="mailError"></div>
</div>
1453
<div class="form-group" style="padding-top: 11px;">
<div class="e-float-input">
<input type="text" id="mobileno" name="mobile" data-required-me
ssage="* Enter your mobile number" required="" data-msg-containerid="noError">
<span class="e-float-line"></span>
<label class="e-float-text e-label-top" for="mobile">Mobile No<
/label>
</div>
<div id="noError"></div>
</div>
<div class="form-group" style="padding-top: 11px;">
<div class="e-float-input upload-area">
<input type="text" id="upload" name="upload" readonly data-requ
ired-message="* Select any file" required="" data-msg-containerid="uploadError">
<button id="browse" type="button" class="e-control e-btn e-info"
onclick="browseClick()">Browse..</button>
<span class="e-float-line"></span>
<label class="e-float-text e-label-top" for="upload">Choose a f
ile</label>
</div>
<div id="uploadError"></div>
@Html.EJS().Uploader("fileupload").AutoUpload(false).Selected("onFi
leSelect").Multiple(false).AllowedExtensions("image/*").Render()
</div>
<div class="form-group" style="padding-top: 11px;">
<div class="e-float-input">
<textarea class="address-field" rows="4" id="Address"></textare
a>
<span class="e-float-line"></span>
<label class="e-float-text e-label-top" >Address</label>
</div>
</div>
</form>
<div class="submitBtn">
<button class="submit-btn e-btn" id="submit-btn" onclick="onFormSubmit(
)">Submit</button>
</div>
@Html.EJS().Dialog("confirmationDialog").Width("335px").Visible(false).Cont
ent("Your details has been updated successfully, Thank you").Target("#control_wrapper")
.IsModal(true).AnimationSettings(new DialogAnimationSettings() { Effect = DialogEffect.
Zoom }).Render()
</div>
</div>
}
<script>
window.onload = function () {
1454
var confirm = document.getElementById("confirmationDialog").ej2_instances[0];
confirm.visible = false;
inputElement = document.getElementById('upload');
formID = document.getElementById('form1');
formObj = new ej.inputs.FormValidator(formID, options);
}
function onFileSelect(args) {
var inputElement = document.getElementById('upload');
inputElement.value = args.filesData[0].name;
}
var options = {
customPlacement: function (inputElement, errorElement) {
inputElement = inputElement.closest('.form-group').querySelector('.error');
inputElement.parentElement.appendChild(errorElement);
},
rules: {
'name': {
required: true
},
'email': {
required: true
},
'upload': {
required: true
},
'mobile': {
required: true
}
}
};
inputElement = document.getElementById('upload');
formID = document.getElementById('form1');
1455
function browseClick() {
document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button'
).click();
return false;
};
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
.control_wrapper {
max-width: 400px;
margin: auto;
}
#control_wrapper {
max-width: 440px;
margin: auto;
border: 0.5px solid grey;
padding: 1% 4% 2%;
background: #f9f9f9;
}
/* csslint ignore:start */
.bootstrap label.e-float-text.e-label-top {
font-weight: bold;
}
/* csslint ignore:end */
.highcontrast #control_wrapper {
1456
background: #000000;
}
.e-error {
padding-top: 3px;
}
.e-upload {
width: 100%;
position: relative;
margin-top: 15px;
}
.submit-btn {
margin-top: 15px;
position: relative;
}
.submitBtn {
position: relative;
left: 79%;
}
.form-support {
width: 100%;
}
.success .form-support {
display: none;
}
.success .successmsg {
border: 0.5px solid green;
padding: 10%;
color: green;
}
#form1 {
position: relative;
top: 14%;
}
1457
.form-support td {
width: 100%;
padding-top: 4%;
}
.e-upload {
display: none;
}
.choose-file {
width: 60%;
}
#browse {
left: 46%;
float: right;
top: -26px
}
.e-bigger #browse {
top: -41px;
}
/* csslint ignore:start */
.e-bigger.material #browse {
top: -35px;
}
.bootstrap #browse {
top: -34px;
}
.form-title {
text-align: center;
}
1458
Template
You can customize the default appearance of the uploader using a template along with buttons.
For example, you can display file type icon along with the default UI elements.
razor
index.css
@section ControlsSection{
<div id='dropArea'>
<span id='drop' class="droparea"> Drop files here or <a href="" id='browse'><u>
Browse</u></a> </span>
@Html.EJS().Uploader("UploadFiles").Success=("onuploadSuccess").Failure("onuplo
adFailed").Selected("onSelect").Progress=("onFileUpload").AsyncSettings(new Syncfusion.
EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/upload
box/Remove" }).AutoUpload=(false).Render()
</div>
<div style='margin-left: 50px; padding-top:25px;'>
<button class="e-btn e-css" id="clearbtn">Clear All</button>
</div>
}
<script>
document.getElementById('browse').onclick = function () {
document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button'
).click();
return false;
};
function onFileUpload(args: any) {
let li: HTMLElement = this.uploadWrapper.querySelector('[data-file-name="' + ar
gs.file.name + '"]');
let progressValue: number = Math.round((args.e.loaded / args.e.total) * 100);
li.getElementsByTagName('progress')[0].value = progressValue;
li.getElementsByClassName('percent')[0].textContent = progressValue.toString()
+ " %";
1459
}
function onuploadSuccess(args: any) {
if (args.operation === 'remove') {
let height: string = document.getElementById('dropArea').style.height;
height = (parseInt(height) - 40) + 'px';
document.getElementById('dropArea').style.height = height;
} else {
let li: HTMLElement = this.uploadWrapper.querySelector('[data-file-name="'
+ args.file.name + '"]');
let progressBar: HTMLElement = li.getElementsByTagName('progress')[0];
progressBar.classList.add('e-upload-success');
li.getElementsByClassName('percent')[0].classList.add('e-upload-success');
let height: string = document.getElementById('dropArea').style.height;
document.getElementById('dropArea').style.height = parseInt(height) - 15 +
'px';
}
}
function onuploadFailed(args: any) {
let li: HTMLElement = this.uploadWrapper.querySelector('[data-file-name="' + ar
gs.file.name + '"]');
let progressBar: HTMLElement = li.getElementsByTagName('progress')[0];
progressBar.classList.add('e-upload-failed');
li.getElementsByClassName('percent')[0].classList.add('e-upload-failed');
}
function onSelect(args: SelectedEventArgs) {
let length: number = args.filesData.length;
let height: string = document.getElementById('dropArea').style.height;
height = parseInt(height) + (length * 55) + 'px';
document.getElementById('dropArea').style.height = height;
}
</script>
#dropArea {
min-height: 50px;
padding-top: 15px;
position: relative;
}
#drop {
padding: 3% 30% 3%;
display: inherit;
border: 1px dashed #c3c3cc
}
.droparea {
font-size: 13px;
}
1460
.e-bigger .droparea {
font-size: 14px;
}
.control_wrapper {
max-width: 400px;
margin: auto;
}
.e-file-select-wrap {
display: none;
}
.e-upload {
float: none;
border: none;
}
.ul-element {
list-style: none;
width: 100%;
padding-left: 0;
}
.file-name {
padding: 8px 6px 8px 0;
font-size: 13px;
width: 46%;
display: inline-block;
position: relative;
top: 4px;
}
.e-bigger .file-name {
font-size: 14px;
}
.file-size {
padding: 4px;
font-size: 13px;
width: 18%;
display: inline-block;
position: relative;
}
.e-bigger .file-size {
font-size: 14px;
}
1461
.file-lists {
border: 1px solid lightgray;
padding: 0 6px 0 14px;
margin-top: 15px;
position: relative;
background: #000000;
}
.file-size, .file-name {
font-family: "Helvetica Neue", "Helvetica", "Arial", "sans-serif";
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.progress-bar-container {
display: block;
float: right;
height: 20px;
right: 13%;
top: 14px;
position: relative;
width: 20%;
}
.progress{
width: 100%;
height: 15px;
-webkit-appearance: none;
-moz-appearance: none;
}
.close-icon-container
{
cursor: pointer;
font-size: 11px;
height: 24px;
margin: 0 12px 0 22px;
padding: 0;
position: absolute;
right: 0;
width: 24px;
top: 6px;
}
.e-icons::before {
left: 7px;
position: inherit;
1462
top: 7px;
content: '\e932';
}
.delete-icon::before {
content: '\e94a';
}
.close-icon-container:hover {
background-color: #d0cdcd;
border-color: transparent;
border-radius: 50%;
box-shadow: 0 0 0 transparent;
}
.highcontrast .close-icon-container:hover {
background-color: #ffd939;
}
.highcontrast .close-icon-container {
color: #ffffff;
}
.upload-success {
color: #2bc700;
}
.upload-fails {
color: #f44336;
}
progress::-webkit-progress-bar {
border: 1px solid lightgrey;
background-color: #ffffff;
border-radius: 2px;
}
#dropArea progress {
border: 1px solid lightgrey;
background-color: #ffffff;
border-radius: 2px;
}
.highcontrast #dropArea progress {
border: none;
background-color: #000000;
}
.highcontrast progress::-webkit-progress-bar {
border: none;
background-color: #000000;
}
1463
.material progress::-webkit-progress-value {
border-radius: 2px;
background-color: #ff4081;
}
.bootstrap progress::-webkit-progress-value {
border-radius: 2px;
background-color: #1f496e;
}
.fabric progress::-webkit-progress-value {
background-color: #1763ff;
border-radius: 2px;
top: -66px;
}
.highcontrast progress::-webkit-progress-value {
background-color: #ffd939;
border-radius: 2px;
}
.material progress::-moz-progress-bar {
border-radius: 2px;
background-color: #ff4081;
}
.bootstrap progress::-moz-progress-bar {
border-radius: 2px;
background-color: #1f496e;
}
.fabric progress::-moz-progress-bar {
background-color: #1763ff;
border-radius: 2px;
top: -66px;
}
.highcontrast progress::-moz-progress-bar {
background-color: #ffd939;
border-radius: 2px;
}
Custom template
You can design the own template by preventing the default file list including buttons. The
showFileList property is used to display whether the default file list or own file list when you use
custom template to upload or remove the files, pass the custom UI argument as true to call
upload / remove public method as follows:
1464
Refer to the following code sample.
razor
index.css
@section ControlsSection{
<div class="col-lg-8 control-section">
<div class="control_wrapper">
<div id='dropArea'>
<span id='drop' class="droparea"> Drop files here or <a href="" id='bro
wse'><u>Browse</u></a> </span>
@Html.EJS().Uploader("UploadFiles").Selected("onFileSelected").Progress
=("onFileUpload").Success=("onUploadSuccess").Failure=("onUploadFailed").AutoUpload(fal
se).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://
aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.s
yncfusion.com/services/api/uploadbox/Remove" }).Render()
</div>
</div>
</div>
}
<script>
var dropElement = document.getElementsByClassName('control-fluid')[0];
var filesDetails = [];
document.getElementById('browse').onclick = function () {
document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button'
).click();
return false;
};
document.getElementById('clearbtn').onclick = function () {
var uploadObj = document.getElementById("fileUpload")
uploadObj.ej2_instances[0].element.value = '';
ej.base.detach(document.getElementById('dropArea').querySelector('.upload-list-
root'));
uploadObj.ej2_instances[0].filesData = [];
uploadObj.ej2_instances[0].fileList = [];
};
var parentElement; var proxy; var progressbarContainer;
function onFileSelect(args) {
if (ej.base.isNullOrUndefined(document.getElementById('dropArea').querySelector(
'.upload-list-root'))) {
parentElement = ej.base.createElement('div', { className: 'upload-list-root'
});
parentElement.appendChild(ej.base.createElement('ul', { className: 'ul-elem
ent' }));
document.getElementById('dropArea').appendChild(parentElement);
}
for (var i = 0; i < args.filesData.length; i++) {
1465
formSelectedData(args.filesData[i], this); // create the LI element for
each file Data
}
this.filesData = this.filesData.concat(args.filesData);
this.upload(args.filesData, true);
args.cancel = true;
}
function formSelectedData(selectedFiles, proxy) {
var liEle = ej.base.createElement('li', { className: 'file-lists', attrs: { 'da
ta-file-name': selectedFiles.name } });
liEle.appendChild(ej.base.createElement('span', { className: 'file-name ', inne
rHTML: selectedFiles.name }));
liEle.appendChild(ej.base.createElement('span', { className: 'file-size ', inne
rHTML: proxy.bytesToSize(selectedFiles.size) }));
if (selectedFiles.status === proxy.localizedTexts('readyToUploadMessage')) {
progressbarContainer = ej.base.createElement('span', { className: 'progress
-bar-container' });
progressbarContainer.appendChild(ej.base.createElement('progress', { classN
ame: 'progress', attrs: { value: '0', max: '100' } }));
liEle.appendChild(progressbarContainer);
}
else {
liEle.querySelector('.file-name').classList.add('upload-fails');
}
var closeIconContainer = ej.base.createElement('span', { className: 'e-icons cl
ose-icon-container' });
ej.base.EventHandler.add(closeIconContainer, 'click', removeFiles, proxy);
liEle.appendChild(closeIconContainer);
document.querySelector('.ul-element').appendChild(liEle);
proxy.fileList.push(liEle);
}
function onFileUpload(args) {
var li = document.getElementById('dropArea').querySelector('[data-file-name="'
+ args.file.name + '"]');
ej.base.EventHandler.remove(li.querySelector('.close-icon-container'), 'click',
removeFiles);
var progressValue = Math.round((args.e.loaded / args.e.total) * 100);
if (!isNaN(progressValue)) {
li.getElementsByTagName('progress')[0].value = progressValue; // Updating
the progress bar value
}
}
function onUploadSuccess(args) {
var _this = this;
var spinnerElement = document.getElementById('dropArea');
var li = document.getElementById('dropArea').querySelector('[data-file-name="'
+ args.file.name + '"]');
if (!ej.base.isNullOrUndefined(li.querySelector('.progress-bar-container'))) {
ej.base.detach(li.querySelector('.progress-bar-container'));
1466
}
if (args.operation === 'upload') {
li.querySelector('.file-name').classList.add('upload-success');
li.querySelector('.close-icon-container').classList.add('delete-icon');
(li.querySelector('.close-icon-container')).onclick = function () {
generateSpinner(_this.uploadWrapper);
};
li.querySelector('.close-icon-container').onkeydown = function (e) {
if (e.keyCode === 13) {
generateSpinner(e.target.closest('.e-upload'));
}
};
}
if (args.operation === 'remove') {
this.fileList.splice(this.fileList.indexOf(li), 1);
this.filesData.splice(this.fileList.indexOf(li), 1);
ej.base.detach(li);
ej.popups.hideSpinner(spinnerElement);
ej.base.detach(spinnerElement.querySelector('.e-spinner-pane'));
}
ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', re
moveFiles, this);
}
function generateSpinner(targetElement) {
ej.popups.createSpinner({ target: targetElement, width: '25px' });
ej.popups.showSpinner(targetElement);
}
function onUploadFailed(args) {
var li = document.getElementById('dropArea').querySelector('[data-file-name="'
+ args.file.name + '"]');
ej.base.EventHandler.add(li.querySelector('.close-icon-container'), 'click', re
moveFiles, this);
li.querySelector('.file-name ').classList.add('upload-fails');
if (args.operation === 'upload') {
ej.base.detach(li.querySelector('.progress-bar-container'));
}
}
function removeFiles(args) {
var status = this.filesData[this.fileList.indexOf(args.currentTarget.parentElem
ent)].status;
if (status === this.localizedTexts('uploadSuccessMessage')) {
this.remove(this.filesData[this.fileList.indexOf(args.currentTarget.parentE
lement)]);
this.filesData.splice(this.fileList.indexOf(args.currentTarget.parentElemen
t), 1);
}
else {
ej.base.detach(args.currentTarget.parentElement);
}
1467
}
</script>
#dropArea {
min-height: 50px;
padding-top: 15px;
position: relative;
}
#drop {
padding: 3% 30% 3%;
display: inherit;
border: 1px dashed #c3c3cc
}
.droparea {
font-size: 13px;
}
.e-bigger .droparea {
font-size: 14px;
}
.control_wrapper {
max-width: 400px;
margin: auto;
}
.e-file-select-wrap {
display: none;
}
.e-upload {
float: none;
border: none;
}
.ul-element {
list-style: none;
width: 100%;
padding-left: 0;
}
.file-name {
padding: 8px 6px 8px 0;
font-size: 13px;
1468
width: 46%;
display: inline-block;
position: relative;
top: 4px;
}
.e-bigger .file-name {
font-size: 14px;
}
.file-size {
padding: 4px;
font-size: 13px;
width: 18%;
display: inline-block;
position: relative;
}
.e-bigger .file-size {
font-size: 14px;
}
.file-lists {
border: 1px solid lightgray;
padding: 0 6px 0 14px;
margin-top: 15px;
position: relative;
background: #d0cdcd;
}
.file-size, .file-name {
font-family: "Helvetica Neue", "Helvetica", "Arial", "sans-serif";
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.progress-bar-container {
display: block;
float: right;
height: 20px;
right: 13%;
top: 14px;
position: relative;
width: 20%;
}
.progress{
width: 100%;
1469
height: 15px;
-webkit-appearance: none;
-moz-appearance: none;
}
.close-icon-container
{
cursor: pointer;
font-size: 11px;
height: 24px;
margin: 0 12px 0 22px;
padding: 0;
position: absolute;
right: 0;
width: 24px;
top: 6px;
}
.close-icon-container::before {
left: 7px;
position: inherit;
top: 7px;
content: '\e932';
}
.delete-icon::before {
content: '\e94a';
}
.close-icon-container:hover {
background-color: #d0cdcd;
border-color: transparent;
border-radius: 50%;
box-shadow: 0 0 0 transparent;
}
.highcontrast .close-icon-container:hover {
background-color: #ffd939;
}
.highcontrast .close-icon-container {
color: #ffffff;
}
.upload-success {
color: #2bc700;
}
.upload-fails {
1470
color: #f44336;
}
progress::-webkit-progress-bar {
border: 1px solid lightgrey;
background-color: #ffffff;
border-radius: 2px;
}
#dropArea progress {
border: 1px solid lightgrey;
background-color: #ffffff;
border-radius: 2px;
}
.highcontrast #dropArea progress {
border: none;
background-color: #000000;
}
.highcontrast progress::-webkit-progress-bar {
border: none;
background-color: #000000;
}
.material progress::-webkit-progress-value {
border-radius: 2px;
background-color: #ff4081;
}
.bootstrap progress::-webkit-progress-value {
border-radius: 2px;
background-color: #1f496e;
}
.fabric progress::-webkit-progress-value {
background-color: #1763ff;
border-radius: 2px;
top: -66px;
}
.highcontrast progress::-webkit-progress-value {
background-color: #ffd939;
border-radius: 2px;
}
.material progress::-moz-progress-bar {
border-radius: 2px;
background-color: #ff4081;
}
.bootstrap progress::-moz-progress-bar {
border-radius: 2px;
background-color: #1f496e;
}
.fabric progress::-moz-progress-bar {
background-color: #1763ff;
border-radius: 2px;
1471
top: -66px;
}
.highcontrast progress::-moz-progress-bar {
background-color: #ffd939;
border-radius: 2px;
}
1472
Localization
The Localization library allows you to localize static text content of the uploader. The static text
contains default text content of action buttons, file status, clear icon title, tooltips, and text content
of drag area. Define the locale object for a culture and assign it to L10n load method.
The following are the list of keys and its values used in the uploader component:
Key Description
uploadFailedMessage To customize the status text when the file is failed to upload.
removedFailedMessage To customize the status text while the file is failed to remove.
To customize the status text when the file size is greater than
invalidMaxFileSize
the maximum file size.
invalidFileType To customize the status text when the file type is invalid.
To customize the status text when the file size is less than
invalidMinFileSize
the minimum file size.
razor
localization.cs
@section ControlsSection{
1473
@Html.EJS().Uploader("UploadFiles").Locale=("fr-CH").Selected("onFileSelected").Dro
pArea=("dropAreaElem").Progress=("onFileUpload").Success=("onUploadSuccess").Failure=("
onUploadFailed").AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyn
cSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", R
emoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
<script>
ej.base.L10n.load({
"fr-CH": {
"uploader": {
"invalidMinFileSize" : "La taille du fichier est trop petite! S'il vous pla
ît télécharger des fichiers avec une taille minimale de 10 Ko",
"invalidMaxFileSize" : "La taille du fichier dépasse 28 Mo",
"invalidFileType" : "Le type de fichier n'est pas autorisé",
"Browse" : "Feuilleter",
"Clear" : "Clair",
"Upload" : "Télécharger",
"dropFilesHint" : "ou Déposer des fichiers ici",
"uploadFailedMessage" : "Impossible d'importer le fichier",
"uploadSuccessMessage" : "Fichier téléchargé avec succès",
"removedSuccessMessage": "Fichier supprimé avec succès",
"removedFailedMessage": "Le fichier n'a pas pu être supprimé",
"inProgress": "Téléchargement",
"readyToUploadMessage": "Prêt à télécharger",
"remove": "Retirer",
"cancel": "Annuler",
"delete": "Supprimer le fichier"
}
}
})
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
1474
}
}
}
1475
Accessibility
The uploader component characterized with complete ARIA accessibility support that helps to be
accessible by on-screen readers and other assistive technology devices.
Keyboard interaction
The following are the standard keys that works on uploader component:
Keyboard
Actions
shortcuts
Closes the file browser dialog alone and cancels the upload on drop
Esc
the file.
razor
keyboard.cs
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).AsyncSettings(new Syncfusion.
EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/upload
box/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
1476
return View();
}
}
}
1477
How To
* .e-upload.e-control
* .e-upload .e-file-select
* .e-upload .e-file-drop
razor
hide-drop.cs
index.css
@section ControlsSection{
@Html.EJS().Uploader("UploadFiles").DropArea(".control-fluid").AsyncSettings(new
Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.c
om/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Remove" }).Render()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1478
#droparea {
padding: 50px 25px;
margin: 30px auto;
border: 1px solid #c3c3c3;
text-align: center;
width: 20%;
display: inline-flex;
}
.e-file-select,
.e-file-drop {
display: none;
}
body .e-upload-drag-hover {
outline: 2px dashed brown;
}
#uploadfile {
width: 60%;
display: inline-flex;
margin-left: 5%;
}
.e-control .e-file-select,
.e-control .e-file-drop {
display: none;
}
razor
invisible.cs
@section ControlsSection{
<div class="control_wrapper">
1479
<div id='preview'></div>
</div>
@section PreScripts {
<script>
function onSelect(args) {
for (var i = 0; i < args.filesData.length; i++) {
var liparentDiv = ej.base.createElement('div', { className: 'image-list' })
;
var liImage = ej.base.createElement('img', { className: 'image' });
liparentDiv.appendChild(liImage);
readURL(liImage, args.filesData[i]);
document.getElementById('preview').appendChild(liparentDiv);
}
args.cancel = true;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
1480
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
Customize progressbar
You can customize the progress bar’s size, color, and background by overriding the styles in
uploader component. Refer to the following example.
razor
progress-customize.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").AsyncSettings(new Syncfusion.EJ2.Inputs
.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploa
dbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove"
}).Render()
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
1481
return View();
}
}
}
razor
sorting.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").Selected("onSelect").AsyncSettings(new
Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.c
om/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Remove" }).Render()
</div>
<script>
var initial = true
function onSelect(args) {
if (initial) { initial = false; return; }
args.isModified = true;
var oldFiles = uploadObj.getFilesData();
var filesData = args.filesData.concat(oldFiles);
var modifiedData = sortFileList(filesData);
args.modifiedFilesData = modifiedData;
}
function sortFileList(filesData) {
var files = filesData;
var fileNames = [];
for (var i = 0; i < files.length; i++) {
fileNames.push(files[i].name);
}
var sortedFileNames = fileNames.sort();
var sortedFilesData = [];
var index = 0;
1482
for (var i = 0; i < sortedFileNames.length; i++) {
var name = sortedFileNames[i];
for (var i = 0; i < files.length; i++) {
if (name === files[i].name) {
sortedFilesData.push(files[i]);
}
}
}
return sortedFilesData;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
file-size.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
1483
@Html.EJS().Uploader("UploadFiles").Selected("onSelect").AsyncSettings(new
Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.c
om/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services
/api/uploadbox/Remove") }).Render()
</div>
<script>
function onSelect(args) {
var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
var totalSize = 0;
for (var i = 0; i < args.filesData.length; i++) {
var file = args.filesData[i];
totalSize = totalSize + file.size;
}
var size = uploadObj.bytesToSize(totalSize);
alert("Total select file's size is " + size);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
razor
1484
buttons.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").AutoUpload("false").AsyncSettings(new Syncf
usion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/se
rvices/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api/
uploadbox/Remove" }).Render()
</div>
<script>
var uploadEle = ej.base.createElement('span', { className: 'upload' });
uploadEle.innerHTML = 'Upload All';
var clearEle = ej.base.createElement('span', { className: 'remove' });
clearEle.innerHTML = 'Clear All';
window.onload = function (args) {
var uploaderObj = document.getElementById("UploadFiles").ej2_instances[0];
uploaderObj.setProperties({
buttons: {
browse: 'Choose file',
clear: clearEle,
upload: uploadEle
}})
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
1485
}
}
razor
confirm-dialog.cs
index.css
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").Removing("onremove").AsyncSettings(new Sync
fusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com/s
ervices/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/api
/uploadbox/Remove"}).Render()
@Html.EJS().Dialog("dialog").Target(".control-section").Visible(false).Width("2
50px").Content("Confirm to remove the file?").Buttons(ViewBag.DefaultButtons).Render()
</div>
<script>
window.onload = function () {
dialog = document.getElementById("dialog").ej2_instances[0];
}
function onremove(args) {
args.cancel = true;
removeFile.push(args.filesData);
dialog.show();
}
function onClick(args) {
var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
dialog.hide();
uploadObj.remove(removeFile, false, true);
removeFile = [];
1486
}
function Close() {
dialog.hide();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
ViewBag.button = new
{
content = "Ok",
isPrimary = true
};
return View();
}
}
}
.control_wrapper {
max-width: 400px;
margin: 0 auto;
}
1487
razor
index.css
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("fileupload").Uploading("onFileUpload").AsyncSettings(new Sy
ncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfusion.com
/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/services/a
pi/uploadbox/Remove" }).Render()
</div>
@section PreScripts {
<script>
function onFileUpload(args) {
args.customFormData = [{'name': 'Syncfusion INC'}];
}
</script>
}
.control_wrapper {
max-width: 505px;
margin: auto;
}
By default, it is working fine when you select a file by clicking the browse button. But, this
behavior is not supported to drag and drop the files for selection.
razor
validate-image.cs
index.css
1488
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("fileupload").AutoUpload(false).AllowedExtensions("image/*")
.Selected("onSelect").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { S
aveUrl = "https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "h
ttps://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove" }).Render()
</div>
@section PreScripts {
<script>
function onSelect(args) {
var uploadObj = document.getElementById("fileupload").ej2_instances[0];
if (event.type === 'drop') {
var allImages = ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bpg'];
var files = args.filesData;
var modifiedFiles = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (allImages.indexOf(file.type) === -1) {
file.status = 'File type is not allowed';
file.statusCode = '0';
}
modifiedFiles.push(file);
}
args.isModified = true;
args.modifiedFilesData = modifiedFiles.concat(uploadObj.filesData);
}
}
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
1489
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
.control_wrapper {
max-width: 505px;
margin: auto;
}
razor
required.cs
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Popups
1490
<div id='customBrowse' class="form-group dropUpload">
Drop image here...
<div id="uploadError"></div>
@Html.EJS().Uploader("fileupload").DropArea(".dropUploa
d").Selected("onFileSelect").AllowedExtensions("image/*").Multiple(true).AutoUpload(fal
se).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Cont
ent("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
<input type="text" id="upload" data-required-message="*
Choose your image to upload" required="" data-msg-containerid="uploadError" />
</div>
</div>
<div class="submitBtn">
<button type="button" class="submit-btn e-btn" id="submit-b
tn">Submit</button>
<div class="desc"><span>*This button is not a submit type a
nd the form submit handled from externally.</span></div>
</div>
</form>
@Html.EJS().Dialog("confirmationDialog").Buttons(ViewBag.dlgButtons
).Width("335px").Visible(false).Content("Your details has been updated successfully, Th
ank you").OverlayClick("closeDialog").Target("#control_wrapper").IsModal(true).Animatio
nSettings(new DialogAnimationSettings() { Effect = DialogEffect.Zoom }).Render()
</div>
</div>
</div>
</div>
<script>
var formID, confirm;
window.onload = function () {
inputElement = document.getElementById('upload');
formID = document.getElementById('form1');
confirm = document.getElementById("confirmationDialog").ej2_instances[0];
formObj = new ej.inputs.FormValidator(formID, options);
document.getElementById('customBrowse').onclick = () => {
document.getElementsByClassName('e-file-select-wrap')[0].querySelector('but
ton').click();
};
document.getElementById('submit-btn').onclick = () => {
onFormSubmit();
};
}
var options = {
customPlacement: function (inputElement, errorElement) {
inputElement = inputElement.closest('.form-group').querySelector('.error');
inputElement.parentElement.appendChild(errorElement);
},
rules: {
1491
'name': {
required: true
},
'email': {
required: true
},
'upload': {
required: true
},
'mobile': {
required: true
}
}
};
function onFileSelect(args) {
if (args.filesData.length > 0) {
if (document.getElementsByClassName('upload-image').length > 0) {
detach(document.getElementsByClassName('imgWrapper')[0]);
}
var imageTag = ej.base.createElement('IMG', { className: 'upload-image', at
trs: { 'alt': 'Image' } });
var wrapper = ej.base.createElement('span', { className: 'imgWrapper' });
wrapper.appendChild(imageTag);
var rootFile = document.getElementsByClassName('dropUpload')[0];
rootFile.insertBefore(wrapper, rootFile.firstChild);
readURL(wrapper, args.filesData[0]);
}
args.cancel = true;
}
1492
confirm.hide();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
ViewBag.button = new
{
content = "Ok",
isPrimary = true
};
return View();
}
}
}
If this method receives any files as arguments, those files only start to upload.
If it has no argument then all the selected files are will start to upload.
razor
dynamic-upload.cs
index.css
@using Syncfusion.EJ2
1493
<div class="col-lg-8 control-section">
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").AutoUpload(false).DropArea(".control-fl
uid").AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = @Url.Co
ntent("/Uploader/Save"), RemoveUrl = @Url.Content("Uploader/Remove") }).Render()
</div>
<span style=' padding-left: 40px; margin-top: 30px'>
<button id='first' class='e-btn e-control'>Upload 0th File</button>
</span>
<span style=' padding-left: 40px; margin-top: 30px'>
<button id='full' class='e-btn e-control'>Upload All Files</button>
</span>
</div>
<script>
window.onload = function () {
var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
document.getElementById('first').onclick = (args) => {
uploadObj.upload(uploadObj.getFilesData()[0]);
};
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1494
.control_wrapper {
max-width: 500px;
margin: auto;
}
.e-upload {
width: 100%;
position: relative;
margin-top: 15px;
margin-bottom: 15px;
}
.e-upload-actions {
display: none;
}
.e-btn {
text-transform: none;
}
razor
check-file-size.cs
index.css
@using Syncfusion.EJ2
1495
</div>
<script>
function onBeforeUpload(args) {
var uploadObj = document.getElementById("UploadFiles").ej2_instances[0];
// get the file size in bytes
var sizeInBytes = args.fileData.size;
// get the file size in standard format
alert("File size is: " + uploadObj.bytesToSize(sizeInBytes))
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
.control_wrapper {
max-width: 500px;
margin: auto;
}
1496
By using uploading event, you can get the file MIME type before uploading it to server. In the
below sample, file MIME type is shown in the alert box before file start to upload.
razor
mime-type.cs
index.css
@using Syncfusion.EJ2
<script>
function onBeforeUpload(args) {
// get the file MIME type
alert("File MIME type is: " + args.fileData.rawFile.type);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
1497
.control_wrapper {
max-width: 500px;
margin: auto;
}
razor
external-click.cs
index.css
@using Syncfusion.EJ2
<script>
window.onload = function () {
document.getElementById('browse').onclick = () => {
document.getElementsByClassName('e-file-select-wrap')[0].querySelector(
'button').click();
};
}
</script>
using System;
1498
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
}
}
.control_wrapper {
max-width: 500px;
margin: auto;
}
#dropArea {
border: 1px dashed #c3c3cc;
text-align: center;
padding: 20px 0 10px;
}
.e-file-select-wrap {
display: none;
}
You can retrieve the saved file path in the uploader success event and assign it to custom
attribute (data-file-name) value of the respective file list element to open the uploaded file. Click
the respective file element to create a new request along with saved file path using http header.
1499
In the server-side, get the file path from the header and open the file using process.start
method.
razor
server-side.cs
@using Syncfusion.EJ2
@section ControlsSection{
<div class="control_wrapper">
@Html.EJS().Uploader("UploadFiles").Success("onUploadSuccess").AsyncSetting
s(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://aspnetmvc.syncfu
sion.com/services/api/uploadbox/Save", RemoveUrl = "https://aspnetmvc.syncfusion.com/se
rvices/api/uploadbox/Remove" }).Render()
</div>
<script>
function onUploadSuccess(args) {
// fetching the generated li elements
var liElements = this.uploadWrapper.querySelectorAll('.e-upload-file-list');
for (var i = 0; i < liElements.length; i++) {
if (liElements[i].getAttribute('data-file-name') == args.file.name) {
liElements[i].addEventListener('click', () => { openFile(args, event) })
// File path have to update from server end in response status description.
liElements[i].setAttribute('file-path', args.e.target.statusText);
}
}
}
function openFile(args, e) {
if (!e.target.classList.contains('e-file-delete-btn') && !e.target.classList.contai
ns('e-file-remove-btn'))
{
var ajax = new XMLHttpRequest();
// create new request for open the selected file
ajax.open("POST", '/Home/openFile');
var liElements = document.getElementsByClassName('e-upload')[0].querySelectorAl
l('.e-upload-file-list');
for (var i = 0; i < liElements.length; i++) {
if (liElements[i].getAttribute('data-file-name') == args.file.name) {
// Added the file path in header to get it in server side.
ajax.setRequestHeader('filePath', liElements[i].getAttribute('file-path').t
oString());
}
}
1500
ajax.send();
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
public partial class UploaderController : Controller
{
public IActionResult DefaultFunctionalities()
{
return View();
}
public void Save() {
if (!System.IO.File.Exists(fileSavePath))
{
httpPostedFile.SaveAs(fileSavePath);
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
<!-- Sending the file path to client side -->
Response.StatusDescription = fileSavePath;
Response.End();
}
}
[AcceptVerbs("Post")]
public void openFile()
{
// Check whether the file is available in the corresponding location
if (System.IO.File.Exists(Request.Headers.GetValues("filePath").First()))
{
// This will open the selected file from server location in desktop
Process.Start(Request.Headers.GetValues("filePath").First());
}
}
}
}
1501