[英]ASP.NET MVC: How to print a variable returned from a Controller to the View on page load?
I want to sum all the values in a column of my table in SQL Database and display it on page load itself. 我想在SQL数据库的表的一列中汇总所有值,并在页面加载本身上显示它。 What I did is:
我做的是:
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");
}
I want to print it like this (in Records.cshtml view): 我想像这样打印它(在Records.cshtml视图中):
@{var sum = ViewBag.FinalSUM;}
<h2>The Total is: @sum</h2>
Where and how should I call the controller method? 我应该在哪里以及如何调用控制器方法? I tried
@Url.Action("Sumthem", "Records")
in the Razor, but the controller method was not getting called. 我在Razor中尝试了
@Url.Action("Sumthem", "Records")
,但控制器方法没有被调用。 How can I return and print the value of the sum as soon as the page loads? 如何在页面加载后立即返回并打印总和的值?
Edit: I tried this after that, but there was a System.StackOverflow error 编辑:之后我尝试了这个,但是有一个System.StackOverflow错误
@{Html.RenderAction("Sumthem", "Records");
var sum = ViewBag.FinalSUM;}
<h2>The Total is: @sum</h2>
//Returned PartialView instead of View from the Controller.
Action : 行动 :
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())
}
}
Partial View (Records.chstml): 部分视图 (Records.chstml):
@model YourModel
@*You can use data from your model as well*@
<h2>The Total is: @ViewBag.FinalSUM</h2>
Usage (in any view where you actually need your total value to be displayed): 用法 (在您实际需要显示总值的任何视图中):
@Html.RenderAction("Sumthem", "Records")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.