Cell in ASP.NET MVC Grid component

21 Oct 202420 minutes to read

In the Syncfusion ASP.NET MVC Grid, a cell refers to an individual data point or a unit within a grid column that displays data. It represents the intersection of a row and a column, and it contains specific information associated with that row and column. Each cell can display text, numbers, or other content related to the data it represents.

The Grid component allows you to customize the appearance and behavior of cells using various features and options. You can define templates, format cell values, enable or disable editing, and perform various other operations on the cells to create interactive and informative data grids in your web applications.

Displaying the HTML content

Displaying HTML content in a Grid can be useful in scenarios where you want to display formatted content, such as images, links, or tables, in a tabular format. Grid component allows you to display HTML tags in the Grid header and content. By default, the HTML content is encoded to prevent potential security vulnerabilities. However, you can enable the DisableHtmlEncode property by setting the value as false to display HTML tags without encoding. This feature is useful when you want to display HTML content in a grid cell.

In the following example, the EJ2 Toggle Switch Button component is added to enable and disable the DisableHtmlEncode property. When the switch is toggled, the Change event is triggered and the DisableHtmlEncode property of the column is updated accordingly. The refreshColumns method is called to refresh the grid and display the updated content.

<label style="padding: 10px 10px">
	Enable or disable HTML Encode
</label>
@Html.EJS().Switch("default").Change("onSwitchChange").Render()
@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
	{
	col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("CustomerID").HeaderText("<strong> Customer ID </strong>").Width("180").Add();
	col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

	}).Render()

	@section Scripts {
		<script type="text/javascript">
			function onSwitchChange(args) {
				var grid = document.getElementById("Grid").ej2_instances[0];
				if (args.checked) {
					grid.getColumnByField('CustomerID').disableHtmlEncode = false;
				} else {
					grid.getColumnByField('CustomerID').disableHtmlEncode = true;
				}
				grid.refreshColumns();
			}</script>
	}
public IActionResult Index()
{
    ViewBag.DataSource =  OrderDetails.GetAllRecords();
    return View();
}

Display HTML content

  • The DisableHtmlEncode property disables HTML encoding for the corresponding column in the grid.
  • If the property is set to true, any HTML tags in the column’s data will be displayed.
  • If the property is set to false, the HTML tags will be removed and displayed as plain text.
  • Disabling HTML encoding can potentially introduce security vulnerabilities, so use caution when enabling this feature.
  • If EnableHtmlSanitizer property of grid is set to true, then the content is sanitized to prevent any potential security vulnerabilities.
  • You can also disable the DisableHtmlEncode property of the column using getColumns method on Change event of Switch component.This is demonstrated in the below code snippet,
function change(args) {
  if (args.checked) {
    grid.getColumns()[1].disableHtmlEncode = false;
  } else {
    grid.getColumns()[1].disableHtmlEncode = true;
  }
  grid.refresh();
}

Autowrap the content

The auto wrap feature allows the cell content in the grid to wrap to the next line when it exceeds the boundary of the specified cell width. The cell content wrapping works based on the position of white space between words. To support the Autowrap functionality in Syncfusion Grid, you should set the appropriate Width for the columns. The column width defines the maximum width of a column and helps to wrap the content automatically.

To enable auto wrap, set the AllowTextWrap property to true. You can also configure the wrap mode by setting the WrapMode property.

Grid provides the below three options for configuring:

  • Both - This is the default value for wrapMode. With this option, both the grid Header and Content text is wrapped.
  • Header - With this option, only the grid header text is wrapped.
  • Content - With this option, only the grid content is wrapped.

The following example demonstrates how to set the AllowTextWrap property to true and specify the wrap mode as Content by setting the WrapMode property. Also change the WrapMode property to Content and Both on changing the dropdown value using the Change event of the DropDownList component.

<div style="display: flex">
		<label style="padding: 10px 10px 26px 0"> Change the wrapmode of auto wrap feature: </label>
		<span style="height:fit-content">
			@Html.EJS().DropDownList("Wrap").Width("180px").DataSource(new List<object> { "Both", "Content" }).Change("change").Render()
		</span>
	</div>
	@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).AllowTextWrap().Columns(col =>
{
	col.Field("Inventor").HeaderText("Inventor Name").Width("150").Add();

	col.Field("NumberOfPatentFamilies").HeaderText("Number of Patent Families").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("Country").HeaderText("Country").Width("150").Add();
	col.Field("Active").HeaderText("Active").Width("150").Add();

}).TextWrapSettings(text => { text.WrapMode(Syncfusion.EJ2.Grids.WrapMode.Content); }).Render()

