Cell Template

The Grid View control allows you to customize layouts of its visual elements using the template technology. This demo demonstrates the use of a template to display cells within the 'Details' column. The template contains a link labeled 'Details'. Clicking this link displays a popup window containing additional information about an employee.

To customize a Grid View's cell, call a column's DataItemTemplate method. A delegate passed to this method takes a parameter that provides access to settings specific to the template container, such the current row's KeyValue and VisibleIndex, the current Column, etc. Template content is specified in the Razor View Engine syntax.

First Name
Last Name
Title
Birth Date
Hire Date
NancyDavolioSales Representative12/8/19785/1/2005
AndrewFullerVice President, Sales2/19/19658/14/1992
JanetLeverlingSales Representative8/30/19854/1/2002
MargaretPeacockSales Representative9/19/19735/3/1993
StevenBuchananSales Manager3/4/195510/17/1993
MichaelSuyamaSales Representative7/2/198110/17/1999
RobertKingSales Representative5/29/19601/2/1994
LauraCallahanInside Sales Coordinator1/9/19853/5/2004
AnneDodsworthSales Representative1/27/198011/15/2004
@model IEnumerable
@Html.Partial("Templates/CellTemplatePartial")
@(Html.DevExpress()
    .BootstrapPopupControl("detailsModal")
    .SettingsAdaptivity(settings => settings.Mode(PopupControlAdaptivityMode.Always).VerticalAlign(PopupAdaptiveVerticalAlign.WindowCenter))
    .PopupAnimationType(AnimationType.None)
    .CloseAnimationType(AnimationType.None)
)
@model IEnumerable
@(Html.DevExpress()
    .BootstrapGridView<DevExpress.AspNetCore.DemoModels.Employee>("gridWithCellTemplates")
    .ClientSideEvents(events => events.Init("initMoreButtons").EndCallback("initMoreButtons"))
    .KeyFieldName(m => m.EmployeeID)
    .Columns(columns => {
    columns.Add(m => m.FirstName);
    columns.Add(m => m.LastName);
        ...
    columns.Add()
        .Caption(" ")
        .Width(50)
        .DataItemTemplate(t => @<text>
                <button type="button" class="btn btn-link more-info" data-key="@t.VisibleIndex">Details...</button>
            </text>);
    })
    ...
    .Bind(Model))
using Microsoft.AspNetCore.Mvc;
namespace DevExpress.AspNetCore.Demos {
    public partial class GridViewController : Controller {
        public ActionResult CellTemplate() {
            return PartialView("Templates/CellTemplate", NorthwindContext.Employees);
        }
        public ActionResult CellTemplatePartial() {
            return PartialView("Templates/CellTemplatePartial", NorthwindContext.Employees);
        }
    }
}
function initMoreButtons(s, e) {
    $(s.GetMainElement()).find(".more-info").click(function () {
        if(s.InCallback()) return;
        var $btn = $(this);
        s.GetRowValues($btn.attr("data-key"), 'FirstName;LastName;Title;Notes', function (values) {
            detailsModal.SetHeaderText(values[0] + " " + values[1] + " - " + values[2]);
            detailsModal.SetContentHtml(values[3]);
            detailsModal.Show();
        });
    });
}

Preview Template

Preview Rows are used to display large memo fields or custom data across all the columns within a Grid View. This demo illustrates how to create a template to display images along with textual content within preview rows.

To set Preview Rows' content, use the PreviewRow method (available through Templates).

