Example of Local Data in ASP.NET Core Charts Control
This sample demonstrates how to bind local data to the Chart component, enabling a chart to be drawn without a request to the server.
@* The chart's settings are in the view; the data they read (ViewData) is set in the controller action (see the controller tab). *@
@Html.UiChart(new UiChartOptions
{
Id = "localDataChart",
Data = (IEnumerable<object>)ViewData["ChartData"],
Height = "340px",
Legend = new UiChartLegend { Visible = false },
Series = new List<UiChartSeries>
{
new UiChartSeries { Type = UiChartSeriesType.Column, XName = "Product", YName = "Sold", Name = "Sold", ShowDataLabel = true }
}
})
@Html.UiChart(new UiChartOptions
{
Id = "localDataChart",
Data = (IEnumerable<object>)ViewData["ChartData"],
Height = "340px",
Legend = new UiChartLegend { Visible = false },
Series = new List<UiChartSeries>
{
new UiChartSeries { Type = UiChartSeriesType.Column, XName = "Product", YName = "Sold", Name = "Sold", ShowDataLabel = true }
}
})
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class ChartController : Controller
{
// The page is Views/Chart/LocalData.cshtml; it draws what ViewData holds.
public ActionResult LocalData()
{
ViewData["ChartData"] = new[]
{
new { Product = "Hand drill", Sold = 120 }, new { Product = "Saw", Sold = 80 }, new { Product = "Level", Sold = 60 },
new { Product = "Hammer", Sold = 140 }, new { Product = "Wrench", Sold = 95 }, new { Product = "Pliers", Sold = 110 }
};
return View();
}
}
}
@* 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>
@* Charts with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
Local data: the Data property takes a list from the page (here a C# list of six rows), and the chart is drawn without a request to the server. Each series names the fields of a row that it reads with XName and YName.