<script>
	function change(args) {
		var grid = document.getElementById("Grid").ej2_instances[0];
		grid.textWrapSettings.wrapMode = args.value;
	}
</script>
public IActionResult Index()
{
    var Records = InventorDetails.GetAllRecords();
    ViewBag.DataSource = Records;
    return View();
}

Auto Wrap the content

  • If a column width is not specified, then the Autowrap of columns will be adjusted with respect to the grid’s width.
  • If a column’s header text contains no white space, the text may not be wrapped.
  • If the content of a cell contains HTML tags, the Autowrap functionality may not work as expected. In such cases, you can use the HeaderTemplate and Template properties of the column to customize the appearance of the header and cell content.

Customize cell styles

Customizing the grid cell styles allows you to modify the appearance of cells in the Grid control to meet your design requirements. You can customize the font, background color, and other styles of the cells. To customize the cell styles in the grid, you can use grid event, css, property or method support.

Using event

To customize the appearance of the grid cell, you can use the QueryCellInfo event of the grid. This event is triggered when each header cell is rendered in the grid, and provides an object that contains information about the header cell. You can use this object to modify the styles of the header cell.

The following example demonstrates how to add a QueryCellInfo event handler to the grid. In the event handler, checked whether the current column is Freight field and then applied the appropriate CSS class to the cell based on its value.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
	{
	col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
	col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

	}).EnableHover(false).AllowSelection(false).QueryCellInfo("customizeCell").Render()

@section Scripts {
	<style>
	.below-30 {
	background-color: orangered;
	}
	.below-80 {
	background-color: yellow;
	}
	.above-80 {
	background-color: greenyellow;
	}
	</style>
	<script type="text/javascript">
		function customizeCell(args) {
			console.log(args.column);
			if (args.column.field === 'Freight') {
				var freightData = args.data['Freight'];
				if (freightData <= 30) {
					args.cell.classList.add('below-30');
				} else if (freightData > 30 && freightData < 80) {
					args.cell.classList.add('below-80');
				} else {
					args.cell.classList.add('above-80');
				}
			}
		}</script>
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Customize cell using event

  • The QueryCellInfo event is triggered for every cell of the grid, so it may impact the performance of the grid whether used to modify a large number of cells.

Using CSS

You can apply styles to the cells using CSS selectors. The Grid provides a class name for each cell element, which you can use to apply styles to that specific cell or cells in a particular column. The e-rowcell class is used to style the row cells, and the e-selectionbackground class is used to change the background color of the selected row.

.e-grid td.e-cellselectionbackground {
  background: #9ac5ee;
  font-style: italic;
}

The following example demonstrates how to customize the appearance of a specific row in the grid on selection using className.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
		{
			col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
			col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add();
			col.Field("OrderDate").HeaderText("Order Date").Width("130").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
			col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
			col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
		}).SelectionSettings(select => select.Mode(Syncfusion.EJ2.Grids.SelectionMode.Cell).Type(Syncfusion.EJ2.Grids.SelectionType.Multiple)).Render()

@section Scripts {
	<style>
			.e-grid td.e-cellselectionbackground {
				background: #9ac5ee;
				font-style: italic;
			}
	</style>
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Customize cell using css

Using property

To customize the style of grid cells, define CustomAttributes property to the column definition object. The CustomAttributes property takes an object with the name-value pair to customize the CSS properties for grid cells. You can also set multiple CSS properties to the custom class using the CustomAttributes property.

.custom-css {
  background: #d7f0f4;
  font-style: italic;
  color:navy
}

Here, setting the CustomAttributes property of the ShipCity column to an object that contains the CSS class ‘custom-css’. This CSS class will be applied to all the cells in the ShipCity column of the grid.

		col.Field("ShipCity").HeaderText("Ship City").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).CustomAttributes(new { @class = "custom-css" }).Add();

The following example demonstrates how to customize the appearance of the OrderID and ShipCity columns using custom attributes.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
	{
		col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).CustomAttributes(new { @class = "custom-css" }).Add();
		col.Field("CustomerID").HeaderText("Customer ID").Width("150").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
		col.Field("ShipCity").HeaderText("Ship City").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).CustomAttributes(new { @class = "custom-css" }).Add();
		col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();
	}).Render()

@section Scripts
{
	<style>
	.custom-css{
		background: #d7f0f4;
		font-style: italic;
		color: navy
	}
	</ style >
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Customize cell using property

Custom attributes can be used to customize any cell in the grid, including header and footer cells.

Using methods

The Grid provides below methods to customize the appearance of the grid columns header and cell:

  1. getHeaderContent: The getHeaderContent method is used to customize the appearance of the column header in the grid and accessing the header element using the querySelector method and applying the style using the style property of the cell element.

  2. getCellFromIndex: The getCellFromIndex method is used to customize the appearance of a specific cell in the grid by specifying the index of the row and column for which you want to customize the appearance.

The following example demonstrates how to use getColumnHeaderByIndex and getCellFromIndex methods to customize the appearance of the CustomerID column header and specific cell inside the DataBound event of the grid.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
	{
	col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("CustomerID").HeaderText("Customer ID").Width("250").Add();
	col.Field("ShipCity").HeaderText("ShipCity").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

	}).DataBound("dataBound").Render()

@section Scripts {
	<script type="text/javascript">
		function dataBound() {
			var grid = document.getElementById("Grid").ej2_instances[0];
			var header = grid.getHeaderContent().querySelector('.e-headercell');
			header.style.backgroundColor = 'red';
			header.style.color = 'white';
			var cell = grid.getCellFromIndex(1, 2);
			cell.style.background = '#f9920b';
			cell.style.color = 'white';
		}</script>
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Customize cell using property

Make sure to pass the correct row and column indices to getCellFromIndex method, or else the appearance of the wrong cell might get customized.

Clip Mode

The clip mode feature is useful when you have a long text or content in a grid cell, which overflows the cell’s width or height. It provides options to display the overflow content by either truncating it, displaying an ellipsis or displaying an ellipsis with a tooltip. You can enable this feature by setting ClipMode property to one of the below available options.

There are three types of ClipMode available:

  • Clip: Truncates the cell content when it overflows its area.
  • Ellipsis: Displays ellipsis when the cell content overflows its area.
  • EllipsisWithTooltip: Displays ellipsis when the cell content overflows its area, also it will display the tooltip while hover on ellipsis is applied. Also it will display the tooltip while hover on ellipsis is applied.

The following example demonstrates, how to set the ClipMode property to Clip , Ellipsis and EllipsisWithTooltip for the Main Fields of Invention column, on changing the dropdown value using the Change event of the DropDownList component. The refresh method is used to refresh the grid and display the updated content.

<div style="display: flex">
		<label style="padding: 10px 10px 26px 0">Change the clip mode: </label>
		<span style="height:fit-content">
			@Html.EJS().DropDownList("ClipMode").Width("180px").DataSource(new List<object> { "Clip", "Ellipsis", "EllipsisWithTooltip" }).Change("change").Render()
		</span>

	</div>
	@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).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();
	  }).Render()

<script>
	function change(args) {
		var grid = document.getElementById("Grid").ej2_instances[0];
		grid.getColumnByField('MainFieldsOfInvention').clipMode = args.value;
		grid.refresh();
	}
</script>
c
public IActionResult Index()
{
    var Order = InventorDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    ViewBag.dropdownData = new string[] { "Clip", "Ellipsis", "EllipsisWithTooltip" };
    return View();
}

Clip Mode

  • By default, ClipMode value is Ellipsis.
  • If you set the Width property of a column, the clip mode feature will be automatically applied to that column if the content exceeds the specified width.
  • Be careful when using the Clip mode, as it may result in important information being cut off. It is generally recommended to use the Ellipsis or EllipsisWithTooltip modes instead.

Tooltip

The Syncfusion Grid allows you to display information about the grid columns to the user when they hover over them with the mouse.

Render bootstrap tooltip in grid cells

