基于C# List数据实现Google Charts简单柱状图展示
Hey Andy, I see the issue here—your current C# code is creating a list of strings that look like arrays, but when serialized to JSON, they're just plain text, not actual JavaScript arrays that Google Charts can understand. Let's adjust your backend code first, then pair it with the right frontend JS to render the bar chart.
Step 1: Fix the C# Data Serialization
Instead of building string representations of arrays, create a 2D object list that will serialize directly into the JSON structure Google Charts expects. Here's the revised code:
// Use a list of object lists instead of strings List<List<object>> googleDataset = new List<List<object>>(); foreach(DataRow row in dsAssets.Rows) { // Add each OS name and count as a nested list googleDataset.Add(new List<object> { row["OSNAME"].ToString(), Convert.ToInt32(row["OS Count"]) }); } // Serialize this to JSON—now it will be a proper 2D array var jsonData = JsonConvert.SerializeObject(googleDataset);
This will output JSON like this (a valid JavaScript 2D array):
[ ["Win 2008 R2", 51], ["Win 2016", 10], ["Win 10", 4], // ... rest of your data ]
Step 2: JavaScript to Render the Google Chart
Now you can use this JSON data to draw the bar chart. Here's a complete example, assuming you've passed the jsonData to your frontend (e.g., via a view variable, API endpoint, or inline script):
<!-- Load Google Charts --> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { // Parse the JSON data from your backend (example for ASP.NET MVC/Razor) const osData = JSON.parse('@Html.Raw(jsonData)'); // If fetching via API, replace the line above with: // fetch('/your-api-endpoint') // .then(response => response.json()) // .then(osData => { // // Rest of the chart logic goes here // }); // Create a DataTable for Google Charts const data = new google.visualization.DataTable(); data.addColumn('string', 'Operating System'); data.addColumn('number', 'Count'); // Add all rows from your parsed data data.addRows(osData); // Configure chart options const options = { title: 'Operating System Distribution', width: 800, height: 500, bars: 'vertical' // Change to 'horizontal' for horizontal bars }; // Draw the chart in the designated container const chart = new google.charts.Bar(document.getElementById('os-chart')); chart.draw(data, google.charts.Bar.convertOptions(options)); } </script> <!-- Container where the chart will render --> <div id="os-chart"></div>
Key Notes:
- If you're using a non-Razor frontend setup, replace
@Html.Raw(jsonData)with how you're passing the JSON string to the client (e.g., a global variable or API response). - The
google.charts.Barpackage is used here for modern bar charts; you can switch to thecorechartpackage if you prefer the classic chart style. - Ensuring
OS Countis converted to an integer in C# is critical—Google Charts requires numeric values for the y-axis to render correctly.
That should get your bar chart up and running smoothly!
内容的提问来源于stack exchange,提问作者SismsyeA

