How to integrate a JavaScript Pivot Table into a Blazor web application?
Introduction
Integrating a Syncfusion JavaScript Pivot Table into a Blazor web application significantly enhances the data analysis capabilities. This is achievable by using a JavaScript interop that invokes JavaScript methods from the Blazor web application. In this article, we will guide you through the procedure, providing a step-by-step example.
Step 1: Create an HTML element
First, you must place a div
element on your razor page (i.e., Index.razor), where the Pivot Table will be displayed. The id
attribute of the div
should be designated as a unique identifier to ascertain that JavaScript initializes the Pivot Table in this specific element correctly.
Here is a code example of how you can create an HTML div element:
[index.razor]
@page "/"
<div class="control-section">
<div class="content-wrapper pivot-container">
<div id="@ID" class="pivot-table"></div>
</div>
</div>
[index.razor.cs]
public partial class Index
{
private string ID = "PivotTable";
}
Step 2: Defining the data source
After creating the HTML div element, it is necessary to define the data source in your Razor page (i.e., Index.razor.cs) to configure the pivot table control. This can be done by creating a class that represents the data structure, in this case, ProductDetails
. This class should contain properties that represent the necessary data fields for the pivot table, such as “Sold”, “Amount”, “Products”, “Year”, and “Quarter”.
Here is an example of how to define a data source for the pivot table using a class called ProductDetails
in the razor page:
[index.razor.cs]
namespace BlazorApp1.Pages
{
public partial class Index
{
public class ProductDetails
{
// Define properties that represent the data fields
public int Sold { get; set; }
public double Amount { get; set; }
public string Country { get; set; }
public string Products { get; set; }
public string Year { get; set; }
public string Quarter { get; set; }
// Method to generate a list of product details
public static List<ProductDetails> GetProductData()
{
// Add product details to the list
List<ProductDetails> productData = new List<ProductDetails>();
productData.Add(new ProductDetails { Sold = 31, Amount = 52824, Country = "France", Products = "Mountain Bikes", Year = "FY 2015", Quarter = "Q1" });
// ... additional data reference
return productData;
}
}
}
}
Step 3: Serialize the data source
After you have determined the necessary data source, you will need to convert it into a JSON string. This conversion is essential for the JavaScript code to accurately read and use the data within the Pivot Table. This can be accomplished by using the JsonSerializer.Serialize
method within the OnInitializedAsync lifecycle method.
Here is an example of how to convert a data source into JSON format:
[index.razor.cs]
using System.Text.Json;
namespace BlazorApp1.Pages
{
public partial class Index
{
protected List<ProductDetails> Data { get; set; }
private string dataSource;
protected override async Task OnInitializedAsync()
{
// Assuming GetProductData is a static method that returns a list of ProductDetails.
Data = ProductDetails.GetProductData();
// Serialize the Data list to a JSON string.
dataSource = JsonSerializer.Serialize(Data);
}
}
}
Step 4: Add stylesheet and script resources
Before initializing the pivot table, you need to include the Syncfusion styles and scripts in your ~/Pages/Host.cshtml
file. This is typically done by adding the references inside the <head>
tag of the ~/Pages/Host.cshtml
file.
Here is the code snippet how you can include the styles and scripts resources:
[Host.cshtml]
<!-- Syncfusion javascript control styles -->
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/24.1.41/fluent.css" />
<!-- Syncfusion javascript control scripts -->
<script src="https://cdn.syncfusion.com/ej2/24.1.44/dist/ej2.min.js" type="text/javascript"></script>
Step 5: Configure the javascript pivot table control
Once you’ve included the necessary references, you’ll need to create a JavaScript file (e.g., pivotview.js) and define a function called integratePivotTable
. This function takes the ID of the DOM element and the serialized data as arguments. Within this function, initialize the pivot view control with serialized data from the Blazor web application.
[pivotview.js]
function integratePivotTable(id, data) {
// Parse the incoming data from a JSON string into an object
var pivotData = JSON.parse(data);
// Initialize pivot table component
var pivotTableObj = new ej.pivotview.PivotView({
// Configure the data source settings for the pivot table
dataSourceSettings: {
// Assign the parsed data here
dataSource: pivotData
columns: [{ name: 'Year' }, { name: 'Quarter' }],
values: [{ name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount'}],
rows: [{ name: 'Country' }, { name: 'Products' }],
},
width: '100%',
height: 290,
gridSettings: { columnWidth: 140 },
showFieldList: true
});
// Append the pivot table to the DOM element with the specified ID
pivotTableObj.appendTo('#' + id);
}
In the code example mentioned, we parse the retrieved data into a JavaScript object within the integratePivotTable
method. Following this, we initialize pivot table component using ej.pivotview.PivotView() instance and assign the parsed data to the dataSource property of the dataSourceSettings. Subsequently we added the fields to row, column, values axes. Finally we appended this pivot table instance to the retrieved DOM element using the appendTo
method. This action will render the pivot table in the Blazor web application.
Step 6: Include the JavaScript file in your Blazor application
Once you have initialized the pivot table in the pivotview.js file, you must reference it within the <body>
tag of the ~/Pages/Host.cshtml
file. Here’s an example of how you can accomplish this:
[Host.cshtml]
<html>
<body>
<script src="scripts/pivotview.js"></script>
</body>
</html>
Step 7: Invoke JavaScript method in razor page
Once you’ve included the pivotview.js file, you can invoke the integratePivotTable
method on your razor page (i.e., Index.razor.cs) using JavaScript interop. Below is an example of how you can invoke the integratePivotTable
method in your razor file:
[Index.razor]
using Microsoft.JSInterop;
namespace BlazorApp1.Pages
{
public partial class Index
{
// Inject the IJSRuntime service that allows invoking JavaScript method
[Inject]
protected IJSRuntime JSRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Here we we ensure the JavaScript method is only called once after the component is first rendered.
if(firstRender) {
// Invoking the 'integratePivotTable' JavaScript method and passing the ID and Serialized dataSource as parameters
await JSRuntime.InvokeVoidAsync("integratePivotTable", ID, dataSource);
}
}
}
}
In the above code, we first injected the IJSRuntime service using the [Inject]
attribute. This service allows us to interact with JavaScript code from our razor page. Subsequently, within the OnAfterRenderAsync
lifecycle method, we checked if it was the first render of the razor component by using the firstRender parameter. If this is indeed the first render, we used the InvokeVoidAsync
method to invoke the integratePivotTable
JavaScript method, passing the ID of the DOM element and the serialized data as parameters. This action integrates the JavaScript pivot table into a Blazor web application.
Step 8: Run your application
Now, compile and run your Blazor project you can see that the Syncfusion JavaScript Pivot Table component has been integrated and is functioning within your Blazor web application.
The following screenshot portrays the results of the code snippets mentioned above,
You can refer to this GitHub sample for a practical demonstration of this code.
Conclusion
I hope you enjoyed learning how to to integrate a JavaScript Pivot Table into a Blazor web application.
You can also refer to our JavaScript Pivot Table feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Pivot Table example to understand how to create and manipulate data.
For current customers, you can check out our components on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!