First Name Last Name Birth Date Title Hire Date
NancyDavolio12/8/1978Sales Representative5/1/2005
Nancy received a BA degree in psychology from Colorado State University in 2000. She also completed &quot;The Art of the Cold Call&quot; course. She is a member of Toastmasters International.
AndrewFuller2/19/1965Vice President, Sales8/14/1992
Andrew received his BTS commercial in 1987 and a Ph.D. in international marketing at the University of Dallas in 1994. He speaks French and Italian fluently, and reads German. He joined the company as a sales representative. After that, he was promoted to sales manager in January 2005 and vice president of sales in March 2006. Andrew is a member of the Sales Management Round table, Seattle Chamber of Commerce, and Pacific Rim Importers Association.
JanetLeverling8/30/1985Sales Representative4/1/2002
Janet received a BS degree in chemistry at Boston College in 2006. She also completed a certificate program in food retailing management. Janet was hired as a sales associate in 2013 and promoted to sales representative in February 2014.
@using DevExpress.AspNetCore.DemoModels
@model IEnumerable
@(Html.DevExpress()
    .BootstrapGridView<Employee>("gridWithPreviewTemplate")
    .Settings(settings => settings.ShowPreview(true))
    .PreviewFieldName(m => m.Notes)
    .KeyFieldName(m => m.EmployeeID)
    .Columns(columns => {
        ...
    })
    .Templates(templates => templates
        .PreviewRow(t => @<text>
            <div class="media">
                @(Html.DevExpress()
                    .BootstrapBinaryImage()
                    .Name("preview" + t.VisibleIndex)
                    .CssClasses(css => css.Control("rounded-circle"))
                    .Value(t.Eval(m => m.Photo)))
                <div class="media-body">@t.Text</div>
            </div>
        </text>))
    ...
    .Bind(Model))

Data Attributes in Header

The Grid View uses the data-toggle attribute to assign actions to DOM elements displayed within complex controls declaratively. In your applications, you can use the data-toggle attribute to assign one of the predefined actions to a control displayed within a template.

This demo demonstrates the use of the data-toggle attribute to declaratively assign an action to a control displayed within a column header template. Button's data-toggle attribute is set to gridview-column-filterpopup to show the header filter popup.

Country
City Company Name Contact Name Address
ArgentinaBuenos AiresCactus Comidas para llevarPatricio SimpsonCerrito 333
ArgentinaBuenos AiresOcéano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-A
ArgentinaBuenos AiresRancho grandeSergio GutiérrezAv. del Libertador 900
AustriaGrazErnst HandelRoland MendelKirchgasse 6
AustriaSalzburgPiccolo und mehrGeorg PippsGeislweg 14
BelgiumBruxellesMaison DeweyCatherine DeweyRue Joseph-Bens 532
BelgiumCharleroiSuprêmes délicesPascale CartrainBoulevard Tirou, 255
BrazilSao PauloComércio MineiroPedro AfonsoAv. dos Lusíadas, 23
BrazilSao PauloFamilia ArquibaldoAria CruzRua Orós, 92
BrazilCampinasGourmet LanchonetesAndré FonsecaAv. Brasil, 442
@using DevExpress.AspNetCore.DemoModels
@model IEnumerable
@(Html.DevExpress()
    .BootstrapGridView<Customer>("gridDataAttributesInHeader")
    .KeyFieldName(m => m.CustomerID)
    .Columns(columns => {
        columns.Add(m => m.Country)
            .SortIndex(0)
            .Settings(s => s.AllowHeaderFilter(true))
            .HeaderTemplate(header => @<text>
                <div>
                    <a data-toggle="gridview-column-sort" aria-label="First Name header column. Sorted ascending" href="javascript:;">@header.Column</a>
                    <div>
                        <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="gridview-column-filterpopup">
                            @{ var filterExpression = ((IBootstrapGridViewDataColumn)header.Column).FilterExpression; }
                            @(string.IsNullOrEmpty(filterExpression) ? "Filter" : filterExpression)
                            <span class="caret"></span>
                        </button>
                    </div>
                </div>
            </text>);
        ...
    })
    ...
    .Bind(Model))

Data Attributes in Row

This demo demonstrates the use of the data-toggle attribute to declaratively assign an action to a control displayed within a data item template. In this demo, each data row displays custom Edit and Delete buttons. The Title Panel template contains a custom button allowing to create a new data row.

To implement CRUD data operations, this demo use the following value of data-toggle attributes:

For mode information about the use of data-toggle attributes in the Grid View, refer to the Data-Toggle Attribute article.

