ChartJS4
Namespace: Wisej.Web.Ext.ChartJS4
Assembly: Wisej.Web.Ext.ChartJS4 (4.1.0.0)
ChartJS4 is a modernized, flexible Chart.js 4.x integration for Wisej.NET. Features improved serialization, better maintainability, and easier customization.
- C#
- VB.NET
public class ChartJS4 : Widget
Public Class ChartJS4
Inherits Widget
The chart is configured on the server through ChartType, Labels, DataSets and ChartOptions. Changing any of these properties (or the content of the observable LabelCollection and DataSetCollection) schedules a refresh of the client-side chart.
Use UpdateData to update only the data and labels with an animation, and the client-call methods (e.g. GetImage, ToBase64Image, IsDatasetVisible) to invoke the corresponding Chart.js API on the client. Methods that return a value from the client are asynchronous and deliver the result to a callback.
Example:
var chart = new ChartJS4 { Dock = DockStyle.Fill, ChartType = ChartType.Bar };
chart.Labels = new[] { "Jan", "Feb", "Mar" };
chart.DataSets.Add(new BarDataSet { Label = "Sales", Data = new object[] { 10, 20, 15 } });
chart.ChartOptions.Plugins.Title.Display = true;
chart.ChartOptions.Plugins.Title.Text = "Quarterly Sales";
this.Controls.Add(chart);
Constructors
ChartJS4()
Constructs a new instance of the ChartJS4 control.
The new control has an empty Labels and DataSets collection bound to it and a ChartType of Line.
Example:
var chart = new ChartJS4 { Dock = DockStyle.Fill };
this.Controls.Add(chart);
Properties
ChartOptions
ChartOptions: Returns or sets the chart options (Chart.js options).
Value: A ChartOptions instance. The getter lazily creates a new instance when none is set.
Nested option objects (e.g. Plugins, Scales) are also created lazily on first access, so they can be configured directly. When rendered, the options are serialized to JSON and properties that match their default values, empty objects and null values are removed. Assigning the property refreshes the chart.
Example:
var chart = new ChartJS4();
chart.ChartOptions.Plugins.Legend.Position = "bottom";
chart.ChartOptions.Plugins.Title.Display = true;
chart.ChartOptions.Plugins.Title.Text = "Monthly Revenue";
ChartType
ChartType: Returns or sets the ChartType. (Default: Line)
Value: One of the ChartType values. The default is Line.
The value is sent to Chart.js as the lower-case type of the chart configuration, unless Type is set, in which case that value takes precedence. Changing the value refreshes the chart.
Example:
var chart = new ChartJS4();
chart.ChartType = ChartType.Doughnut;
DataSets
DataSetCollection: Returns or sets the data sets for the chart (Chart.js data.datasets).
Value: A DataSetCollection of ChartDataSet objects (e.g. LineDataSet, BarDataSet, PieDataSet). Assigning null replaces it with a new empty collection.
DataSetCollection supports implicit conversion from ChartDataSet[] and List<ChartDataSet>. Assigning the property, or adding, removing or replacing data sets, refreshes the chart. Use UpdateData to push data changes with an animation.
Example:
var chart = new ChartJS4();
chart.DataSets.Add(new LineDataSet
{
Label = "Visitors",
Data = new object[] { 12, 19, 3, 5 },
BorderColor = Color.SteelBlue
});
InitScript
String: Returns the JavaScript initialization script of the chart widget.
Value: The content of the embedded startup.js resource, which creates the Chart.js instance on the client and implements the client-side methods invoked by this control.
The setter is ignored: the initialization script is always loaded from the embedded resource.
Example:
var script = chart.InitScript;
System.Diagnostics.Debug.WriteLine(script.Length);
Labels
LabelCollection: Returns or sets the labels for the chart data (Chart.js data.labels).
Value: A LabelCollection. Assigning null replaces it with a new empty collection.
LabelCollection supports implicit conversion from string[] and List<string>. Assigning the property, or adding, removing or changing labels, refreshes the chart.
Example:
var chart = new ChartJS4();
chart.Labels = new[] { "Mon", "Tue", "Wed" };
chart.Labels.Add("Thu");
Options
Object: Returns or sets the raw configuration object sent to the client widget.
Value: A dynamic object with the type, options, widgetFunctions and data fields passed to the Chart.js constructor.
This property is hidden from the designer. It is regenerated every time the control renders from ChartType, ChartOptions, WidgetFunctions, Labels and DataSets, so values assigned directly are overwritten. Use ChartOptions to configure the chart instead.
Example:
// Configure the chart through ChartOptions rather than Options.
chart.ChartOptions.Plugins.Legend.Position = "bottom";
chart.Update();
Packages
List<Package>: Returns the list of script packages required by the chart.
Value: The list of Package objects loaded on the client before the chart widget is created.
The list is built on first access and contains, in order:
- The embedded Chart.js 4 library, chartjs-plugin-datalabels, the chartjs-adapter-date-fns bundle and moment.js.
- Every embedded resource found in a
ChartJsPluginsfolder of any loaded assembly (other than this one). - The packages registered in PluginPackages.
Example:
foreach (var package in chart.Packages)
System.Diagnostics.Debug.WriteLine($"{package.Name}: {package.Source}");
PluginPackages
List<Package>: Returns the list of additional plugin packages to load with the chart. Use this to register custom Chart.js plugins globally (e.g., in Application_Start).
Value: A static, application-wide list of Package objects. Empty by default.
The packages are appended to Packages after the built-in scripts (Chart.js, chartjs-plugin-datalabels, the date-fns adapter and moment.js) and after the scripts discovered automatically from embedded resources placed in a ChartJsPlugins folder of any loaded assembly.
Because Packages is built the first time it is read, register plugin packages before the first chart is created.
Example:
ChartJS4.PluginPackages.Add(new Package
{
Name = "chartjs-plugin-zoom.js",
Source = "https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2/dist/chartjs-plugin-zoom.min.js"
});
WidgetFunctions
WidgetFunction[]: Returns or sets the widget functions that are passed to the chart. Widget functions allow JavaScript callbacks (e.g., scriptable options) to be defined server-side and called client-side using the (ctx)=>functionName pattern.
Value: An array of WidgetFunction objects, or null (the default).
Any string option value in ChartOptions or DataSets matching (args)=>Name is replaced on the client by a function whose parameters are args and whose body is the Source of the function with the same Name. The form (args)=>Name(values) instead invokes the function once and assigns the returned value.
Each function is also registered on the client widget under its name.
Example:
chart.WidgetFunctions = new[]
{
new ChartJS4.WidgetFunction
{
Name = "barColor",
Source = "return ctx.raw > 10 ? 'green' : 'red';"
}
};
chart.DataSets.Add(new BarDataSet { Data = new object[] { 5, 15, 8 }, BackgroundColor = "(ctx)=>barColor" });
Methods
Clear()
Clears the chart canvas.
Invokes the Chart.js chart.clear() method on the client. The chart is drawn again on the next update or render.
Example:
chart.Clear();
Destroy()
Destroys the chart instance, cleaning up any references and event listeners.
Invokes the Chart.js chart.destroy() method on the client. The control itself is not disposed; the chart is re-created the next time the control is refreshed (e.g. by calling Update()).
Example:
chart.Destroy();
GenerateLegend(callback)
Generates an HTML legend for the chart.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<String> | Callback that receives the HTML string, or an empty string if the chart is not available. |
Invokes chart.generateLegend() on the client. Note that Chart.js 3 and later no longer provide this method natively; it works only when it has been added to the chart (for example by a plugin), otherwise the client call fails. For custom HTML legends in Chart.js 4 consider an HTML legend plugin.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.GenerateLegend(html =>
{
this.htmlPanel1.Html = html;
});
GetActiveElements(callback)
Retrieves the currently active (hovered) elements.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<Object[]> | Callback that receives the array of active elements, or an empty array when there are none or the result could not be read. |
Invokes the Chart.js chart.getActiveElements() method on the client. Each element is a dynamic object that typically exposes the datasetIndex and index fields.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.GetActiveElements(elements =>
{
this.labelInfo.Text = $"{elements.Length} active element(s)";
});
GetDataVisibility(index, callback)
Retrieves the visibility state of data at the specified index.
| Parameter | Type | Description |
|---|---|---|
| index | Int32 | Index of the data. |
| callback | Action<Boolean> | Callback that receives true if the data at index is visible; otherwise false. |
Invokes the Chart.js chart.getDataVisibility(index) method on the client.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.GetDataVisibility(2, isVisible =>
{
AlertBox.Show(isVisible ? "Visible" : "Hidden");
});
GetImage(callback)
Retrieves the chart as a PNG image and passes it to the specified callback.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<Image> | Callback method that receives the Image of the chart, rendered over the control's BackColor, or null if the client could not produce an image. |
The image is produced asynchronously by the browser from the chart's canvas. See GetImageAsync for the awaitable version.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.GetImage(image =>
{
if (image != null)
image.Save(Application.MapPath("chart.png"));
});
GetImageAsync()
Asynchronously returns the chart as a PNG image.
Returns: Task<Image>. A task that completes with an Image of the chart rendered over the control's BackColor, or null if the client could not produce an image.
This is the awaitable version of GetImage. The image is produced by the browser from the chart's canvas.
Example:
private async void buttonSave_Click(object sender, EventArgs e)
{
var image = await this.chartJS41.GetImageAsync();
if (image != null)
this.pictureBox1.Image = image;
}
GetVisibleDatasetCount(callback)
Retrieves the number of visible datasets.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<Int32> | Callback that receives the count of visible datasets. |
Invokes the Chart.js chart.getVisibleDatasetCount() method on the client.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.GetVisibleDatasetCount(count =>
{
this.labelInfo.Text = $"{count} of {chart.DataSets.Count} datasets visible";
});
Hide(datasetIndex)
Hides a dataset and triggers the 'hide' animation.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset to hide. |
Invokes the Chart.js chart.hide(datasetIndex) method on the client. The chart is updated automatically; no additional update call is needed.
Example:
chart.Hide(0);
Hide(datasetIndex, dataIndex)
Hides a specific data element in a dataset and triggers the 'hide' animation.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset. |
| dataIndex | Int32 | Index of the data element. |
Invokes the Chart.js chart.hide(datasetIndex, dataIndex) method on the client.
Example:
// hide the third slice of a pie chart.
chart.Hide(0, 2);
IsDatasetVisible(datasetIndex, callback)
Checks if a dataset is visible.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset. |
| callback | Action<Boolean> | Callback that receives true if the dataset is visible; otherwise false. |
Invokes the Chart.js chart.isDatasetVisible(datasetIndex) method on the client.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.IsDatasetVisible(0, visible =>
{
chart.SetDatasetVisibility(0, !visible);
chart.UpdateChart();
});
OnChartClick(e)
Fires the ChartClick event.
| Parameter | Type | Description |
|---|---|---|
| e | ChartClickEventArgs | Event arguments. |
OnWebRender(config)
Renders the client component.
| Parameter | Type | Description |
|---|---|---|
| config | Object |
OnWidgetEvent(e)
Handles events fired by the widget.
| Parameter | Type | Description |
|---|---|---|
| e | WidgetEventArgs |
Render()
Triggers a redraw of all chart elements.
Invokes the Chart.js chart.render() method on the client. Unlike UpdateChart, it does not update elements with new data; use it to redraw after changes that don't affect the data.
Example:
chart.Render();
Reset()
Resets the chart to its state before the initial animation.
Invokes the Chart.js chart.reset() method on the client. A subsequent UpdateChart call runs the initial animation again.
Example:
chart.Reset();
chart.UpdateChart();
ResetChartType()
Resets the ChartType property to its default value (Line).
Used by the designer. This method assigns the backing field directly and does not refresh the chart.
Example:
chart.ResetChartType();
Resize(width, height)
Resizes the chart canvas. If no dimensions are provided, detects the new size from the container.
| Parameter | Type | Description |
|---|---|---|
| width | Nullable<Int32> | Optional width in pixels. |
| height | Nullable<Int32> | Optional height in pixels. |
Invokes the Chart.js chart.resize() method on the client. Both width and height must be specified to set an explicit size; if either is omitted the size is detected from the container.
Example:
chart.Resize();
chart.Resize(640, 480);
SetActiveElements(activeElements)
Sets the active (hovered) elements for the chart.
| Parameter | Type | Description |
|---|---|---|
| activeElements | Object[] | Array of active element specifications. Each item is an object with the datasetIndex and index fields. An empty array clears the active elements. |
Invokes the Chart.js chart.setActiveElements() method on the client. This sets the hover state of the elements; to also show the tooltip use the Chart.js tooltip API on the client.
Example:
chart.SetActiveElements(new object[]
{
new { datasetIndex = 0, index = 1 },
new { datasetIndex = 1, index = 1 }
});
SetDatasetVisibility(datasetIndex, visible)
Sets the visibility of a dataset.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset. |
| visible | Boolean | true to show, false to hide. |
Invokes the Chart.js chart.setDatasetVisibility(datasetIndex, visible) method on the client. The change is not drawn until the chart is updated, e.g. with UpdateChart.
Example:
chart.SetDatasetVisibility(1, false);
chart.UpdateChart();
ShouldSerializeChartType()
Determines whether the ChartType property should be serialized by the designer.
Returns: Boolean. true if ChartType differs from Line; otherwise false.
Used by the designer and the code serializer.
Example:
if (chart.ShouldSerializeChartType())
chart.ResetChartType();
Show(datasetIndex)
Shows a dataset and triggers the 'show' animation.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset to show. |
Invokes the Chart.js chart.show(datasetIndex) method on the client. The chart is updated automatically; no additional update call is needed.
Example:
chart.Show(0);
Show(datasetIndex, dataIndex)
Shows a specific data element in a dataset and triggers the 'show' animation.
| Parameter | Type | Description |
|---|---|---|
| datasetIndex | Int32 | Index of the dataset. |
| dataIndex | Int32 | Index of the data element. |
Invokes the Chart.js chart.show(datasetIndex, dataIndex) method on the client.
Example:
chart.Show(0, 2);
Stop()
Stops all currently running animations on the chart.
Invokes the Chart.js chart.stop() method on the client.
Example:
chart.Stop();
ToBase64Image(type, quality, callback)
Returns a base64 encoded string of the chart in the requested format.
| Parameter | Type | Description |
|---|---|---|
| type | String | Image MIME type (e.g., "image/png", "image/jpeg", "image/webp"). |
| quality | Double | Quality for lossy formats (0.0 to 1.0). |
| callback | Action<String> | Callback that receives the image as a data URL (data:<type>;base64,…), or an empty string if the chart is not available. |
Invokes the Chart.js chart.toBase64Image(type, quality) method on the client.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.ToBase64Image("image/jpeg", 0.8, dataUrl =>
{
this.pictureBox1.ImageSource = dataUrl;
});
ToBase64Image(callback)
Returns a base64 encoded string of the chart in PNG format.
| Parameter | Type | Description |
|---|---|---|
| callback | Action<String> | Callback that receives the PNG image as a data URL (data:image/png;base64,…), or an empty string if the chart is not available. |
Equivalent to calling ToBase64Image with "image/png" and a quality of 1.0.
Throws:
- ArgumentNullException
callback is
null.
Example:
chart.ToBase64Image(dataUrl =>
{
this.pictureBox1.ImageSource = dataUrl;
});
ToggleDataVisibility(index)
Toggles the visibility of data at the specified index across all datasets.
| Parameter | Type | Description |
|---|---|---|
| index | Int32 | Index of the data. |
Invokes the Chart.js chart.toggleDataVisibility(index) method on the client. This is mostly useful for charts where each data item has its own legend entry, such as pie, doughnut and polar area charts. The change is not drawn until the chart is updated, e.g. with UpdateChart.
Example:
chart.ToggleDataVisibility(2);
chart.UpdateChart();
UpdateChart(mode)
Triggers an update of the chart. This will update all scales, legends, and re-render the chart.
| Parameter | Type | Description |
|---|---|---|
| mode | String | The update mode. Can be "none", "resize", "reset", "hide", "show", "normal" or "active". When null or empty, the default Chart.js update is performed. |
Invokes the Chart.js chart.update(mode) method on the client. Use "none" to update without animation.
Example:
chart.UpdateChart();
chart.UpdateChart("none");
UpdateData(duration)
Causes the chart to update the data set and labels with animation.
| Parameter | Type | Description |
|---|---|---|
| duration | Int32 | Duration of the update animation in milliseconds. The default is 300. |
Sends the current DataSets and Labels to the client and updates the existing Chart.js data in place, allowing smooth transitions. The call is skipped when the control is already scheduled for a full refresh.
Example:
chart.DataSets[0].Data = new object[] { 5, 8, 13, 21 };
chart.UpdateData(500);
Events
ChartClick
ChartClickEventHandler Fired when the user clicks a data point on the chart.
The event is fired only at runtime and only when the click hits at least one chart element. Data contains a data array with one entry per element under the pointer, each with the pointIndex and dataSetIndex fields.
Example:
chart.ChartClick += (s, e) =>
{
var point = e.Data.data[0];
AlertBox.Show($"DataSet {point.dataSetIndex}, point {point.pointIndex}");
};