Telerik Forums
UI for ASP.NET MVC Forum
0 answers
4 views

Description

Hello Telerik Community,

I'm encountering an issue with my Kendo Chart implementation where certain data points are not displaying on the line series, despite being present in the dataset. Here's a breakdown of the problem and my current setup:

Problem 

- Some data points, specifically those corresponding to the dates November 27 and November 29, are not showing up on the line chart.
- However, these dates are appearing correctly in the category legend.

Setup

- I'm using Kendo Chart to visualize historical pool data.
- Data is fetched from a database and processed in the controller before being passed to the Razor view for rendering.
- Each manufacturer's data is plotted on the chart as separate line series, with the x-axis representing dates and the y-axis representing weight.

Relevant Code

Controller Code: I've provided the relevant controller code responsible for fetching and processing the data.
Razor View Code: Similarly, I've included the Razor view code where the Kendo Chart is defined and configured.

Expected Outcome

- I expect the line chart to display all data points, including those for November 27 and November 29, for each manufacturer.

Steps Taken

- I've checked the data in the controller, and it seems that all data points are correctly fetched from the database.
- I've inspected the generated HTML for the chart and confirmed that the missing data points are indeed not being rendered.

Request for Assistance

- Could you please review my setup and help me identify any potential issues causing the missing data points?
- Additionally, if you have any suggestions for troubleshooting or debugging this issue further, I would greatly appreciate it.

Additional Information

Framework: ASP.NET MVC- Browser: Chrome, Edge

Thank you in advance for your assistance!


public ActionResult ChartTMS(DateTime? fromDate, DateTime? toDate, string unit = "gm")
        {
            fromDate = fromDate?.Date;
            toDate = toDate.HasValue ? toDate.Value.Date.AddDays(1).AddTicks(-1) : DateTime.Today;
 
            if (!fromDate.HasValue || !toDate.HasValue)
            {
                fromDate = DateTime.Today.AddDays(-6);
                toDate = DateTime.Today;
            }
 
            var allMeasurements = (
                from m in db.Target_Measurement_History.AsNoTracking()
                where m.Measurement_Record_Date >= fromDate.Value && m.Measurement_Record_Date <= toDate.Value
&& m.Target_Lot_Profile != null
&& m.Target_Lot_Profile.Target_Item != null
&& m.Target_Lot_Profile.Target_Item.Target_Manufacturer != null
                select new MeasurementDataViewModel
                {
                    Measurement_Record_Date = m.Measurement_Record_Date,
                    Pt_Remaining_Gms = m.Pt_Remaining_Gms,
                    Ru_Remaining_Gms = m.Ru_Remaining_Gms,
                    Manufacturer = m.Target_Lot_Profile.Target_Item.Target_Manufacturer,
                }).ToList();
 
            var manufacturers = allMeasurements.Select(m => m.Manufacturer).Distinct();
            var colorMap = new Dictionary<string, string>();
            Random rand = new Random();
 
            foreach (var manufacturer in manufacturers)
            {
                colorMap[manufacturer] = $"#{rand.Next(0x1000000):X6}";
            }
 
            var groupedData = allMeasurements
                .GroupBy(m => new { m.Measurement_Record_Date.Date, m.Manufacturer })
                .Select(group => new MeasurementDataViewModel
                {
                    Measurement_Record_Date = group.Key.Date,
                    Pt_Remaining_Gms = group.Sum(item => item.Pt_Remaining_Gms),
                    Ru_Remaining_Gms = group.Sum(item => item.Ru_Remaining_Gms),
                    Manufacturer = group.Key.Manufacturer,
                    Color = colorMap[group.Key.Manufacturer]
                })
                .OrderBy(g => g.Measurement_Record_Date)
                .ThenBy(g => g.Manufacturer)
                .ToList();
 
            const float gramsPerTroyOunce = 31.1035f;
 
            if (unit == "t oz")
            {
                foreach (var item in groupedData)
                {
                    if (item.Pt_Remaining_Gms.HasValue)
                        item.Pt_Remaining_Gms = item.Pt_Remaining_Gms.Value / gramsPerTroyOunce;
 
                    if (item.Ru_Remaining_Gms.HasValue)
                        item.Ru_Remaining_Gms = item.Ru_Remaining_Gms.Value / gramsPerTroyOunce;
                }
            }
 
            ViewBag.fromDate = fromDate;
            ViewBag.toDate = toDate;
            ViewBag.Unit = unit;
 
            return View(groupedData);
        }

    public class MeasurementDataViewModel
    {
        public DateTime Measurement_Record_Date { get; set; }
        public float? Pt_Remaining_Gms { get; set; }
        public float? Ru_Remaining_Gms { get; set; }
        public string Manufacturer { get; set; }
        public string Color { get; set; }
    }
