我想对SQL数据库中表的一列中的所有值求和并将其显示在页面加载本身上。我所做的是:
public ActionResult Sumthem() {
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("SELECT SUM (Final) FROM SomeTable", con);
cmd.Connection.Open();
ViewBag.FinalSUM = cmd.ExecuteScalar().ToString();
return View("Records");
}
我要这样打印(在Records.cshtml视图中):
@{var sum = ViewBag.FinalSUM;}
<h2>The Total is: @sum</h2>
我在哪里以及如何调用控制器方法?我在Razor中尝试过@Url.Action("Sumthem", "Records")
,但未调用controller方法。页面加载后,如何返回和打印总和的值?
编辑:此后我尝试了此操作,但是出现了System.StackOverflow错误
@{Html.RenderAction("Sumthem", "Records");
var sum = ViewBag.FinalSUM;}
<h2>The Total is: @sum</h2>
//Returned PartialView instead of View from the Controller.
答案 0 :(得分:0)
操作:
install.packages("captioner")
library(captioner)
table_nums <- captioner::captioner(prefix = "Table")
table_nums(name = "MyFirstTable", caption = "Caption")
table(c(1, 2, 3), c(1, 3, 3))
部分视图(Records.chstml):
public ActionResult Sumthem() {
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("SELECT SUM (Final) FROM SomeTable", con);
cmd.Connection.Open();
ViewBag.FinalSUM = cmd.ExecuteScalar().ToString();
return PartialView("Records", new YourModel())
}
}
用法(在实际上需要显示总值的任何视图中):
@model YourModel
@*You can use data from your model as well*@
<h2>The Total is: @ViewBag.FinalSUM</h2>