gpt4 book ai didi

javascript - MVC5实时刷新Chart.js

转载 作者:行者123 更新时间:2023-12-03 10:38:09 25 4
gpt4 key购买 nike

我目前正在创建一个仪表板来显示通过 Chart.js 从 Google Analytics 获取的信息。目标是允许用户选择指标、日期和绘制图表的时间间隔,仪表板将调用 Google 并在单击按钮时更新图表。仪表板是在 Visual Studio 2013 的 MVC 应用程序中创建的。仪表板当前如下所示:Dashboard Sample右边画得不好的盒子是我打算放置按钮的地方。我遇到的问题是为按钮创建功能。我对 MVC 非常陌生,而且我相对确定我已经破坏了逻辑,因为我没有 View 。这个应用程序基本上已经成为 View 的 Controller 。 (这是在看了几十个 MVC 教程之后发生的事情。

Controller 目前看起来像这样:

public enum Metrics{users, newUsers, percentNewSessions,  sessionsPerUser, sessions, bounces, bounceRate, sessionDuration, hits}

public enum Interval{Today, Yesterday, LastWeek, LastTwoWeeks, Daily, Weekly, Monthly, Yearly}

public class HomeController : Controller
{
public ActionResult Index()
{
string accountEmailAddress = "email@thing.com";
string keyPath = Server.MapPath("path");
var certificate = new X509Certificate2(keyPath, "blah", X509KeyStorageFlags.Exportable);//Creates certificate

var credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(accountEmailAddress)
{
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(certificate));//Creates credentials ot GA server

AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "Dash"
});//Starts the service up.

string profileId = "ga:59346790";
string startDate = "2012-06-07";
string endDate = "2015-02-17";
string timing = "Yearly";
string metrics = "ga:users";
string[] dates = DateList(startDate, endDate, timing);
List<string> ColumnName = new List<string>();
List<double> values = new List<double>();
if (timing.Equals("Daily"))
{
for (int i = 0; i < dates.Length - 1; i++)
{
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, dates[i], dates[i], metrics);
GaData data = request.Execute();
ColumnName.Add(DateLabel(dates[i]));
if (data.Rows == null)
{
values.Add(0);
}
else
{
foreach (var row in data.Rows)
{
foreach (var item in row)
{
values.Add(Convert.ToDouble(item));
}
}
}
}
}
else
{
for (int i = 0; i < dates.Length - 2; i+=2)
{
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, dates[i], dates[i + 1], metrics);
GaData data = request.Execute();
ColumnName.Add(DateLabel(dates[i]));
if (data.Rows == null)
{
values.Add(0);
}
else
{
foreach (var row in data.Rows)
{
foreach (var item in row)
{
values.Add(Convert.ToDouble(item));
}
}
}
}
}
List<Metrics> metricList = Enum.GetValues(typeof(Metrics)).Cast<Metrics>().ToList();
List<Interval> intervalList = Enum.GetValues(typeof(Interval)).Cast<Interval>().ToList();
ViewBag.Metrics = new SelectList(metricList);
ViewBag.Intervals = new SelectList(intervalList);
values.OrderByDescending(m => values.Min());
ViewBag.ColumnName = ColumnName.ToArray();
ViewBag.Values = values.ToArray();
int[] test = { 3, 5, 6, 7, 3, 8, 9 };
ViewBag.intArray = test;
string[] testLabel = { "This", "Is", "A", "Test", "You", "Got", "It?" };
ViewBag.strArray = testLabel;
return View();
}

private static string DateLabel(string date){ ....code}
private static string[] DateList(string startDate, string endDate, string timing){...code}
}

这是我的观点: @{ ViewBag.Title = "首页";

double[] result = ViewBag.Values;
string[] labels = ViewBag.ColumnName;
string test = "";
string label = "";

for(int i =0; i<= result.Length - 1; ++i)
{
if(i==0)
{
test = test + result[i].ToString();
}
else
{
test = test + "," + result[i].ToString();
}
}

for (int i = 0; i <= labels.Length - 1; ++i)
{
if (i == 0)
{
label = label + labels[i].ToString();
}
else
{
label = label + "," + labels[i].ToString();
}
}
}
<label for="myChart">
Google Analytics<br />
<canvas id="myChart" width="800" height="400"></canvas>
</label>
<div>
<label for="Metrics">
Metrics <br />
@Html.DropDownList("Metrics", (SelectList)ViewBag.Metrics, new { @class = "form-control" })
</label>
<label for="Intervals">
Interval<br />
@Html.DropDownList("Intervals", (SelectList)ViewBag.Intervals, new { @class = "form-control" })
</label>
<label for="StartDate">
Start Date<br />
@Html.TextBox("StartDate")
</label>
<label for="EndDate">
End Date<br />
@Html.TextBox("EndDate")
</label>
</div>

<script>
var result = "@test";
var resultsArray = result.split(',');
var newLabels = "@label";
var labelsArray = newLabels.split(',');
var context = $("#myChart").get(0).getContext("2d");
var data = {
labels: labelsArray,

datasets: [{

label: "My First dataset",
fillColor: "rgba(220,220,220,0,2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: resultsArray

}]
}
var options = {
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: true,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.4,
//Boolean - Whether to show a dot for each point
pointDot: true,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill: true,

}
var myLineChart = new Chart(context).Line(data, options)

$(document).ready(function () {
$('#StartDate').datepicker();
$('#EndDate').datepicker();
});
</script>

如果有人可以向我展示如何使用我当前的代码来完成创建一个按钮来实时刷新仪表板,那就太好了,尽管就 MVC 标准而言,该代码有点 FUBAR。我愿意接受温和的(或不那么温和的)插入他走向正确的方向。

最佳答案

不要在 Controller 的 Index 方法中填充图表数据,也不要在 View 加载时绘制图表数据。创建一个单独的方法(甚至可以查看 WebAPI),该方法仅返回用于填充图表的 JSON 数据。调用该方法并在单击按钮时刷新图表。用于填充图表的 JavaScript 也应该位于单独的文件中,并且不包含在 View 的文本中。图表将刷新,而无需重新加载整个页面。

Google for AJAX(如果您想了解更多有关如何完成此操作的信息)。

我还会考虑使用SignalR这样您就不需要按钮,服务器可以在新数据可用时将新数据发送到图表,但这可能是一项高级技术。

关于javascript - MVC5实时刷新Chart.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28907713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com