[
    {
        "Measurement_Record_Date": "/Date(1542823200000)/",
        "Pt_Remaining_Gms": 4370,
        "Ru_Remaining_Gms": 5621,
        "Manufacturer": "JX Nippon"
    },
    {
        "Measurement_Record_Date": "/Date(1542823200000)/",
        "Pt_Remaining_Gms": 4571,
        "Ru_Remaining_Gms": 4295,
        "Manufacturer": "Kojundo/Mitsui"
    },
    {
        "Measurement_Record_Date": "/Date(1543168800000)/",
        "Pt_Remaining_Gms": 1785,
        "Ru_Remaining_Gms": 7086,
        "Manufacturer": "JX Nippon"
    },
    {
        "Measurement_Record_Date": "/Date(1543255200000)/",
        "Pt_Remaining_Gms": 36432,
        "Ru_Remaining_Gms": 41800,
        "Manufacturer": "Kurt J. Lesker"
    },
    {
        "Measurement_Record_Date": "/Date(1543428000000)/",
        "Pt_Remaining_Gms": 76360,
        "Ru_Remaining_Gms": 74687,
        "Manufacturer": "Kurt J. Lesker"
    },
    {
        "Measurement_Record_Date": "/Date(1543428000000)/",
        "Pt_Remaining_Gms": 11138,
        "Ru_Remaining_Gms": 9686,
        "Manufacturer": "Materion"
    },
    {
        "Measurement_Record_Date": "/Date(1543428000000)/",
        "Pt_Remaining_Gms": 1329,
        "Ru_Remaining_Gms": 4796,
        "Manufacturer": "Mitsubishi"
    }
]
@using Kendo.Mvc.UI
@using System.Web.Mvc
@using System.Web.Mvc.Html
@using Kendo.Mvc.Extensions
@model IEnumerable<TMS_RND.Controllers.MeasurementDataViewModel>
@using System.Web.Helpers
 
@{
    ViewBag.Title = "Chart";
    Layout = "~/Views/Shared/_Layout.cshtml";
 
    DateTime startDate = ViewBag.fromDate ?? DateTime.Today.AddDays(-6);
    DateTime endDate = ViewBag.toDate ?? DateTime.Today;
    string currentUnit = ViewBag.Unit ?? "gm";
    var manufacturers = Model
        .GroupBy(m => m.Manufacturer)
        .Select(g => new
        {
            Manufacturer = g.Key,
            Color = g.First().Color
        })
        .ToList();
}
 
 
<div class="demo-section wide">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
            From: @(Html.Kendo().DatePicker().Name("fromDate").Value(startDate.ToString("yyyy-MM-dd")))
            To: @(Html.Kendo().DatePicker().Name("toDate").Value(endDate.ToString("yyyy-MM-dd")))
<button id="refreshChart">Refresh Chart</button>
<button id="clearFilter">Clear</button>
<button id="toggleUnit">@(currentUnit == "gm" ? "Switch to Troy oz" : "Switch to gm")</button>
</div>
<div>
<button class="tab" id="totalPoolTab">Total Pool</button>
<button class="tab" id="tmsTab" style="background-color: lightblue;">TMS</button>
</div>
<div>
            @foreach (var manufacturer in manufacturers)
            {
<span style="color:@manufacturer.Color">@manufacturer.Manufacturer</span>
            }
