![](/img/trans.png)
[英]ASP.NET MVC - How to display data in Razor view returned from Webapi controller
[英]ASP.NET MVC: How to print a variable returned from a Controller to the View on page load?
我想在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")
,但控制器方法没有被调用。 如何在页面加载后立即返回并打印总和的值?
编辑:之后我尝试了这个,但是有一个System.StackOverflow错误
@{Html.RenderAction("Sumthem", "Records");
var sum = ViewBag.FinalSUM;}
<h2>The Total is: @sum</h2>
//Returned PartialView instead of View from the Controller.
行动 :
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())
}
}
部分视图 (Records.chstml):
@model YourModel
@*You can use data from your model as well*@
<h2>The Total is: @ViewBag.FinalSUM</h2>
用法 (在您实际需要显示总值的任何视图中):
@Html.RenderAction("Sumthem", "Records")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.