Example of Toolbar and Commands in ASP.NET MVC Data Grid Control
Search, export, column chooser, command column, your own toolbar items and filters outside the grid.
Filters outside the grid: the fields below call grid.reload({ from, to, shippedOnly });
the values start as DataUrlParams and bind to the action's own parameters
(FilteredOrders(UiDataRequest request, DateTime? from, DateTime? to, bool shippedOnly)).
Totals (Aggregates) cover every filtered order, not just the page.
Toolbar: Excel / CSV / PDF export and Print (all filtered orders, with the totals), Columns
(column chooser), and two items of our own (ToolbarItems, OnToolbarClick).
Command column: Edit / Delete on each row (Update / Cancel while editing) and a custom
Details button (OnCommandClick). Drag a header to move a column (AllowReordering),
or its edge to resize it.
@Html.AntiForgeryToken()
@Html.UiGrid(new UiGridOptions
{
Id = "featureGrid",
DataUrl = Url.Action("FilteredOrders", "GridDemo"),
DataUrlParams = new { from = new DateTime(2026, 1, 1), to = new DateTime(2026, 12, 31), shippedOnly = false },
InsertUrl = Url.Action("Insert", "GridDemo"),
UpdateUrl = Url.Action("Update", "GridDemo"),
RemoveUrl = Url.Action("Remove", "GridDemo"),
EditSettings = new UiEditSettings { AllowEditing = true, AllowDeleting = true, AllowAdding = true, ShowDeleteConfirmDialog = true },
Toolbar = new List<string> { "Add", "ExcelExport", "CsvExport", "PdfExport", "Print", "ColumnChooser", "Search" },
ToolbarItems = new List<UiGridToolbarItem>
{
new UiGridToolbarItem { Id = "clearFilters", Text = "Clear filters", TooltipText = "Clear the column filters and the search" },
new UiGridToolbarItem { Id = "help", Text = "Help", Align = UiToolbarAlign.Right }
},
OnToolbarClick = "GridDemo.onToolbarClick",
OnCommandClick = "GridDemo.onCommandClick",
AllowFiltering = true,
AllowReordering = true,
PageSize = 8,
Currency = "PHP",
OnActionComplete = "GridDemo.onActionComplete",
OnDataError = "GridDemo.onDataError",
Aggregates = new List<UiGridAggregateRow>
{
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderNo", Type = UiAggregateType.Count, FooterTemplate = "${Count} orders" },
new UiGridAggregateColumn { Field = "OrderDate", Type = UiAggregateType.Min, FooterTemplate = "From ${Min}" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Sum, FooterTemplate = "Total: ${Sum}" },
new UiGridAggregateColumn { Field = "Shipped", Type = UiAggregateType.TrueCount, FooterTemplate = "${TrueCount} shipped" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderDate", Type = UiAggregateType.Max, FooterTemplate = "To ${Max}" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Average, FooterTemplate = "Avg: ${Average}" }
}
}
},
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "Id", HeaderText = "ID", Type = UiColumnType.Number, Width = 70, IsPrimaryKey = true, IsIdentity = true, ShowInColumnChooser = false },
new UiGridColumn { Field = "OrderNo", HeaderText = "Order #", Width = 120, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "Customer", HeaderText = "Customer", Width = 190, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "OrderDate", HeaderText = "Order Date", Type = UiColumnType.Date, Format = "MM/dd/yyyy", Width = 140, DefaultValue = DateTime.Today },
new UiGridColumn { Field = "Amount", Type = UiColumnType.Number, Format = "C2", Width = 150, DefaultValue = 0 },
new UiGridColumn { Field = "Shipped", Type = UiColumnType.Boolean, Width = 110, DefaultValue = false },
new UiGridColumn
{
HeaderText = "Commands", Width = 150,
Commands = new List<UiGridCommand>
{
new UiGridCommand { Type = UiCommandType.Edit },
new UiGridCommand { Type = UiCommandType.Delete },
new UiGridCommand { Type = UiCommandType.Save },
new UiGridCommand { Type = UiCommandType.Cancel },
new UiGridCommand { Type = UiCommandType.Custom, Name = "details", Text = "Details" }
}
}
}
})
@Html.AntiForgeryToken()
<p>
<strong>Filters outside the grid:</strong> the fields below call <code>grid.reload({ from, to, shippedOnly })</code>;
the values start as <code>DataUrlParams</code> and bind to the action's own parameters
(<code>FilteredOrders(UiDataRequest request, DateTime? from, DateTime? to, bool shippedOnly)</code>).
<strong>Totals</strong> (<code>Aggregates</code>) cover every filtered order, not just the page.
<strong>Toolbar:</strong> Excel / CSV / PDF export and Print (all filtered orders, with the totals), Columns
(column chooser), and two items of our own (<code>ToolbarItems</code>, <code>OnToolbarClick</code>).
<strong>Command column:</strong> Edit / Delete on each row (Update / Cancel while editing) and a custom
Details button (<code>OnCommandClick</code>). Drag a header to move a column (<code>AllowReordering</code>),
or its edge to resize it.
</p>
<form class="row g-2 align-items-end mb-2" onsubmit="GridDemo.applyOrderFilters(); return false;">
<div class="col-auto"><label class="form-label small mb-0" for="gridFrom">From</label><input id="gridFrom" type="date" class="form-control form-control-sm" value="2026-01-01"></div>
<div class="col-auto"><label class="form-label small mb-0" for="gridTo">To</label><input id="gridTo" type="date" class="form-control form-control-sm" value="2026-12-31"></div>
<div class="col-auto form-check ms-2"><input id="gridShipped" type="checkbox" class="form-check-input"><label class="form-check-label small" for="gridShipped">Shipped only</label></div>
<div class="col-auto"><button type="submit" class="btn btn-primary btn-sm">Apply</button></div>
</form>
@Html.UiGrid(new UiGridOptions
{
Id = "featureGrid",
DataUrl = Url.Action("FilteredOrders", "GridDemo"),
DataUrlParams = new { from = new DateTime(2026, 1, 1), to = new DateTime(2026, 12, 31), shippedOnly = false },
InsertUrl = Url.Action("Insert", "GridDemo"),
UpdateUrl = Url.Action("Update", "GridDemo"),
RemoveUrl = Url.Action("Remove", "GridDemo"),
EditSettings = new UiEditSettings { AllowEditing = true, AllowDeleting = true, AllowAdding = true, ShowDeleteConfirmDialog = true },
Toolbar = new List<string> { "Add", "ExcelExport", "CsvExport", "PdfExport", "Print", "ColumnChooser", "Search" },
ToolbarItems = new List<UiGridToolbarItem>
{
new UiGridToolbarItem { Id = "clearFilters", Text = "Clear filters", TooltipText = "Clear the column filters and the search" },
new UiGridToolbarItem { Id = "help", Text = "Help", Align = UiToolbarAlign.Right }
},
OnToolbarClick = "GridDemo.onToolbarClick",
OnCommandClick = "GridDemo.onCommandClick",
AllowFiltering = true,
AllowReordering = true,
PageSize = 8,
Currency = "PHP",
OnActionComplete = "GridDemo.onActionComplete",
OnDataError = "GridDemo.onDataError",
Aggregates = new List<UiGridAggregateRow>
{
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderNo", Type = UiAggregateType.Count, FooterTemplate = "${Count} orders" },
new UiGridAggregateColumn { Field = "OrderDate", Type = UiAggregateType.Min, FooterTemplate = "From ${Min}" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Sum, FooterTemplate = "Total: ${Sum}" },
new UiGridAggregateColumn { Field = "Shipped", Type = UiAggregateType.TrueCount, FooterTemplate = "${TrueCount} shipped" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderDate", Type = UiAggregateType.Max, FooterTemplate = "To ${Max}" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Average, FooterTemplate = "Avg: ${Average}" }
}
}
},
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "Id", HeaderText = "ID", Type = UiColumnType.Number, Width = 70, IsPrimaryKey = true, IsIdentity = true, ShowInColumnChooser = false },
new UiGridColumn { Field = "OrderNo", HeaderText = "Order #", Width = 120, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "Customer", HeaderText = "Customer", Width = 190, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "OrderDate", HeaderText = "Order Date", Type = UiColumnType.Date, Format = "MM/dd/yyyy", Width = 140, DefaultValue = DateTime.Today },
new UiGridColumn { Field = "Amount", Type = UiColumnType.Number, Format = "C2", Width = 150, DefaultValue = 0 },
new UiGridColumn { Field = "Shipped", Type = UiColumnType.Boolean, Width = 110, DefaultValue = false },
new UiGridColumn
{
HeaderText = "Commands", Width = 150,
Commands = new List<UiGridCommand>
{
new UiGridCommand { Type = UiCommandType.Edit },
new UiGridCommand { Type = UiCommandType.Delete },
new UiGridCommand { Type = UiCommandType.Save },
new UiGridCommand { Type = UiCommandType.Cancel },
new UiGridCommand { Type = UiCommandType.Custom, Name = "details", Text = "Details" }
}
}
}
})
<h3>Event log</h3>
<ul id="eventLog" style="font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto; border: 1px solid var(--ui-border, #dadce3); padding: 8px;"></ul>
@section scripts {
<script>
window.GridDemo = (function () {
'use strict';
// Sample-local event-log utility.
function log(message) {
var list = document.getElementById('eventLog');
if (!list) { return; }
var item = document.createElement('li');
item.textContent = new Date().toLocaleTimeString() + ' - ' + message;
list.insertBefore(item, list.firstChild);
}
return {
applyOrderFilters: function () {
var from = document.getElementById('gridFrom');
var to = document.getElementById('gridTo');
var shipped = document.getElementById('gridShipped');
var grid = window.Lumen && window.Lumen.get('featureGrid');
if (!from || !to || !shipped || !grid) { return; }
var params = { from: from.value || null, to: to.value || null, shippedOnly: shipped.checked };
log('featureGrid: reload(' + JSON.stringify(params) + ')');
grid.reload(params);
},
onToolbarClick: function (args, gridId) {
log(gridId + ': toolbar ' + args.item.id);
if (args.item.id === 'clearFilters') {
var grid = window.Lumen && window.Lumen.get(gridId);
if (!grid) { return; }
grid.search('');
grid.clearFiltering();
} else if (args.item.id === 'help') {
alert('Export buttons export every filtered order with the totals; Columns shows or hides columns.');
}
},
onCommandClick: function (args, gridId) {
log(gridId + ': command ' + (args.commandColumn.name || args.commandColumn.type) + ' on ' + args.rowData.OrderNo);
if (args.commandColumn.name === 'details') {
alert(args.rowData.OrderNo + ' - ' + args.rowData.Customer + '\n' + (args.rowData.Notes || ''));
}
},
onActionComplete: function (args, gridId) {
if (args.action) {
log(gridId + ': ' + args.action + ' saved - ' + JSON.stringify(args.data));
} else if (args.requestType === 'beginEdit' || args.requestType === 'cancel') {
log(gridId + ': ' + args.requestType);
}
},
onDataError: function (message, gridId) {
log(gridId + ': data error - ' + message);
}
};
})();
</script>
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
using Lumen.UI.Mvc.Demo.Models;
using Newtonsoft.Json;
// ServerOperations = true (default): the grid POSTs a UiDataRequest and expects { result, count } back (UiDataOperations.Execute).
// ServerOperations = false: return all rows once as a plain JSON array.
namespace Lumen.UI.Mvc.Demo.Controllers
{
public partial class GridDemoController : Controller
{
// SampleOrders.All is a shared in-memory list (also read by the chart demo); a real app would use its database instead.
private static readonly object Sync = SampleOrders.Sync;
/// <summary>
/// DataUrl with extra values (DataUrlParams / grid.reload(params)): they arrive beside the grid's own
/// paging, sorting and filtering fields and bind to these parameters. Totals (Aggregates) are worked
/// out by UiDataOperations over every filtered row.
/// </summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult FilteredOrders(UiDataRequest request, DateTime? from, DateTime? to, bool shippedOnly = false)
{
lock (Sync)
{
IQueryable<Order> orders = SampleOrders.All.AsQueryable();
if (from.HasValue) { orders = orders.Where(o => o.OrderDate >= from.Value.Date); }
if (to.HasValue) { orders = orders.Where(o => o.OrderDate < to.Value.Date.AddDays(1)); }
if (shippedOnly) { orders = orders.Where(o => o.Shipped); }
return Json(UiDataOperations.Execute(orders, request, "Id"));
}
}
/// <summary>Grid InsertUrl: the grid sends the new row; return it with its new Id.</summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult Insert(UiCrudRequest<Order> request)
{
if (request == null || request.Value == null)
{
return new HttpStatusCodeResult(400);
}
lock (Sync)
{
Order order = request.Value;
order.Id = SampleOrders.All.Count == 0 ? 1 : SampleOrders.All.Max(o => o.Id) + 1;
SampleOrders.All.Insert(0, order);
return Json(order);
}
}
/// <summary>Grid UpdateUrl: request.Key is the primary key of the edited row.</summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult Update(UiCrudRequest<Order> request)
{
int id;
if (request == null || request.Value == null || !int.TryParse(request.Key, out id))
{
return new HttpStatusCodeResult(400);
}
lock (Sync)
{
Order existing = SampleOrders.All.FirstOrDefault(o => o.Id == id);
if (existing == null)
{
return HttpNotFound();
}
Copy(request.Value, existing);
return Json(existing);
}
}
/// <summary>Copies what the grid edits. Columns a grid doesn't show arrive empty and are left as they are.</summary>
private static void Copy(Order from, Order to)
{
to.OrderNo = from.OrderNo;
to.OrderDate = from.OrderDate;
to.Amount = from.Amount;
to.Shipped = from.Shipped;
if (from.Region != null) { to.Region = from.Region; }
if (from.Notes != null) { to.Notes = from.Notes; }
// The demo's grids edit the customer in two ways: as text (Customer) or through the foreign key
// column (CustomerId, whose name then follows). A name that was typed wins.
bool nameTyped = from.Customer != null && from.Customer != to.Customer;
if (from.CustomerId > 0 && from.CustomerId != to.CustomerId && !nameTyped)
{
to.CustomerId = from.CustomerId;
CustomerInfo customer = SampleOrders.CustomerList.FirstOrDefault(c => c.CustomerId == from.CustomerId);
if (customer != null) { to.Customer = customer.Name; }
}
else if (nameTyped)
{
to.Customer = from.Customer;
}
}
/// <summary>Grid RemoveUrl: request.Key is the primary key of the deleted row.</summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult Remove(UiCrudRequest<Order> request)
{
int id;
if (request == null || !int.TryParse(request.Key, out id))
{
return new HttpStatusCodeResult(400);
}
lock (Sync)
{
SampleOrders.All.RemoveAll(o => o.Id == id);
return Json(new { ok = true });
}
}
}
}
namespace Lumen.UI.Mvc.Demo.Models
{
public class Order
{
public int Id { get; set; }
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Customer { get; set; }
/// <summary>Key of the customer (see SampleOrders.Customers), to show a foreign key column.</summary>
public int CustomerId { get; set; }
/// <summary>North, South, East or West: a column with few values, to show grouping and a dropdown editor.</summary>
public string Region { get; set; }
public decimal Amount { get; set; }
public bool Shipped { get; set; }
/// <summary>Long free text, to show text wrapping in the grid.</summary>
public string Notes { get; set; }
}
}
namespace Lumen.UI.Mvc.Demo.Models
{
/// <summary>A customer, the lookup list of the grid's foreign key column.</summary>
public class CustomerInfo
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
}
namespace Lumen.UI.Mvc.Demo.Models
{
/// <summary>In-memory test data for the grid and chart demos. A real app would query a database instead.</summary>
public static class SampleOrders
{
/// <summary>Lock held while reading or changing <see cref="All"/> (the grid demo edits it).</summary>
public static readonly object Sync = new object();
private static readonly string[] Customers =
{
"Santos Trading", "Reyes Hardware", "Dela Cruz Foods", "Bautista Auto Parts",
"Garcia Textiles", "Mendoza Electronics", "Torres Logistics", "Flores Bakery"
};
// Long notes to show text wrapping; some contain one very long word (a part number without spaces),
// which is broken inside the word only because it is wider than the column.
private static readonly string[] Notes =
{
"Deliver to the back entrance before 10 AM; the front gate is closed on weekends and public holidays.",
"Customer asked for partial delivery: send the available items now and the rest when back in stock.",
"Replacement part PN-XJ9000-ULTRAHEAVYDUTY-STAINLESSSTEELFLANGEASSEMBLY-REV7 must be checked before shipping.",
"Fragile.",
"Invoice must show the purchase order number, the project code and the name of the receiving warehouse.",
"Supercalifragilisticexpialidociousnessmaximizationprogramme discount applied at checkout.",
"Call the site supervisor thirty minutes before arrival so the loading bay can be cleared.",
"Standard delivery."
};
private static readonly string[] Cities =
{
"Manila", "Cebu", "Davao", "Quezon City", "Iloilo", "Baguio", "Cagayan de Oro", "Bacolod"
};
/// <summary>The values of Order.Region: the grouping demo's groups and the dropdown editor's choices.</summary>
public static readonly string[] Regions = { "North", "South", "East", "West" };
/// <summary>Lookup list for the foreign key column: Order.CustomerId -> Name.</summary>
public static readonly List<CustomerInfo> CustomerList = BuildCustomers();
public static readonly List<Order> All = Build();
private static List<CustomerInfo> BuildCustomers()
{
var list = new List<CustomerInfo>();
for (int i = 0; i < Customers.Length; i++)
{
list.Add(new CustomerInfo { CustomerId = i + 1, Name = Customers[i], City = Cities[i] });
}
return list;
}
private static List<Order> Build()
{
// The demo builds made-up rows here (the fields are in the class above); a real app queries its database.
throw new NotImplementedException("Return your own rows.");
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Grids with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@