Kendo UI MVC Chart Binding not working

1 Answer 61 Views
Chart
Guillermo
Top achievements
Rank 1
Iron
Guillermo asked on 06 Sep 2023, 09:22 AM | edited on 12 Sep 2023, 03:00 PM

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;
        }

    }                           

1 Answer, 1 is accepted

Sort by
0
Guillermo
Top achievements
Rank 1
Iron
answered on 07 Sep 2023, 11:33 AM | edited on 12 Sep 2023, 03:00 PM

I solved it by adding new JsonSerializerOptions() { PropertyNameCaseInsensitive = false } to my return statement:

return Json(result, new JsonSerializerOptions() { PropertyNameCaseInsensitive = false });

 

However, now I am struggling with passing data to the controller. I want the controller to receive the contractCode, date and time since they are values that will be recovered from a textbox. I tried using the Data method in Read but it does not work in any way:

     .Read(read => read.Action("GetOrderBook", "OrderBookChart").Data(@<text>
            function() {
                //pass parameters to the Read method
                return {
                    contractCode: "code",
                date: "2023-04-24",
                time: "13:50:25.020"
                }
            }
              </text>))
                )
Anton Mironov
Telerik team
commented on 11 Sep 2023, 07:02 AM

Hi Guillermo,

Thank you for sharing the resolution approach for the first issue with the community.

In order to achieve the second requirement, I would recommend using one of the approaches in the following forum thread answer:

Give a  try to the approaches above and let me know if they achieve the desired result.


Kind Regards,
Anton Mironov

Guillermo
Top achievements
Rank 1
Iron
commented on 12 Sep 2023, 02:59 PM | edited

Hi,

Thanks for the answer.

It does not work using the javascript function. It does work though passing the values directly like this:

.Read(read => read.Action("GetBestOrders", "BestOrders", 
                new { contractCode = "code", fromDate = "2023-09-04", fromTime = "10:26:24.605", toDate = "2023-09-04", toTime = "10:57:33.352"  }))
                )
However, I need to use a JavaScript function because I need to obtain the values from textboxes in the HTML.
Anton Mironov
Telerik team
commented on 14 Sep 2023, 02:21 PM

Hi Guillermo,

I am not sure about the requirements in the last reply - do we should send and receive the contractCode through a JavaScript function or not?

However, this could also be achieved by using an Ajax Request.

Please share the complete scenario and I will try my best to achieve the desired result.

Looking forward to hearing back from you.

Best Regards,
Anton Mironov

Tags
Chart
Asked by
Guillermo
Top achievements
Rank 1
Iron
Answers by
Guillermo
Top achievements
Rank 1
Iron
Share this question
or