Customers
Company Name Contact Name Country City Address
Alfreds Futterkiste Maria AndersGermanyBerlinObere Str. 57
Ana Trujillo Emparedados y helados Ana TrujilloMexicoMéxico D.F.Avda. de la Constitución 2222
Antonio Moreno Taquería Antonio MorenoMexicoMéxico D.F.Mataderos 2312
Around the Horn Thomas HardyUKLondon120 Hanover Sq.
Berglunds snabbköp Christina BerglundSwedenLuleåBerguvsvägen 8
Blauer See Delikatessen Hanna MoosGermanyMannheimForsterstr. 57
Blondesddsl père et fils Frédérique CiteauxFranceStrasbourg24, place Kléber
Bólido Comidas preparadas Martín SommerSpainMadridC/ Araquil, 67
Bon app' Laurence LebihanFranceMarseille12, rue des Bouchers
Bottom-Dollar Markets Elizabeth LincolnCanadaTsawassen23 Tsawassen Blvd.
@using DevExpress.AspNetCore.DemoModels
@model IEnumerable
@(Html.DevExpress()
    .BootstrapGridView<Customer>("gridToggleInRows")
    .KeyFieldName(m => m.CustomerID)
    .Columns(columns => {
        columns
            .Add(m => m.CompanyName)
            .DataItemTemplate(t => @<text>
                @Html.Raw(t.Text)
                <button type="button" class="btn btn-link" data-toggle="gridview-datarow-edit">
                    <span class="fa fa-pencil"></span>
                </button>
                <button type="button" class="btn btn-link" data-toggle="gridview-datarow-delete">
                    <span class="fa fa-trash"></span>
                </button>
            </text>);
        ...
    })
    .Settings(settings => settings.ShowTitlePanel(true))
    .Templates(templates => templates
        .TitlePanel(@<text>
            Customers
            <button type="button" class="btn btn-link" data-toggle="gridview-newrow">
                <span class="fa fa-plus"></span>
            </button>
        </text>))
    .Routes(routes => routes
        .MapRoute(r => r
            .Controller("GridView")
            .Action("DataToggleInRows"))
    .MapRoute(r => r
            .RouteType(GridViewRouteType.AddRow)
            .Controller("GridView")
            .Action("DataToggleInRowsAddRow"))
        .MapRoute(r => r
            .RouteType(GridViewRouteType.UpdateRow)
            .Controller("GridView")
            .Action("DataToggleInRowsUpdateRow"))
        .MapRoute(r => r
            .RouteType(GridViewRouteType.DeleteRow)
            .Controller("GridView")
            .Action("DataToggleInRowsDeleteRow")))
    .Bind(Model))
using Microsoft.AspNetCore.Mvc;
using System;
namespace DevExpress.AspNetCore.Demos {
    public partial class GridViewController : Controller {
        public ActionResult DataToggleInRows() {
            return PartialView("Templates/DataToggleInRows", DataAttributesInRowCustomers.Get());
        }
        public ActionResult DataToggleInRowsAddRow(EditableCustomer customer) {
            if(ModelState.IsValid)
                try {
                    DataAttributesInRowCustomers.Insert(customer);
                } catch(Exception e) {
                    ViewData["ErrorMessage"] = e.Message;
                }
            return PartialView("Templates/DataToggleInRows", DataAttributesInRowCustomers.Get());
        }
        public ActionResult DataToggleInRowsUpdateRow(EditableCustomer customer) {
            if(ModelState.IsValid)
                try {
                    DataAttributesInRowCustomers.Update(customer);
                } catch(Exception e) {
                    ViewData["ErrorMessage"] = e.Message;
                }
            return PartialView("Templates/DataToggleInRows", DataAttributesInRowCustomers.Get());
        }
        public ActionResult DataToggleInRowsDeleteRow(string customerID = "none") {
            if(ModelState.IsValid)
                try {
                    DataAttributesInRowCustomers.Remove(customerID);
                } catch(Exception e) {
                    ViewData["ErrorMessage"] = e.Message;
                }
            return PartialView("Templates/DataToggleInRows", DataAttributesInRowCustomers.Get());
        }
    }
}

namespace DevExpress.AspNetCore.Demos {
    public class EditableCustomer {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string Country { get; set; }
        public string City { get; set; }
        public string Address { get; set; }
    }
}
Screen Size
Color Themes
Demo QR Code