</div>
</div>
<div id="chartContainer">
        @(Html.Kendo().Chart(Model)
            .Name("chart")
            .Title("Historical Pool Data")
            .HtmlAttributes(new { style = "height: 400px;" })
            .Legend(legend => legend.Position(ChartLegendPosition.Bottom))
            .SeriesDefaults(seriesDefaults => seriesDefaults.Line().Stack(false))
            .Series(series => {
                foreach (var manufacturer in manufacturers)
                {
                    var manufacturerData = Model.Where(m => m.Manufacturer == manufacturer.Manufacturer).ToList();
                    series.Line(manufacturerData.Select(m => m.Pt_Remaining_Gms))
                          .Name("Pt - " + manufacturer.Manufacturer)
                          .Color(manufacturer.Color)
                          .Visible(true)
                          .Labels(labels => labels.Visible(true).Format("{0:N2} " + currentUnit));
                    series.Line(manufacturerData.Select(m => m.Ru_Remaining_Gms))
                          .Name("Ru - " + manufacturer.Manufacturer)
                          .Color(manufacturer.Color)
                          .Visible(false)
                          .Labels(labels => labels.Visible(true).Format("{0:N2} " + currentUnit));
                }
            })
            .CategoryAxis(axis => axis.Categories(Model.Select(m => m.Measurement_Record_Date.ToString("dd MMM yyyy")).Distinct()))
            .ValueAxis(axis => axis.Numeric()
                .Line(line => line.Visible(false))
                .Title("Weight (" + currentUnit + ")"))
            .Tooltip(tooltip => tooltip.Visible(true).Format("{0:N2} " + currentUnit))
        )
</div>
</div>
 
<script>
    $(document).ready(function () {
        function toISOStringWithMidday(date) {
            var localDate = new Date(date);
            localDate.setHours(12, 0, 0, 0);
            var offset = localDate.getTimezoneOffset() * 60000;
            var localMidday = new Date(localDate.getTime() - offset);
            return localMidday.toISOString();
        }
 
        $("#refreshChart").click(function () {
            refreshChart();
        });
 
        $("#toggleUnit").click(function () {
            var newUnit = '@currentUnit' == 'gm' ? 't oz' : 'gm';
            refreshChart(newUnit);
        });
 
        $("#clearFilter").click(function () {
            window.location.href = '@Url.Action("ChartTMS", "Target_Measurement_History")';
        });
 
        function refreshChart(newUnit) {
            var selectedFromDate = $("#fromDate").data("kendoDatePicker").value();
            var selectedToDate = $("#toDate").data("kendoDatePicker").value();
            var unitParam = newUnit || '@currentUnit';
 
            if (selectedFromDate && selectedToDate) {
                var difference = Math.abs(selectedToDate.getTime() - selectedFromDate.getTime());
                if (difference > 7 * 24 * 60 * 60 * 1000) {
                    alert("Please select a date range within 7 days.");
                    return;
                }
 
                var fromDateStr = toISOStringWithMidday(selectedFromDate);
                var toDateStr = toISOStringWithMidday(selectedToDate);
 
                window.location.href = '@Url.Action("ChartTMS", "Target_Measurement_History")' + '?fromDate=' + fromDateStr + '&toDate=' + toDateStr + '&unit=' + unitParam;
            } else {
                alert("Please select both from and to dates.");
            }
        }
 
        $("#totalPoolTab").click(function() {
            window.location.href = '@Url.Action("Chart", "Target_Measurement_History")';
        });
 
        $("#tmsTab").click(function() {
            window.location.href = '@Url.Action("ChartTMS", "Target_Measurement_History")';
        });
 
        $("#tmsTab").css("background-color", "lightblue");
 
        $(".tab").click(function() {
            $(".tab").css("background-color", "");
            $(this).css("background-color", "lightblue");
        });
    });
</script>
S M Rahiyan
Top achievements
Rank 1
 updated question on 29 Apr 2024
1 answer
10 views

I am unable to use the filter function i.e I am expecting when I click on the funnel to enter a text or something to take place i.e filtering however no option so far?

 


@model ReportViewModel
@using Kendo.Mvc.UI

@{
    ViewBag.Title = "Report";
}


<link href="https://kendo.cdn.telerik.com/themes/6.4.0/default/default-ocean-blue.css" rel="stylesheet" type="text/css" />
<script src="https://kendo.cdn.telerik.com/2024.1.319/js/kendo.all.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2024.1.319/js/kendo.aspnetmvc.min.js"></script>

<style>

    /* Basic styling for grids */
    .k-grid {
        width: 100%;
        border-collapse: collapse;
    }

    /* Grid header styling */
    .k-grid-header {
        background-color: #f5f5f5;
        border-bottom: 1px solid #ddd;
    }

        /* Grid header cell styling */
        .k-grid-header th {
            padding: 8px;
            font-weight: bold;
            text-align: left;
        }

    /* Grid body styling */
    .k-grid tbody tr {
        border-bottom: 1px solid #ddd;
    }

    /* Grid body cell styling */
    .k-grid tbody td {
        padding: 8px;
    }

    /* Alternate row background color */
    .k-grid tbody tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    /* Hover effect for rows */
    .k-grid tbody tr:hover {
        background-color: #f0f0f0;
    }
</style>

<h2>Employee and Location Report</h2>

<h3>Employees</h3>


@(Html.Kendo().Grid(Model.Employees)
    .Name("gridEmployees")
    .Columns(columns =>
    {
        columns.Bound(e => e.EmployeeId).Title("Employee ID");
        columns.Bound(e => e.FirstName).Title("First Name");
        columns.Bound(e => e.LastName).Title("Last Name");
        columns.Bound(e => e.Department).Title("Department");
        columns.Bound(e => e.Position).Title("Position");
        columns.Bound(e => e.Salary).Title("Salary").Format("{0:C}");
    })
    .Pageable()
    .Sortable()
    .Filterable() // Enable filtering
    )

<h3>Locations</h3>
@(Html.Kendo().Grid(Model.Locations)
        .Name("gridLocations")
        .Columns(columns =>
        {
            columns.Bound(l => l.LocationId).Title("Location ID");
            columns.Bound(l => l.City).Title("City");
            columns.Bound(l => l.Country).Title("Country");
            columns.Bound(l => l.Address).Title("Address");
        })
        .Pageable()
        .Sortable()
        .Filterable()
        )

Eyup
Telerik team
 answered on 26 Apr 2024
1 answer
24 views

I have a chart that tracks website registrations by date, Country and State.  A user selects which country(ies) and state(s) they want to see and the chart should have a column for each country for each date (aggregate by year)

My current View code:

@(Html.Kendo().Chart<DatePoint>()
    .Name("RegistrationDashboard")
    .Title("Total Registrations")
    .Theme("material")
    .DataSource(ds => ds
        .Read(read => read.Action("RegistrationDashboard_Read", "Reports").Data("filterReport"))
        .Group(group =>
            group.Add(grp => grp.Country)
        )
    )
    .Series(series =>
    {
        series.Column(model => model.Value, categoryExpression: model => model.Date).Aggregate(ChartSeriesAggregate.Count).Stack("Country").Name("");
    })
    .CategoryAxis(axis =>
        axis
            .Date()
            .BaseUnit(ChartAxisBaseUnit.Years)
            .MajorGridLines(lines => lines.Visible(false))
    )
    .ValueAxis(axis => axis
        .Numeric()
        .Line(line => line.Visible(false))
    )
    .Tooltip(tooltip => tooltip.Visible(true))
    )

An example of JSON data sent from the datasource (I have a button that refreshes the data source whenever a user chooses new countries/states)


[
  {
    "Date": "/Date(1558584000000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Cundinamarca"
  },
  {
    "Date": "/Date(1562299200000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1572494400000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Antioquia"
  },
  {
    "Date": "/Date(1580533200000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Estado de Mexico"
  },
  {
    "Date": "/Date(1585281600000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Beni"
  },
  {
    "Date": "/Date(1594094400000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1594094400000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1594094400000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1594094400000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1607058000000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Antioquia"
  },
  {
    "Date": "/Date(1608008400000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Jalisco"
  },
  {
    "Date": "/Date(1608008400000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Jalisco"
  },
  {
    "Date": "/Date(1608526800000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Antioquia"
  },
  {
    "Date": "/Date(1626148800000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Queretaro"
  },
  {
    "Date": "/Date(1632801600000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1633924800000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Valle del Cauca"
  },
  {
    "Date": "/Date(1634011200000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Antioquia"
  },
  {
    "Date": "/Date(1640840400000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Aguascalientes"
  },
  {
    "Date": "/Date(1641445200000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Aguascalientes"
  },
  {
    "Date": "/Date(1642741200000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Aguascalientes"
  },
  {
    "Date": "/Date(1643691600000)/",
    "Value": 1,
    "Country": "Mexico",
    "State": "Mexico"
  },
  {
    "Date": "/Date(1650340800000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1650340800000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Santa Cruz"
  },
  {
    "Date": "/Date(1652241600000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Cochabamba"
  },
  {
    "Date": "/Date(1652328000000)/",
    "Value": 1,
    "Country": "Bolivia",
    "State": "Cochabamba"
  },
  {
    "Date": "/Date(1661140800000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Bogota"
  },
  {
    "Date": "/Date(1664856000000)/",
    "Value": 1,
    "Country": "Colombia",
    "State": "Narino"
  }
]
In this scenario, there are 3 countries returned.  For each year (these dates are between 2019 and 2022 but there could be any number of years from as far back as 2010)