The Grid control allows rendering Bootstrap tooltips in the cells. To enable this feature, you need to add the Bootstrap CDN link and call the tooltip() method to initialize the tooltip.

This is demonstrated in the sample code below which shows how to enable Bootstrap tooltip for the CustomerID field using Template property in grid cells,

Step 1: Add the CDN link of Bootstrap in the _Layout.cshtml file. Place the link tag in the head for the CSS.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

Step 2: The following code demonstrates how to render Bootstrap tooltip for the CustomerID field with Template on grid cells.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Columns(col =>
	{
	col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("CustomerID").HeaderText("Customer ID").Width("250").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Template("#template").Add();
	col.Field("ShipCity").HeaderText("ShipCity").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).Render()

@section Scripts {
	<script id="template" type="text/x-template">
		<span data-toggle="tooltip" title="${CustomerID}" data-container="body" data-placement="left" data-delay='{"show":"800", "hide":"300"}'><i class="fas fa-pencil-alt"></i>${CustomerID}</span>
	</script>
	<script>
		$(document).ready(function () {
			$('[data-toggle="tooltip"]').tooltip();
		});
	</script>
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

The following screenshot represents the Bootstrap tooltip for the CustomerID field,

 Render bootstrap tooltip in grid

  • The Bootstrap CDN link must be added to the HTML file.

Display custom tooltip for columns

The Grid provides a feature to display custom tooltips for its columns using the EJ2 Tooltip component. This allows you to provide additional information about the columns when the user hovers over them.

To enable custom tooltips for columns in the Grid, you can render the Grid control inside the Tooltip component and set the target as .e-rowcell. This will display the tooltip when hovering over the grid cells.

Change the tooltip content for the grid cells by using the following code in the BeforeRender event.

 beforeRender(args): void {
    if (args.target.classList.contains('e-rowcell')) {
        // event triggered before render the tooltip on target element.
        this.tooltip.content = 'This is value "' + args.target.innerText + '" ';
    }
  }

The following example demonstrates how to customize the tooltip content for the grid cells by using the BeforeRender event of the EJ2 Tooltip component.

@Html.EJS().Tooltip("Tooltip").Target(".e-rowcell").ContentTemplate(@<div>
	@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
	{
	   col.Field("OrderID").HeaderText("Order ID").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	   col.Field("CustomerID").HeaderText("Customer Name").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	   col.Field("OrderDate").HeaderText("Order Date").Width("130").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Format("yMd").Add();
	   col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
	   col.Field("ShipCountry").HeaderText("Ship Country").Width("120").Add();

	}).Render()
</div>).BeforeRender("beforeRender").Render()

<script>
	function beforeRender(args) {
		var tooltip = document.getElementById("Tooltip").ej2_instances[0]
		if (args.target.classList.contains('e-rowcell')) {
			// event triggered before render the tooltip on target element.
			tooltip.content = 'The value is "' + args.target.innerText + '" ';
		}
	}
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Display custom tooltip

Grid lines

The GridLines in a grid are used to separate the cells with horizontal and vertical lines for better readability. You can enable the grid lines by setting the GridLines property to one of the following values:

Modes Actions
Both Displays both the horizontal and vertical grid lines.
None No grid lines are displayed.
Horizontal Displays the horizontal grid lines only.
Vertical Displays the vertical grid lines only.
Default Displays grid lines based on the theme.

The following example demonstrates how to set the GridLines property based on changing the dropdown value using the Change event of the DropDownList component.

<div style="display: flex">
		<label style="padding: 10px 10px 26px 0">Change the Grid lines: </label>
		<span style="height:fit-content">
			@Html.EJS().DropDownList("GridLines").Width("180px").DataSource(new List<object> { "Default", "Both", "Horizontal", "Vertical", "None" }).Change("change").Render()
		</span>

	</div>
	@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).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();
	  }).Render()

<script>
	function change(args) {
		var grid = document.getElementById("Grid").ej2_instances[0];
		grid.gridLines = args.value;
	}
</script>
public IActionResult Index()
{
    var Order = InventoryDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    ViewBag.dropdownData = new string[] { "Default", "Both", "Horizontal", "Vertical", "None" };
    return View();
}

Grid Lines