简体   繁体   中英

Dynamic Chart Rendering in Razor View

I've data grouping in C# and trying to bind it from Razor view as follows with high charts:

//Dynamic Chart - Starts
 @if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
     {
         foreach (var item in Model.aLstTopsideModuleGroupBy)
         {
          foreach (var item2 in item)
          {
              int i = 0;
         <text>
Highcharts.chart('container'@i, {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Demo Chart'
    },
    subtitle: {
        text: ''
    },
    xAxis: {
        categories: [
            'Structural Primary',
            'Structural Secondary',
            'Mechanical',
            'Piping',
            'Electrical',
            'Instrument',
            'Telecommunication',
            'Safety',
            'Architectural  ',
            'Other/ Future Load  ',
            'Live Load'
        ],
        crosshair: true
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Weight Data'
        }
    },
    tooltip: {
        headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
        pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
            '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
        footerFormat: '</table>',
        shared: true,
        useHTML: true
    },
    plotOptions: {
        column: {
            pointPadding: 0,
            borderWidth: 0
        }
    },
    series: [
        {
            name: 'Dry',
            data: '@item2.BaseDry'

        }, {
            name: 'Operating',
            data: '@item2.BaseOp'

        }]
});
</text>
              i++;
          }

         }
     }
     //Dynamic Chart - Ends 

The data grouping is something as follows:

Data 1
1, 2, 3, 4, 5

Data 2
1, 2, 3, 4, 5

The above I require to create two different charts depending upon the data set, that's why used the followg:

 Highcharts.chart('container'@i, {});

In the frontend, trying to do the following:

              <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
                        @if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
                        {
                            int i = 0;
                            foreach (var item in Model.aLstTopsideModuleGroupBy)
                            {
                                <div id="container" @i></div>
                                <p class="highcharts-description">

                                </p>
                            }
                            i++;
                        }
                    </div>
                </div>
            </div>

In the browser's inspect element, getting this exception:

Uncaught SyntaxError: missing ) after argument list

I was trying to follow this link but failed - Razor With JavaScript

Is there any way I can make the chart dynamic with Razor view rather Ajax call? This is what I am trying to implement:

High Charts

When using razon and javascript you need to be mindful that you can't really generate javascript code using razor. To the best of my knowledge you need to create a javascript function in the same view or a parent view if you are using a partial that creates the charts and have razor call it along with creating the div placeholder to display the chart, the data on the chart should be loaded via ajax calls.

The following code is an example and should not be copy and pasted without modification, you need to tweak it for your requirements, this is only to show the concept. If anyone else has a more elegant solution, please contribute.

async function createChart(containerName, dryArgument, operatingArgument){
    let dryData = await fech(`@Url.Action("GetDryData")/?argument=${dryArgument}`)
  let operatingData = await fech(`@Url.Action("GetOperatingData")/?argument=${operatingArgument}`)
  Highcharts.chart(containerName, {
      chart: {
          type: 'column'
      },
      title: {
          text: 'Monthly Average Rainfall'
      },
      subtitle: {
          text: 'Source: WorldClimate.com'
      },
      xAxis: {
          categories: [
              'Jan',
              'Feb',
              'Mar',
              'Apr',
              'May',
              'Jun',
              'Jul',
              'Aug',
              'Sep',
              'Oct',
              'Nov',
              'Dec'
          ],
          crosshair: true
      },
      yAxis: {
          min: 0,
          title: {
              text: 'Rainfall (mm)'
          }
      },
      tooltip: {
          headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
          pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
              '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
          footerFormat: '</table>',
          shared: true,
          useHTML: true
      },
      plotOptions: {
          column: {
              pointPadding: 0.2,
              borderWidth: 0
          }
      },
      series: [
        {
            name: 'Dry',
            data: JSON.parse(dryData)

        }, {
            name: 'Operating',
            data: JSON.parse(operatingData)

        }]
  });
}

Note that you need to create two ContenResult() actions in the controller to get the data.

To call them you can then use:

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
            //Dynamic Chart - Starts
             @if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
                 {
                     foreach (var item in Model.aLstTopsideModuleGroupBy)
                     {
                      foreach (var item2 in item)
                      {
                          int i = 0;
                     
                            <div id="container@i"></div>
                            <p class="highcharts-description">

                            </p>
                          
                          <script>
                            window.onload = function () {
                                createChart('#container@i',@item2.BaseDry,@item2.BaseOp);
                            };
                        </script>

                        i++;
                      }

                     }
                 }
                 //Dynamic Chart - Ends 
        </div>
    </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM