Example of Live Data in ASP.NET MVC Data Grid Control
This sample demonstrates how frequently Grid cells are updated in real-time data at a set interval.
@Html.UiGrid(new UiGridOptions
{
Id = "LiveData",
Data = ViewData["Data"],
Height = "500px",
RowHeight = 38,
EnableVirtualization = true,
EnableHover = false,
OnQueryCellInfo = "queryCellInfo",
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "id", HeaderText = "ID", Type = UiColumnType.Number, Width = 140, Visible = false, IsPrimaryKey = true },
new UiGridColumn { Field = "CountryCode", HeaderText = "Ticker", Width = 70 },
new UiGridColumn { Field = "Change", HeaderText = "Change % 1D", Type = UiColumnType.Number, Format = "N0", Width = 100 },
new UiGridColumn { Field = "Net", HeaderText = "Net", Type = UiColumnType.Number, Format = "C2", Width = 100 },
new UiGridColumn { Field = "Rating", HeaderText = "Technical Rating 1D", Width = 150 },
new UiGridColumn { Field = "NetIncome", HeaderText = "Net Income", Type = UiColumnType.Number, Format = "C2", Width = 150 },
new UiGridColumn { Field = "Sector", HeaderText = "Sector", Width = 160 },
new UiGridColumn { Field = "EmployeeCount", HeaderText = "Employee Count", Width = 130 }
}
})
<style>
.above-0 { color: #2e7d32; }
.below-0 { color: #c62828; }
.ui-grid .tabulator-cell.e-increase { color: #2e7d32; }
.ui-grid .tabulator-cell.e-decrease { color: #c62828; }
.rating-cell .ic { display: inline-block; width: 14px; margin-right: 6px; }
.rating-cell.neutral { color: #757575; }
.feed-bar { margin-bottom: 12px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
</style>
<div class="feed-bar">
<label for="numeric" style="font-size: 14px;">Feed Delay(ms):</label>
<input type="number" id="numeric" value="1000" min="10" max="5000" step="1" style="width: 120px;" />
<button type="button" id="updatebtn">Start Data Update</button>
<button type="button" id="clearbtn" disabled>Stop Data Update</button>
</div>
@Html.UiGrid(new UiGridOptions
{
Id = "LiveData",
Data = ViewData["Data"],
Height = "500px",
RowHeight = 38,
EnableVirtualization = true,
EnableHover = false,
OnQueryCellInfo = "queryCellInfo",
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "id", HeaderText = "ID", Type = UiColumnType.Number, Width = 140, Visible = false, IsPrimaryKey = true },
new UiGridColumn { Field = "CountryCode", HeaderText = "Ticker", Width = 70 },
new UiGridColumn { Field = "Change", HeaderText = "Change % 1D", Type = UiColumnType.Number, Format = "N0", Width = 100 },
new UiGridColumn { Field = "Net", HeaderText = "Net", Type = UiColumnType.Number, Format = "C2", Width = 100 },
new UiGridColumn { Field = "Rating", HeaderText = "Technical Rating 1D", Width = 150 },
new UiGridColumn { Field = "NetIncome", HeaderText = "Net Income", Type = UiColumnType.Number, Format = "C2", Width = 150 },
new UiGridColumn { Field = "Sector", HeaderText = "Sector", Width = 160 },
new UiGridColumn { Field = "EmployeeCount", HeaderText = "Employee Count", Width = 130 }
}
})
<script>
// Syncfusion colours the cells by their value, and shows the rating with an arrow and a word.
function queryCellInfo(args) {
if (args.column === 'NetIncome') {
args.cell.classList.toggle('e-decrease', args.data.Net < 0);
args.cell.classList.toggle('e-increase', args.data.Net > 0);
} else if (args.column === 'Change' || args.column === 'Net') {
args.cell.classList.toggle('below-0', args.data[args.column] < 0);
args.cell.classList.toggle('above-0', args.data[args.column] >= 0);
} else if (args.column === 'Rating') {
var d = args.data, arrow = '\u25B2', text = 'Buy', cls = 'above-0';
if (d.Change === 0) { arrow = '\u25AC'; text = 'Neutral'; cls = 'neutral'; }
else if (d.Change < -2 && d.Net < 0) { arrow = '\u25BC\u25BC'; text = 'Strong sell'; cls = 'below-0'; }
else if (d.Net < 0) { arrow = '\u25BC'; text = 'Sell'; cls = 'below-0'; }
else if (d.Change > 5 && d.Net > 10) { arrow = '\u25B2\u25B2'; text = 'Strong buy'; }
var box = document.createElement('span');
box.className = 'rating-cell ' + cls;
var icon = document.createElement('span');
icon.className = 'ic';
icon.textContent = arrow;
var word = document.createElement('span');
word.textContent = text;
box.appendChild(icon);
box.appendChild(word);
args.content = box;
}
}
// Syncfusion's feed: every delay, each row in view gets a new Net, Change, Rating and Net Income (setCellValue); the cells flash as they change.
var timerID;
function updateCellValues() {
var grid = window.Lumen.get('LiveData');
var rows = grid.getCurrentViewRecords();
var changes = rows.map(function (row, i) {
var num = Math.floor(Math.random() * 99) + 1;
num *= Math.floor(Math.random() * 2) === 1 ? 1 : -1;
num *= i % 2 === 0 ? 0.25 : i % 3 === 0 ? 0.83 : i % 5 === 0 ? 0.79 : i % 4 === 0 ? 0.42 : 0.51;
var net = parseFloat(num.toFixed(2));
var change = parseFloat(parseFloat((net - row.Net).toString().substring(0, 2)).toFixed(2));
return { id: row.id, Net: net, Change: change, Rating: net < 0 ? 'Sell' : 'Buy', NetIncome: net + change };
});
grid.updateRows(changes);
}
document.getElementById('updatebtn').addEventListener('click', function () {
if (timerID) { return; }
document.getElementById('updatebtn').disabled = true;
document.getElementById('numeric').disabled = true;
document.getElementById('clearbtn').disabled = false;
timerID = setInterval(updateCellValues, Math.max(10, parseInt(document.getElementById('numeric').value, 10) || 1000));
});
document.getElementById('clearbtn').addEventListener('click', function () {
if (!timerID) { return; }
document.getElementById('updatebtn').disabled = false;
document.getElementById('numeric').disabled = false;
document.getElementById('clearbtn').disabled = true;
clearInterval(timerID);
timerID = undefined;
});
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class GridController : Controller
{
// The page is Views/Grid/LiveData.cshtml; it draws what ViewData holds.
public ActionResult LiveData()
{
ViewData["Data"] = LiveData.GetLiveDatas(100);
return View();
}
public class LiveData
{
public static List<LiveData> tradeData = new List<LiveData>();
public long id { get; set; }
public string CountryCode { get; set; }
public decimal Change { get; set; }
public decimal Net { get; set; }
public string Rating { get; set; }
public string Sector { get; set; }
public string EmployeeCount { get; set; }
public decimal NetIncome { get; set; }
public LiveData(long Id, string CountryCode, decimal Change, decimal Net, string Rating, string Sector, string EmployeeCount, decimal NetIncome) {
this.id = Id;
this.CountryCode = CountryCode;
this.Net = Net;
this.Rating = Rating;
this.Sector = Sector;
this.EmployeeCount = EmployeeCount;
this.NetIncome = NetIncome;
}
public static List<LiveData> GetLiveDatas(long dataCount)
{
string[] ContryNames = { "ALA", "ALB", "DZA", "ASM", "AND", "AGO", "AIA", "ATA", "ATG",
"ARG", "ARM", "ABW", "AUS", "AUT", "AZE", "BHS", "BHR", "BGD", "BRB", "BLR", "BEL", "BLZ",
"BEN", "AFG", "BMU", "BTN", "BOL", "BES", "BIH", "BWA", "BVT", "BRA", "IOT", "BRN", "BGR",
"BFA", "BDI", "CPV", "KHM", "CMR", "CAN", "CYM", "CAF", "TCD", "CHL", "CHN", "CXR", "CCK",
"COL", "COM", "COG", "COD", "COK", "CRI", "CIV", "HRV", "CUB", "CUW", "CYP", "CZE", "DNK", "DJI",
"DMA" };
string[] Category = { "Energy", "Financial", "Technology", "Healthcare", "Retail",
"Manufacturing", "Consumer Goods", "Telecommunications", "Transportation", "Utilities",
"Real Estate", "Industrial Goods", "Oil and Gas", "Entertainment", "Media", "Banking",
"Sports", "Mining", "Automotive", };
string[] Rating = { "Buy", "Sell" };
Random random = new Random();
for (long i = 1; i <= dataCount; i++) {
string countryCode = ContryNames[random.Next(ContryNames.Length)] + ContryNames[random.Next(ContryNames.Length)];
decimal change = Decimal.Floor(Convert.ToDecimal(random.Next(201) - 90 * 0.96));
decimal net = Decimal.Floor(Convert.ToDecimal(random.Next(201) - 90 * 2.95));
string rating = Rating[random.Next(Rating.Length)];
string sector = Category[random.Next(Category.Length)];
string employeeCount = random.Next(10000) + 100 + "K";
decimal netIncome = Decimal.Floor(Convert.ToDecimal(random.Next(201) - 90 * 0.45));
tradeData.Add(new LiveData(i, countryCode, change, net, rating, sector, employeeCount, netIncome) { });
}
return tradeData;
}
}
}
}
@* 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. *@
The updating of Grid cells can be done without any performance lagging by using the setCellValue method. The style of Grid cells can be customized using the queryCellInfo event.
In this demo,
- Clicking the start update button triggers automatic updates of Grid cells at the interval set in the feed delay text box which is a milliseconds format.
- Clicking the stop update button will halt the automatic updating of Grid cells.