C#webform查询数据库数据显示为折线图后端js怎么写
时间: 2024-02-23 22:02:11 浏览: 114
在 C# 的 WebForm 中,可以使用 JavaScript 和 Chart.js 库来实现查询数据库数据并显示为折线图。下面是一个简单的示例:
1. 在 aspx 页面中添加一个 div 和一个 canvas 标签,例如:
```
<div id="chartContainer" style="width: 800px; height: 400px;">
<canvas id="myChart"></canvas>
</div>
```
2. 在后台代码中编写查询数据库数据的代码,并将数据转换为 JSON 格式,例如:
```
protected void Page_Load(object sender, EventArgs e)
{
List<SalesData> salesDataList = new List<SalesData>();
string connectionString = "Data Source=your_server_name;Initial Catalog=your_database_name;User ID=your_user_id;Password=your_password;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT Date, Revenue FROM Sales", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SalesData salesData = new SalesData();
salesData.Date = reader.GetDateTime(0);
salesData.Revenue = reader.GetInt32(1);
salesDataList.Add(salesData);
}
reader.Close();
}
string salesDataJson = JsonConvert.SerializeObject(salesDataList);
Page.ClientScript.RegisterStartupScript(this.GetType(), "SalesDataJson", $"var salesData = {salesDataJson};", true);
}
```
3. 在 aspx 页面中引入 Chart.js 库和后台传递的数据,并编写 JavaScript 代码绘制折线图,例如:
```
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: salesData.map(x => x.Date),
datasets: [{
label: 'Sales',
data: salesData.map(x => x.Revenue),
borderColor: 'blue',
fill: false
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
```
这样就可以在 WebForm 中查询数据库数据并显示为折线图了。当然,具体的实现方式还需要根据你的具体需求来做相应的调整。
阅读全文
相关推荐


