I would like to have a series column for each country for each year. Each column would be stacked based on the number of registrations per state.

The user could choose from 1...N countries.  (I'm sure I can set a limit so the chart isn't out of control, but that's not the point)

When I set the datasource group to "State", there is a series column for each year and the legend shows each state. When I group by "Country", there is only 1 series column for each year and the legend shows the countries selected. I have included a screenshot of each grouping

How do I make a series column for each country with the amounts "stacked" for that country's respective states?

Eyup
Telerik team
 answered on 31 Jan 2024
1 answer
42 views

I have a kendo chart with two line series which have the same colour, but have different dash types, dotted and solid. On the chart legend, both series appear with solid lines, but I want the legend to have the dash type displayed - dotted or solid.

Using the HTMLHelper, I've tried to configure the legend using some settings within, but it was not clear from the documentation how this could be configured.

https://docs.telerik.com/aspnet-core/api/kendo.mvc.ui.fluent/chartlegenditemsettingsbuilder#chartlegenditemsettingsbuilder

            .Legend(legend =>
            {
                legend.Position(ChartLegendPosition.Top);
                legend.Item(x =>
                {
                    x.Visual("handler");
                });
            })

In the handler I can see there is options.markers.type, which is currently set to "rect", but from this API reference, there does not seem to be a dotted line type
https://docs.telerik.com/kendo-ui/api/javascript/dataviz/ui/chart/configuration/series.markers.type

Eyup
Telerik team
 answered on 20 Nov 2023
1 answer
69 views

Hi, I have the following chart and I would like to insert a plot band when I click on the chart. I use the same javascript code in the console of the browser and it works, however, it does not work when I do it from my code:


    <script>
        // Hub Settings
        var hub = Global.HubManager.createHub(Global.HubType.BestOrders)
        var hubConnection = hub.connection;
        var hubStart = hub.start;
   
        function onPlotAreaClick(e) {
           console.log(kendo.format("Plot area click :: Timestamp {0} : {1:N0}",
                e.category, e.value
            ));
            
            showVerticalLine();
        }

        function showVerticalLine() {
            console.log("generating vertical line")

            var chart = $("#BestOrdersLive").data("kendoChart");
            var plotbands = chart.options.categoryAxis.plotBands[0];
            console.log(plotbands);
            plotbands = {color: "Red", from: 30, to: 30};
            console.log(plotbands);
            
            chart.redraw();
        }
        
    </script>
   <div id="live-chart">
        @(
            Html.Kendo().Chart<BestOrderViewModel>()
            .Name("BestOrdersLive")
            .AutoBind(true)
            .Theme("Black")
            .Title("Best Orders Live")
            .Legend(true)
            .Events(e => e.PlotAreaClick("onPlotAreaClick"))
            .DataSource(dataSource => dataSource
					.SignalR()
                    .AutoSync(true)
					.Transport(tr => tr
					    .Promise("hubStart")
					    .Hub("hubConnection")
					    .Client(c => c
					        .Read("read")
					        .Create("create")
					        .Update("update")
					        .Destroy("destroy")
					        )
					    .Server(s => s
					        .Read("read")
                            .Create("create")
                            .Update("update")
					        .Destroy("destroy")
					        )
					)
             )
            .Series(series =>
            {
                series.Column(model => model.DealVolume).Name("TradeVolume").CategoryField("ActionTime").Axis("volume").Tooltip(t => t.Visible(true));
                series.Line(model => model.BestBid).Name("BestBid").CategoryField("ActionTime").Color("Yellow");
                series.Line(model => model.BestAsk).Name("BestAsk").CategoryField("ActionTime").Color("Blue");
                series.Line(model => model.DealPricePaid).Name("DealPricePaid").CategoryField("ActionTime").Color("Red").Width(0);
                series.Line(model => model.DealPriceGiven).Name("DealPriceGiven").CategoryField("ActionTime").Color("Green").Width(0);
                series.Line(model => model.DealPriceOTC).Name("DealPriceOTC").CategoryField("ActionTime").Color("Black").Width(0);
                series.Line(model => model.ReferencePrice).Name("ReferencePrice").CategoryField("ActionTime").Color("Grey");
                
            })
            .Transitions(false)
            .CategoryAxis(axis => axis
                .Date()
                .Title("Hora")
                .BaseUnit(ChartAxisBaseUnit.Minutes)
                .Labels(labels => labels.Format("HH:mm:ss").Step(10).Rotation(90))
            .Crosshair(c => c.Visible(true))
            .PlotBands(bands => bands.Add().From(2).To(2).Color("Transparent"))
            )
            .ValueAxis(config =>
                config
                    .Numeric("price")
                    .Visible(true)
                    .Title("Preço (€)")
            )
            .ValueAxis(config =>
                config
                    .Numeric("volume")
                    .Visible(true)
                    .Title("Volume")
            )
            .Zoomable(zoomable => zoomable
            .Mousewheel(mousewheel => mousewheel.Lock(ChartAxisLock.Y))
            .Selection(selection => selection.Lock(ChartAxisLock.Y))
            )
            .Pannable(pannable => pannable
            .Lock(ChartAxisLock.Y)
            )
            )
   </div>

Anton Mironov
Telerik team
 answered on 26 Sep 2023
1 answer
68 views

I have a chart loaded with a data source, and I would like to change the dash type based on the series name. I can't find a property in JavaScript or at the chart level (e.g., DashTypeField)

here is an extract from my code

@(Html.Kendo().Chart<AquascopWeb.pages.ValorisationResultats.Models.EvolPiezometreMultiPointSeriesDataViewModel>()
    .Name("chartEvolPiezometreMultiPoint").HtmlAttributes(new { style = "height:" + height + "px;" })
    .Title(title => title
        .Text("Evolution du type d'observation " + ViewBag.TypeTraite + " - multi-pézomètres ")
        .Font("bold 16px 'Arial Unicode MS'")
    )
    .Legend(legend => legend.Position(ChartLegendPosition.Bottom).Font("11px 'Arial Unicode MS'"))
    .SeriesDefaults(seriesDefaults =>
        seriesDefaults.Line().Style(ChartLineStyle.Normal)
    )
    .Series(series =>
    {
        series.Line(value => value.Data, categoryExpression: category => category.Date).MissingValues(ChartLineMissingValues.Gap).GroupNameTemplate("#= group.value #").Markers(conf=>conf.Visible(false).Size(2)).Style(ChartLineStyle.Normal);     
    })
    .CategoryAxis(axis => axis
            .Name("series-axis")
        .Line(line => line.Visible(false))
        .Labels(label=>label.Visible(false))
        )
    .CategoryAxis(axis =>
    {
        axis.Name("label-axis");
        axis.Line(line => line.DashType(ChartDashType.Dot));
        axis.Categories(model => model.Date);
        axis.Type(ChartCategoryAxisType.Category)/*.MajorGridLines(lines => lines.Visible(false))*/;        
        axis.Justify(true);
        axis.Date().BaseUnit(ChartAxisBaseUnit.Fit)
            .MaxDateGroups(12).Labels(labels => labels.DateFormats(formats => { formats.Days("dd/MM/yyyy"); formats.Months("MMMM yyyy"); }))
            .AutoBaseUnitSteps(unitSteps => unitSteps
                .Days(new int[] { 3 }) // Would produce 31 groups => Skip to weeks.
                .Weeks(new int[] { }) // Not allowed as no steps are defined => Skip to months.
                .Months(new int[] { 1 }) // Results in 2 groups => Chosen.
            );
        axis.Labels(label =>
        {
            label.Rotation("auto");
            label.Font("11px 'Arial Unicode MS'");
        });
    }
    )
    .ValueAxis(axis => axis
        .Numeric()
        .Title(title=>
        {
            title.Text(ViewBag.TypeTraite);
            title.Font("8px");
        })
        .Labels(label =>
        {
            label.Rotation("auto");
        })
        .AxisCrossingValue(0, int.MinValue)
    )
    .Tooltip(tooltip => tooltip
        .Visible(true)
        .Shared(true) 
    .SharedTemplate(
                    "<div style='display: flex;flex-direction:column;'>" +
                        "<div style='display: flex;align-items: center;justify-content: center;font-size: 12px;font-weight: bold;'>#= kendo.toString(category, 'dd MMMM yyyy')#</div>" +
                        "<table class='table table-sm'>" +
                        "   <tbody>" +
                        "# for (var i = 0; i < points.length; i++) { #" +
                        "       <tr>" +
                        "           <td><span style='color:#= points[i].series.color #' class='k-icon k-i-minus minus-grand'></span></td>" +
                        "           <td>#= points[i].series.name #</td>" +
                        "           <td>&nbsp;:&nbsp;</td>" +
                        "           <td><span style='font-size: 12px;font-weight: bold;color:#= points[i].series.color #'>#= points[i].value #</span></td>" +
                        "       </tr>" +
                        "# } #" +
                        "   </tbody>" +

                        "</table>" +
                    "</div>"
                   )
    )
    .Pannable(pannable => pannable
    .Lock(ChartAxisLock.Y)
    )
    .Zoomable(zoomable => zoomable
        .Mousewheel(mousewheel => mousewheel.Lock(ChartAxisLock.Y))
        .Selection(selection => selection.Lock(ChartAxisLock.Y))
    )
    .DataSource(dataSource => dataSource
        .Read(read => read.Action("ChartEvolPiezometreMultiPoint_Read", "GraphEvolPiezometreMultiPoint"))
        .Group(g => g.Add(v => v.Name))
        .Sort(s => s.Add(v => v.Date))
    )
    .Events(events=>events.DataBound("chartEvolPiezometreMultiPoint_DataBound"))
)


Anton Mironov
Telerik team
 answered on 14 Sep 2023
1 answer
61 views

Hi,

I am trying to set up a chart by retrieving the data from an API and the binding  is not working. I can see in the network tab of the browser that I am receiving the correct data from the API, but then the chart is blank, no data being represented. Here is my code:

                           

 

@(
        Html.Kendo().Chart<OrderBookChart>()
            .AutoBind(true)
            .Events(events => events.DataBound("onDataBound"))
            .Events(e => e.Render("onRender"))
            .Legend(false)
            .DataSource(ds => ds
                .Group(group => group.Add(model => model.OrderId))
                .Sort(s => s.Add(model => model.OrderId).Descending())

                .Read(read => read.Action("GetOrderBook", "OrderBookChart").Data("additionalInfo"))
                )
            .SeriesDefaults(seriesDefaults =>
                seriesDefaults.Bar().Stack(true)
            )
            .Series(series =>
            {
                series.Bar(model => model.Quantity).Name("Quantity").CategoryField("Price")
                .Labels(l => l
                    .Visible(true)
                    .Template("#= customLabelFormat(dataItem.Quantity) #")
                    .Position(ChartBarLabelsPosition.OutsideEnd)
                    .Background("transparent")
                );
            })
        .CategoryAxis(axis =>
            axis
            .Labels(labels => labels.Rotation(0))


        )
        .ValueAxis(config => 
            config.Numeric()
            .Visible(true)
            .Color("transparent")
        )
        )

controller:

[Route("contract-order-book-at")]
    [ApiController]
    public class OrderBookChartController : Controller
    {
        private readonly string _urlRestApi;
        private readonly ILogger<UserDataService> _logger;
        private readonly AppSettings _appSettings;

        public OrderBookChartController(ILogger<UserDataService> logger,
                                AppSettings appSettings)
        {
            _logger = logger;
            _appSettings = appSettings;
            _urlRestApi = _appSettings.UrlApiRest;

        }

        [HttpPost]
        public ActionResult GetOrderBook(string contractCode, string date, string time, [DataSourceRequest] DataSourceRequest dSourceRequest)
        {
            List<OrderBookChart> result;
            string baseUrl = _urlRestApi;
            contractCode = "code";
            date = "2023-04-24";
            time = "13:50:25.020";
            var urlRequest = $"{baseUrl}/contract-order-book-at?contractCode={contractCode}&date={date}&time={time}";

            result = LoadDataFromBackendAsync(urlRequest).Result;

            DataSourceResult ds = result.ToDataSourceResult(dSourceRequest);
             return Json(result.ToDataSourceResult(dSourceRequest));

        }

        private async Task<List<OrderBookChart>> LoadDataFromBackendAsync(string urlRequest)
        {
            List<OrderBookChart> result = new List<OrderBookChart>();

            try
            {
                using (HttpClient client = new HttpClient())
                {

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, urlRequest);
                    HttpResponseMessage response = client.SendAsync(request).Result;

                    var responseContent = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseContent))
                    {
                        var responseJson = JArray.Parse(responseContent);

                        foreach (var item in responseJson.Children<JObject>())
                        {
                            result.Add(new OrderBookChart(item.GetValue("traderId").Value<int>(), item.GetValue("side").Value<string>(), item.GetValue("price").Value<decimal>(),
                                item.GetValue("quantity").Value<int>(), item.GetValue("creationTime").Value<DateTime>()));

                        }
                        return result;
                    }
                    else
                    {
                        _logger.LogError($"{nameof(UserDataService)}.{nameof(LoadDataFromBackendAsync)}. Error getting UserPreferences, StatusCode: ({response.StatusCode})");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{nameof(UserDataService)}.{nameof(LoadDataFromBackendAsync)}. Message: {ex.Message}");
            }

            return result;

        }
    }

 

Model:

 public class OrderBookChart
    {


        public int OrderId { get; set; }


        public String Side { get; set; }
       
        public decimal Price { get; set; }


        public int Quantity { get; set; }

        public DateTime CreationTime { get; set; }


        public OrderBookChart(int orderId, string side, decimal price, int quantity, DateTime creationTime)
        {
            OrderId = orderId;
            Side = side;
            Price = price;
            Quantity = quantity;
            CreationTime = creationTime;
        }

    }                           
Guillermo
Top achievements
Rank 1
Iron
 updated question on 12 Sep 2023
1 answer
62 views

I have a chart with the following definition:

@(Html.Kendo().Chart<ChartViewModel>()

.Name("MyChart") .DataSource(d => d .WebApi() .Read(r => r.Action("GetData", "api/Chart").Data("MyChartData")) .Group(g => g.Add(n => n.Group)) ) .Legend(l => l.Position(ChartLegendPosition.Bottom).Labels(n => n.Template("#=series._groupValue#"))) .Series(s => s.Column(n => n.Value, n => n.Colour).Stack(true)) .CategoryAxis(c => c.Categories(n => n.Category)) .ValueAxis(a => a.Numeric()) .Tooltip(t => t.Visible(true).Template("#=value# - #= category #")) )

Note in particular the series definition; I can control the color of individual data points in the chart. This is great.

...but the groups displayed in the legend doesn't take on these colors

I know that I can add the following line to control the group colors:

.SeriesColors(new string[] { "#color1", "#color2", "etc..." })

...but this doesn't guarantee that any particular group will get a specific color. I know in advance what the groups will be, and what colors I want each one to have. ...this seems like a very obvious and simple requirement, but the chart definition doesn't appear to support this for some reason? How do I achieve this?

Tom
Top achievements
Rank 1
Iron
 answered on 08 Sep 2023
1 answer
49 views

I have updated kendo version 2021.3.1109 to 2023.1.425. After upgrading I am not able to see series colors. 


Ivan Danchev
Telerik team
 answered on 05 Sep 2023
1 answer
59 views

The Value Axis isn't showing a DateTime like '5/1/2023 10:00 AM' which is the same DateTime format that the data from my stored procedure is using. I'd like the value axis to show each hour of the day.

Attached is a screenshot of the grid. Thanks!

Here's the chart's code:

 @(Html.Kendo().Chart<BatchPlantHourlyOutputViewModel>()
    .Name("chart")
    .Title("Planned Pour Delivery Times vs Actual Pour Delivery Times")
    .Legend(legend => legend
        .Visible(true)
        .Position(ChartLegendPosition.Bottom)
    )

    .DataSource(dataSource => dataSource
        .Read(read => read.Action("GetBatchPlantHourlyOutputGraph", "Production")
        .Data("PSW.UI.getSelectedInputVals(false)")))
        .Events(e => e.DataBound("PSW.Events.Graph.onBatchPlantHourlyOutputGraphDataBound"))

    .Series(series =>
    {
        series.Line(model => model.ScheduledHour)
           .Name("Scheduled Time");

        series.Line(model => model.StartTime)
            .Name("Actual Time");
    })

    .CategoryAxis(axis => axis
        .Categories(model => model.Output)
        .MajorGridLines(lines => lines.Visible(true))
    )

    .ValueAxis(axis => axis
        .Date()      
        .Labels(labels => labels.Format("{0:MM/dd/yyyy hh:mm:ss}"))
        .Line(line => line.Visible(false))
    )
    )
Anton Mironov
Telerik team
 answered on 22 Jun 2023
Narrow your results
Selected tags
Tags
+? more
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?