首先,这不是一个学校项目。我目前正在创建一个ASP.NET MVC项目,并且是javascript新手。目前,我已经设置了一个Google图表,希望显示在网页上。那很好,但是我不想使用硬编码的数字,而是想从数据库中获取特定数字的总和。我已经在控制器中编写了一个函数,该函数执行SQL查询并以int值的形式返回SUM。
[HttpGet]
[Route("graphs")]
public static int getMonth(int monthNum, int eventTypeId)
{
int identity = -1;
using (SqlConnection con =
new SqlConnection(WebConfigurationManager.ConnectionStrings["PilotDBConnectionString"].ConnectionString)
)
{
con.Open();
using (SqlCommand cmd =
new SqlCommand(
"SELECT SUM(count) FROM DailyAggregate WHERE MONTH(created_on) = @monthNum AND event_type_id = @eventTypeId AND YEAR(created_on) = YEAR(getdate())",
con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@monthNum", monthNum);
cmd.Parameters.AddWithValue("@eventTypeId", eventTypeId);
if (cmd.ExecuteScalar() == null)
{
return 0;
}
return (int)cmd.ExecuteScalar();
}
}
}
此代码可以正常工作,并且在调用时成功返回int。问题是我试图在cshtml索引文件(创建图形的地方)中调用此方法,而不是在值中进行硬编码。我已经阅读了有关Web方法和Ajax的文章,但是至少在我尝试做的事情中,并没有真正掌握它。有人可以向我指出正确的方向,以解决我的问题,或者至少提供一些有关我的问题的相关文档吗?同样,如果有更好的解决方法,也将不胜感激。这是我当前在cshtml文件中的变量:
var Monthly = google.visualization.arrayToDataTable([
['Monthly Data in (Year)', 'Login Count Per App', 'Failed Login', 'Password Change'],
['January', 1500, 234, 234],
['February', 1950, 234, 234],
['March', 2300, 234, 234],
['April', 2300, 234, 234],
['May', 1500, 234, 234],
['June', 234, 234, 234],
['July', getGraphs(7, 8), getGraphs(7, 9), getGraphs(7, 11)],
['August', 234, 234, 234],
['September', 234, 234, 234],
['October', 234, 234, 234],
['November', 234, 234, 234],
['December', 234, 234, 234]
]);
这是我的ajax函数:
function getGraphs(monthNum, eventtypeId) {
$.get({
async: false,
type: "POST",
url: "/api/weasel/graphs",
data: { monthNum: monthNum, eventTypeId: eventtypeId },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
return response;
},
failure: function () {
alert('bad request');
}
});
}