我似乎无法让我的课程实例化。当我运行我的Web应用程序时。我试图将我的课程成绩传递到一些谷歌图表,但似乎无法让课程实例化。任何帮助/链接/代码将不胜感激。
这就是我似乎陷入困境的地方:
DashboardController.cs
using System.Web.Mvc;
namespace AudAPIApp.Controllers
{
[Authorize]
public class DashboardController : Controller
{
public ActionResult Index()
{
GoogleAPI googleReport = new GoogleAPI();
return View(googleReport);
//New to MVC not sure if this is how to instantiate my class?
}
}
}
我已经在我的课程中放置了代码块,而我的应用程序并没有通过它。
GoogleApi.cs
namespace AudAPIApp
{
public class GoogleAPI
{
public static GetReportsResponse googleRpt;
static void Main(string[] args)
{
try
{
//code that gets all the data. This all works in a console app I made. My challenge is making it work in MVC.
var response = batchRequest.Execute();
googleRpt = response;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
Index.cshtml
<script>
var googleData = [];
@{
//this is where I get error: "Object reference not set to an instance of an object."
foreach(var x in GoogleAPI.googleRpt.Reports.First().Data.Rows)
{
@:googleData.push([@x.Dimensions, @x.Metrics])
}
}
</script>
我知道这不应该工作,因为它使用的是未实例化的对象。
答案 0 :(得分:0)
首先,因为它看起来像一个网站,所以不要使用Main,因为你没有一个控制台应用程序挂钩,并且不要使它静态。像这样:
一般情况下(可能过度简化),如果你的类只有静态的东西,那么你不需要实例化它(static =在类的所有实例之间共享,所以创建一个新的实例不会做任何事情)。
namespace AudAPIApp
{
public class GoogleAPI
{
public GetReportsResponse googleRpt;
public void GenerateReport()
{
try
{
//code that gets all the data. This all works in a console app I made. My challenge is making it work in MVC.
var response = batchRequest.Execute();
googleRpt = response;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
接下来,更改控制器以创建该对象,调用generate函数并将其作为模型传递
using System.Web.Mvc;
namespace AudAPIApp.Controllers
{
[Authorize]
public class DashboardController : Controller
{
public ActionResult Index()
{
GoogleAPI googleReport = new GoogleAPI();
googleReport.GenerateReport();
return View(googleReport);
//New to MVC not sure if this is how to instantiate my class?
}
}
}
您现在已将名为googleReport的GoogleAPI实例传递给您的视图,并在googleReport.googleRpt中填充了您的报告。
//Add this to the top of your cshtml file
@model AudAPIApp.GoogleAPI
<script>
var googleData = [];
@{
//this is where I get error: "Object reference not set to an instance of an object."
foreach(var x in Model.googleRpt.Reports.First().Data.Rows)
{
@:googleData.push([@x.Dimensions, @x.Metrics])
}
}
</script>
您现在可以将您的报告作为Model对象的属性获取,该对象实际上是您在控制器中创建的GoogleAPI对象。