Telerik Forums
UI for ASP.NET MVC Forum
1 answer
13 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
34 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
52 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
55 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
54 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
45 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
43 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
53 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
1 answer
121 views
 
In MVC application I am using Kendo column charts and I have the data as below.
TypePercentageDateColor
A25.52/12#2456C7
B702/13#2456C8
B502/14#2456C8
B55.52/15#2456C8
A60.32/13#2456C8

I want to create a column chart with this data, chart should be categorized by Date and there should be multiple columns depending on the type.

I wrote the below code snippet but it isn't working, cannot see the data on UI.

 @(Html.Kendo().Chart<EntitiesA.Report>
                ()
                .Name("Report")
                .Title("ReportA")
                .Legend(legend => legend
                .Position(ChartLegendPosition.Top)
                )
                .DataSource(dataSource => dataSource
                    .Read(read => read.Action("MethodReport", "ReportController"))
                    .Group(group => group.Add(model => model.Type))
                    .Sort(sort => sort.Add(model => model.Date).Ascending())
                )
                .Series(series =>
                {
                    series.Column(model => model.Percentage)
                        .Name("#= group.value # (Percentage)").CategoryField("Date").ColorField("Color");
                })
                .Legend(legend => legend
                    .Position(ChartLegendPosition.Bottom)
                )
                .CategoryAxis(axis => axis
                    .Labels(labels => labels.Format("MM/DD"))
                )
                .ValueAxis(axis => axis.Numeric()
                                .Labels(labels => labels.Format("{0:N0}"))
                                .MajorUnit(20)
                                .Max(100)
                                .Line(line => line.Visible(false))
                )
                .Tooltip(tooltip => tooltip
                .Visible(true)
                .Format("{0:N0}")
                )
                ) 

I don't see any data in the graph it is blank how to fix it, am I missing any logic or piece of code.

Eyup
Telerik team
 answered on 20 Feb 2023
0 answers
108 views

Hi Team, 

I want to display the ORG chart in the Asp.net MVC application but it is not displayed. It shows only an empty page. No error is shown in the console. I have attached the screenshot below.       

My Layout references are as : 

<link rel="stylesheet" href="/Content/kendo/2022.3.913/kendo.common.min.css" />
    <link rel="stylesheet" href="/Content/kendo/2022.3.913/kendo.default.min.css" />
    <link rel="stylesheet" href="/Content/kendo/2022.3.913/kendo.default.mobile.min.css" />
    <script src="https://kendo.cdn.telerik.com/2022.3.1109/js/jquery.min.js"></script>
    <script src="~/Scripts/kendo/2022.3.913/kendo.all.min.js"></script>
    <script src="~/Scripts/kendo/2022.3.913/kendo.aspnetmvc.min.js" type="text/javascript"></script>
    <script src="~/Scripts/kendo/2022.3.913/kendo.dataviz.min.js"></script>
    <script src="~/Scripts/kendo/2022.3.913/kendo.orgchart.min.js"></script>

Razer page code as below:- 

@using Kendo.Mvc.UI;

             @(Html.Kendo().OrgChart<fcPortoloManager.Models.Portolo.OrgChartViewModel>()
    .Name("orgchart")
    .DataSource(dataSource => dataSource
        .Read(read => read.Action("Read", "OrganizationStructure"))
        .Model(m => {
            m.Id(f => f.ID);
            m.ParentId(f => f.ParentID);
            m.Name(f => f.Name);
            m.Title(f => f.Title);           
        })

And controller code is as below :

  public JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(new
            {
                Data = OrgChartData
            }, JsonRequestBehavior.AllowGet);
        }
        public static OrgChartEmployeeViewModel One(Func<OrgChartEmployeeViewModel, bool> predicate)
        {
            return OrgChartData.FirstOrDefault(predicate);
        }
        private static IList<OrgChartEmployeeViewModel> OrgChartData
        {
            get
            {
                IList<OrgChartEmployeeViewModel> source = System.Web.HttpContext.Current.Session["OrgChartEmployees"] as IList<OrgChartEmployeeViewModel>;

                if (source == null)
                {
                    System.Web.HttpContext.Current.Session["OrgChartEmployees"] = source = new List<OrgChartEmployeeViewModel>
                    {
                    new OrgChartEmployeeViewModel() { ID = 1, Name = "Gevin Bell", Title = "CEO", Expanded = true, Avatar = "../content/web/treelist/people/1.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 2, Name = "Clevey Thrustfield", Title = "COO", Expanded = true, ParentID = 1, Avatar = "../content/web/treelist/people/2.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 3, Name = "Carol Baker", Title = "CFO", Expanded = false, ParentID = 1, Avatar = "../content/web/treelist/people/3.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 4, Name = "Kendra Howell", Title = "CMO", Expanded = false, ParentID = 1, Avatar = "../content/web/treelist/people/4.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 5, Name = "Sean Rusell", Title = "Financial Manager", Expanded = true, ParentID = 3, Avatar = "../content/web/treelist/people/5.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 6, Name = "Steven North", Title = "Senior Manager", Expanded = false, ParentID = 3, Avatar = "../content/web/treelist/people/6.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 7, Name = "Michelle Hudson", Title = "Operations Manager", Expanded = true, ParentID = 2, Avatar = "../content/web/treelist/people/7.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 8, Name = "Andrew Berry", Title = "Team Lead", ParentID = 5, Avatar = "../content/web/treelist/people/8.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 9, Name = "Jake Miller", Title = "Junior Accountant", ParentID = 5, Avatar = "../content/web/treelist/people/9.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 10, Name = "Austin Piper", Title = "Accountant", ParentID = 5, Avatar = "../content/web/treelist/people/10.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 11, Name = "Dilyana Newman", Title = "Accountant", ParentID = 5, Avatar = "../content/web/treelist/people/11.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 12, Name = "Eva Andrews", Title = "Team Lead", ParentID = 6, Avatar = "../content/web/treelist/people/12.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 13, Name = "Kaya Nilsen", Title = "Financial Specialist", ParentID = 6, Avatar = "../content/web/treelist/people/13.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 14, Name = "Elena Austin", Title = "Team Lead", ParentID = 4, Avatar = "../content/web/treelist/people/14.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 15, Name = "Lora Samuels", Title = "Lawyer", ParentID = 4, Avatar = "../content/web/treelist/people/15.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 16, Name = "Lillian Carr", Title = "Operator", ParentID = 7, Avatar = "../content/web/treelist/people/17.jpg" },
                    new OrgChartEmployeeViewModel() { ID = 17, Name = "David Henderson", Title = "Team Lead", ParentID = 7, Avatar = "../content/web/treelist/people/16.jpg" },
                };
                }
                return source;
            }
        }

The model code is as below : 

 public class OrgChartEmployeeViewModel {
        public int ID { get; set; }
        public string Name { get; set; }

        public string Title { get; set; }

        public bool Expanded { get; set; }

        public string Avatar { get; set; }

        public int ParentID { get; set; }
    }

 

 

 

 

 

 
Navneet
Top achievements
Rank 1
 asked on 30 Dec 2022
Narrow your results
Selected tags
Tags
+? more
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?