Column Template in ASP.NET MVC Grid Component
16 Dec 202424 minutes to read
Grid component provides a Template
option that allows you to display custom elements in a column instead of the field value. This can be useful when you need to display images, buttons, or other custom content within a column.
When using template columns, they are primarily meant for rendering custom content and may not provide built-in support for grid actions like sorting, filtering, editing. It is must to define the
Field
property of the column to perform any grid actions.
Render image in a column
To render an image in a grid column, you need to define a Template
for the column using the template property. The Template
property expects the HTML element or a function that returns the HTML element.
The following example demonstrates how to define a Template
for the Employee Image field that displays an image element. The Template
property is set to the HTML element that contains an image tag. You have utilized the src
and alt
attributes to an image tag.
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).Height("315").Columns(col =>
{
col.HeaderText("Employee Image").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Template("#template").Width("150").Add();
col.Field("FirstName").HeaderText("First Name").Width("100").Add();
col.Field("LastName").HeaderText("Last Name").Width("100").Add();
col.Field("City").HeaderText("City").Width("100").Add();
}).Render()
<style>
.image img {
height: 55px;
width: 55px;
border-radius: 50px;
box-shadow: inset 0 0 1px #e0e0e0, inset 0 0 14px rgba(0, 0, 0, 0.2);
}
</style>
<script id="template" type="text/x-template">
<div class="image">
<img src="/Content/images/Employees/${EmployeeID}.png" alt="${EmployeeID}" />
</div>
</script>
public IActionResult Index()
{
var Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
The
Template
option allows to define any HTML content within a column.
Render hyperlink in a column
The Grid component provides support for rendering hyperlink columns and performing routing on click using the Template
property. This feature is useful when displaying data that requires a link to another page or website.
The following example demonstrates, how to render hyperlink column in the Grid using the Template
property of the Column
. To define a Template
for the column, you can use the Template
with the a
tag to create the hyperlink.
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").Width(90).Add();
col.Field("LastName").HeaderText("Last Name").Width(150).Add();
col.Field("FirstName").HeaderText("First Name").Width(150).Template("#template").Add();
}).Render()
<script id="template" type="text/x-template">
<div>
<a href="https://www.google.com/search?q=${FirstName}" target="_blank">
${FirstName}
</a>
</div>
</script>
public IActionResult Index()
{
var Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
The window.open() method is a built-in JavaScript function that opens a new browser window or tab with the specified URL.
Render other components in a column
The column template has options to render a custom component in a grid column instead of a field value.
Render LineChart component in a column
The LineChart component of Syncfusion® provides an elegant way to represent and compare data over time. It displays data points connected by straight line segments to visualize trends in data.
In the following example, we have rendered the Sparkline Chart component in the Grid column by defining the Template
property.
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).QueryCellInfo("queryCellInfo").Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("FirstName").HeaderText("First Name").Width(150).Add();
col.HeaderText("Employee Performance Rating").Template("#columnTemplate").Width(280).Add();
}).Render()
<script id="columnTemplate" type="text/x-template">
<div id="spkline${EmployeeID}" style="height: 50px; width: 90%;"></div>
</script>
<script>
let lineData = [
[0, 6, -4, 1, -3, 2, 5],
[5, -4, 6, 3, -1, 2, 0],
[6, 4, 0, 3, -2, 5, 1],
[4, -6, 3, 0, 1, -2, 5],
[3, 5, -6, -4, 0, 1, 2],
[1, -3, 4, -2, 5, 0, 6],
[2, 4, 0, -3, 5, -6, 1],
[5, 4, -6, 3, 1, -2, 0],
[0, -6, 4, 1, -3, 2, 5],
[6, 4, 0, -3, 2, -5, 1],
];
function queryCellInfo(args) {
if (args.column.headerText === 'Employee Performance Rating') {
let sparklineContainer = args.cell.querySelector('#spkline' + args.data.EmployeeID);
let sparkline = new ej.charts.Sparkline({
height: '50px',
width: '90%',
lineWidth: 2,
valueType: 'Numeric',
fill: '#3C78EF',
dataSource: getSparkData('line', args.data.EmployeeID),
});
sparkline.appendTo(sparklineContainer);
}
}
function getSparkData(type, count) {
return lineData[count];
}
</script>
public IActionResult Index()
{
var Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
Render ColorPicker component in a column
The ColorPicker component of Syncfusion® provides a user-friendly way to select colors from a pre-defined color palette or custom colors. It can be used in a variety of scenarios such as picking a theme color or changing the color of an element on a page.
In the following code, we rendered the ColorPicker component in the Grid column by defining the Template
property.
function colorPicker(args) {
let inputElement = args.cell.querySelector('input')
let colorPickerObject = new ej.inputs.ColorPicker({
type: 'color',
mode: 'Palette',
change: change,
});
colorPickerObject.appendTo(inputElement);
}
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).EnableHover(false).QueryCellInfo("colorPicker").Height(315).Columns(col =>
{
col.Field("FirstName").HeaderText("First Name").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("LastName").HeaderText("Last Name").Width(150).Add();
col.Field("City").HeaderText("City").Width(150).Add();
col.HeaderText("Change the color of row").Template("#columnTemplate").Width(120).Add();
}).Render()
<script type="text/x-template" id="columnTemplate">
<input id="element" type="color" />
</script>
<script>
function colorPicker(args) {
let inputElement = args.cell.querySelector('input')
let colorPickerObject = new ej.inputs.ColorPicker({
type: 'color',
mode: 'Palette',
change: change,
});
colorPickerObject.appendTo(inputElement);
}
function change(args) {
let grid = document.querySelector('#Grid').ej2_instances[0];
let selectedRows = grid.getSelectedRows();
for (let row of selectedRows) {
row.style.backgroundColor = args.value;
}
grid.clearSelection();
}
</script>
public IActionResult Index()
{
var Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
Render DropDownList component in a column
To render a custom component in a grid column, you need to define a Template
for the column using the Template
property. In the following code, we rendered the DropDownList component in the Order Status column by defining the Template
property.
function dropdown(args) {
if (args.column.field === 'OrderStatus') {
let drop = new ej.dropdowns.DropDownList({
dataSource: dropData,
value: args.data['OrderStatus'],
popupHeight: 150,
popupWidth: 150,
});
drop.appendTo(args.cell.querySelector('#dropElement'));
}
}
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).QueryCellInfo("dropdown").Height(315).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width(100).Add();
col.Field("Freight").HeaderText("Freight").Width(90).Format("C2").Add();
col.Field("OrderStatus").HeaderText("Order Status").Template("#columnTemplate").Width(200).Add();
}).Render()
<script type="text/x-template" id="columnTemplate" >
<div id="dropElement" ></div>
</script>
<script>
let dropData = ['Order Placed', 'Processing', 'Delivered'];
function dropdown(args) {
if (args.column.field === 'OrderStatus') {
let drop = new ej.dropdowns.DropDownList({
dataSource: dropData,
value: args.data['OrderStatus'],
popupHeight: 150,
popupWidth: 150,
});
drop.appendTo(args.cell.querySelector('#dropElement'));
}
}
</script>
public IActionResult Index()
{
var Order = OrdersDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
Render Chip component in a column
The Grid component provides support for rendering Chips component in a column using the Template
property. This feature is useful when displaying data that requires a chip component to be rendered in a column.
In the following code, we rendered the Chips component in the Grid First Name column by defining the Template
property.
function queryCellInfo(args) {
if (args.column.field === 'FirstName') {
let chip = new ej.buttons.ChipList({
text: args.data[args.column.field],
});
chip.appendTo(args.cell.querySelector('#chipElement'));
}
}
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).EnableHover(false).QueryCellInfo("queryCellInfo").Height(315).Columns(col =>
{
col.Field("LastName").HeaderText("Last Name").Width(90).Add();
col.Field("City").HeaderText("City").Width(150).Add();
col.Field("FirstName").HeaderText("First Name").Template("#columnTemplate").Width(90).Add();
}).Render()
<script type="text/x-template" id="columnTemplate" >
<div id="chipElement" ></div>
</script>
<script>
function queryCellInfo(args) {
if (args.column.field === 'FirstName') {
let chip = new ej.buttons.ChipList({
text: args.data[args.column.field],
});
chip.appendTo(args.cell.querySelector('#chipElement'));
}
}
</script>
public IActionResult Index()
{
var Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
Render ProgressBar component in a column
The Syncfusion® Grid component supports rendering the Progress Bar component within a column using the Template
property. Displaying the Progress Bar
component in a grid column allows users to visually track the progress of tasks or operations associated with specific records. This feature is particularly useful for applications involving processes such as data loading, task completion, or other progressive activities.
In the following code, the Progress Bar
component render in the Grid Freight column by defining the Template
property.
function queryCellInfo(args) {
if (args.column.field === 'Freight') {
let percentageProgress = new ej.progressbar.ProgressBar({
type: 'Linear',
height: '60',
value: args.data['Freight'],
trackThickness:24,
progressThickness:20
});
percentageProgress.appendTo(args.cell.querySelector('#progressBarElement'));
}
}
@Html.EJS().Grid("FlatGrid").DataSource((IEnumerable<object>)ViewBag.dataSource).QueryCellInfo("queryCellInfo").Height(315).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width(150).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width(150).Add();
col.Field("Freight").HeaderText("Freight").Template("#columnTemplate").Width(150).Add();
}).Render()
<script type="text/x-template" id="columnTemplate" >
<div id="progressBarElement" ></div>
</script>
<script>
function queryCellInfo(args) {
if (args.column.field === 'Freight') {
let percentageProgress = new ej.progressbar.ProgressBar({
type: 'Linear',
height: '60',
value: args.data['Freight'],
trackThickness:24,
progressThickness:20
});
percentageProgress.appendTo(args.cell.querySelector('#progressBarElement'));
}
}
</script>
public IActionResult Index()
{
var Order = OrdersDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
Using condition template
The conditional column Template
allows you to display template elements based on specific conditions.
The following example demonstrates how to use the Template
property with the Template
element and add the condition to render the checkbox based on the value of the Discontinued field. The Discontinued field will render a checkbox in each row for which the value of the Discontinued field is true.
<script id="template" type="text/x-template">
<div class="template_checkbox">
${if(Discontinued)}
<input type="checkbox" checked> ${else}
<input type="checkbox"> ${/if}
</div>
</script>
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="315" >
<e-grid-columns>
<e-grid-column headerText="Discontinued" template="#template" textAlign="Center" width="150" ></e-grid-column>
<e-grid-column field="ProductID" headerText="Product ID" textAlign="Right" width="150"></e-grid-column>
<e-grid-column field="CategoryName" headerText="Category Name" width="150"></e-grid-column>
<e-grid-column field="ProductName" headerText="Product Name" width="150"></e-grid-column>
</e-grid-columns>
</ejs-grid>
<script id="template" type="text/x-template">
<div class="template_checkbox">
${if(Discontinued)}
<input type="checkbox" checked> ${else}
<input type="checkbox">
${/if}
</div>
</script>
public IActionResult Index()
{
var Category = CategoryDetails.GetAllRecords();
ViewBag.DataSource = Category;
return View();
}
You can use any template element or custom component instead of the checkbox in the conditional template based on your requirement.
How to get the row object by clicking on the template element
The Grid component allows you to retrieve the row object of the selected record when clicking on a Template
element. This feature can be useful when you need to perform custom actions based on the selected record.
In the following code, the button element is rendered in the Employee Data column and Click
event binding is used to call the showDetails method when the template element is clicked. The showDetails method is passed the data object as an argument, which allows you to access the selected row object and display it in the dialog popup.
@Html.EJS().Dialog("dialog").Header("Selected Row Details").Content("dialogContent").ShowCloseIcon(true).Visible(false).Width("50%").Render()
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Height(315).QueryCellInfo("queryCellInfo").Columns(col =>
{
col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(130).Add();
col.Field("FirstName").HeaderText("First Name").Width(120).Add();
col.HeaderText("Employee Data").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Template("#columnTemplate").Width(150).IsPrimaryKey(true).Add();
}).Render()
<script id="columnTemplate" type="text/x-template">
<button class='e-btn view-button'>View</button>
</script>
<script>
function queryCellInfo(args) {
let dialog = document.getElementById("dialog").ej2_instances[0];
if (args.column.headerText === 'Employee Data') {
args.cell.querySelector('.view-button').addEventListener('click', function () {
dialog.visible = true;
dialog.content =
`<p><b>EmployeeID:</b> ${args.data.EmployeeID}</p>
<p><b>FirstName:</b> ${args.data.FirstName}</p>
<p><b>LastName:</b> ${args.data.LastName}</p>`;
});
}
}
</script>
public IActionResult Index()
{
let Emp = EmployeeDetails.GetAllRecords();
ViewBag.DataSource = Emp;
return View();
}
Use custom helper inside the template
The Syncfusion® Grid allows you to use custom helpers inside the Template
property of a column. This feature allows you to create complex templates that can incorporate additional helper functions that are not available through the default Template
syntax.
To use the custom helper function inside a column template, you must first add the function to the template’s context.
The following example illustrates how to implement a custom helper function within the template property, utilizing the Template
property specifically for the Freight column.
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("CustomerID").HeaderText("Customer ID").Width(120).Add();
col.Field("Freight").HeaderText("Freight").Template("#template").Width(90).Format("C2").Add();
col.Field("OrderDate").HeaderText("Order Date").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(120).Format("yMd").Add();
}).Height("315").Render();
<script type="text/x-template" id="template">
${ formatCurrency(data.Freight) }
</script>
<script>
function formatCurrency(value) {
return '₹ ' + value.toFixed(3);
}
</script>
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
Custom helpers can only be used inside the template property of a column.
Dynamically adding template column
The Syncfusion® Grid component allows you to dynamically add template columns at runtime. This capability is particularly useful when the structure of the grid needs to be modified based on individual interactions or other dynamic conditions.
Dynamically adding template columns involves creating and inserting columns with custom templates after the grid has been initialized. This approach provides flexibility in presenting data in a highly customizable manner.
The following example demonstrates how to add template column using external button click. In this example, the ShipCountry column with a Dropdownlist is added in column Template
, and an icon is displayed in the column header by using the HeaderTemplate
for the ShipCountry column.
<div style="padding:0px 0px 20px 0px">
@Html.EJS().Button("addColumnButton").Content("Add Column").CssClass("e-outline").Render()
</div>
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).QueryCellInfo("queryCellInfo").Columns(col =>
{
col.Field("OrderID").HeaderText("Order ID").Width(80).Add();
col.Field("CustomerID").HeaderText("Customer Name").Width(100).Add();
col.Field("Freight").HeaderText("Freight").Width(80).Add();
}).Height("315").Render();
<script id="columnTemplate" type="text/x-template">
<input id="dropElement" type="text" />
</script>
<script id="headerTemplate" type="text/x-template">
<div><span class="e-icons e-location"></span> Ship Country</div>
</script>
<script>
let dropData = ['USA', 'Germany', 'Brazil', 'France', 'Belgium', 'Switzerland', 'Venezuela', 'Austria', 'Mexico'];
document.getElementById('addColumnButton').addEventListener('click', function () {
let grid = document.getElementById('Grid').ej2_instances[0];
let newColumn = {
field: 'ShipCountry',
headerText: 'Ship Country',
width: 100,
headerTemplate: '#headerTemplate',
template: '#columnTemplate'
};
grid.columns.push(newColumn);
grid.refreshColumns();
});
function queryCellInfo(args) {
if (args.column.field === 'ShipCountry') {
let dropDownList = new ej.dropdowns.DropDownList({
dataSource: dropData,
fields: { text: 'ShipCountry', value: 'ShipCountry' },
value: args.data['ShipCountry'],
index: 0
});
dropDownList.appendTo(args.cell.querySelector('#dropElement'));
}
}
</script>
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}