簡體   English   中英

ASP.NET MVC:如何在Controller加載時將Controller返回的變量打印到View?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM