Example of Reactive Aggregate in ASP.NET Core Data Grid Control
Footer totals that are worked out again when a row changes.
The footer totals follow the data: when a row changes (grid.setRowData(key, changes), or an edit), the Sum, Average,
Min, Max and Count are worked out again and the page shows the new values after a moment. Change some amounts with the buttons
and watch the footer.
@Html.UiGrid(new UiGridOptions
{
Id = "reactiveAggregateGrid",
Data = Model,
PageSize = 6,
Aggregates = new List<UiGridAggregateRow>
{
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderNo", Type = UiAggregateType.Count, FooterTemplate = "${Count} orders" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Sum, Format = "C2", FooterTemplate = "Sum: ${Sum}" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Average, Format = "C2", FooterTemplate = "Average: ${Average}" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Max, Format = "C2", FooterTemplate = "Max: ${Max}" }
}
}
},
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "Id", IsPrimaryKey = true, Visible = false, ShowInColumnChooser = false },
new UiGridColumn { Field = "OrderNo", HeaderText = "Order #", Width = 140 },
new UiGridColumn { Field = "Customer", HeaderText = "Customer Name", Width = 200 },
new UiGridColumn { Field = "Amount", Type = UiColumnType.Number, Format = "C2", Width = 200 },
new UiGridColumn { Field = "Shipped", Type = UiColumnType.Boolean, Width = 120 }
}
})
@using Lumen.UI.Mvc.Demo.Models
@model System.Collections.Generic.List<Lumen.UI.Mvc.Demo.Models.Order>
<p>
The footer totals follow the data: when a row changes (<code>grid.setRowData(key, changes)</code>, or an edit), the <code>Sum</code>, <code>Average</code>,
<code>Min</code>, <code>Max</code> and <code>Count</code> are worked out again and the page shows the new values after a moment. Change some amounts with the buttons
and watch the footer.
</p>
<div class="feat-bar">
<button type="button" class="btn btn-sm btn-primary" id="reactiveRaise">Raise 3 amounts</button>
<button type="button" class="btn btn-sm btn-outline-primary" id="reactiveLower">Lower 3 amounts</button>
<span id="reactiveInfo" class="text-muted small"></span>
</div>
@Html.UiGrid(new UiGridOptions
{
Id = "reactiveAggregateGrid",
Data = Model,
PageSize = 6,
Aggregates = new List<UiGridAggregateRow>
{
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "OrderNo", Type = UiAggregateType.Count, FooterTemplate = "${Count} orders" },
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Sum, Format = "C2", FooterTemplate = "Sum: ${Sum}" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Average, Format = "C2", FooterTemplate = "Average: ${Average}" }
}
},
new UiGridAggregateRow
{
Columns = new List<UiGridAggregateColumn>
{
new UiGridAggregateColumn { Field = "Amount", Type = UiAggregateType.Max, Format = "C2", FooterTemplate = "Max: ${Max}" }
}
}
},
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "Id", IsPrimaryKey = true, Visible = false, ShowInColumnChooser = false },
new UiGridColumn { Field = "OrderNo", HeaderText = "Order #", Width = 140 },
new UiGridColumn { Field = "Customer", HeaderText = "Customer Name", Width = 200 },
new UiGridColumn { Field = "Amount", Type = UiColumnType.Number, Format = "C2", Width = 200 },
new UiGridColumn { Field = "Shipped", Type = UiColumnType.Boolean, Width = 120 }
}
})
@section scripts {
<script>
window.GridReactiveAggregate = (function () {
'use strict';
var changes = 0;
function change(direction) {
var grid = window.Lumen && window.Lumen.get('reactiveAggregateGrid');
var rows = grid ? grid.getCurrentViewRecords() : null;
if (!rows || !rows.length) { return; }
for (var n = 0; n < 3; n++) {
var row = rows[Math.floor(Math.random() * rows.length)];
var amount = Math.max(1, Math.round((row.Amount * (1 + direction * (0.05 + Math.random() * 0.15))) * 100) / 100);
grid.setRowData(row.Id, { Amount: amount });
changes++;
}
var info = document.getElementById('reactiveInfo');
if (info) { info.textContent = changes + ' amounts changed'; }
}
function init() {
var raise = document.getElementById('reactiveRaise');
var lower = document.getElementById('reactiveLower');
if (raise) { raise.addEventListener('click', function () { change(1); }); }
if (lower) { lower.addEventListener('click', function () { change(-1); }); }
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
return {};
})();
</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.
// Inside the Sample action of GridDemoController:
List<Order> orders = CopyOrders(SampleOrders.All.Take(30));
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;
private static List<Order> CopyOrders(IEnumerable<Order> orders)
{
// Copies, so the in-page edits never change the shared list.
return orders.Select(o => new Order
{
Id = o.Id, OrderNo = o.OrderNo, OrderDate = o.OrderDate, Customer = o.Customer, CustomerId = o.CustomerId,
Region = o.Region, Amount = o.Amount, Shipped = o.Shipped, Notes = o.Notes
}).ToList();
}
}
}
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>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."
};
/// <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" };
public static readonly List<Order> All = Build();
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.");
}
}
}
@* Program.cs *@
builder.Services.AddControllersWithViews().AddLumenUIJson();
builder.Services.AddLumenUI();
// ...
app.UseLumenUI();
@* Views/_ViewImports.cshtml *@
@using Lumen.UI.Mvc
@addTagHelper *, Lumen.UI.Core
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@await RenderSectionAsync("scripts", required: false)
</body>
@* Grids with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@