title: ASP.NET MVC: How to print a variable returned from a Controller to the View on page load?
body: <p>I want to sum all the values in a column of my table in SQL Database and display it  on page load itself. What I did is:</p>
  
  <pre><code>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");   
  }     
  </code></pre>
  
  <p>I want to print it like this (in Records.cshtml view):</p>
  
  <pre><code>@{var sum = ViewBag.FinalSUM;}
  &lt;h2&gt;The Total is: @sum&lt;/h2&gt;
  </code></pre>
  
  <p>Where and how should I call the controller method? I tried <code>@Url.Action("Sumthem", "Records")</code> in the Razor, but the controller method was not getting called. How can I return and print the value of the sum as soon as the page loads?</p>
  
  <p>Edit: I tried this after that, but there was a System.StackOverflow error</p>
  
  <pre><code>@{Html.RenderAction("Sumthem", "Records");
  var sum = ViewBag.FinalSUM;}
  &lt;h2&gt;The Total is: @sum&lt;/h2&gt;
  //Returned PartialView instead of View from the Controller.
  </code></pre>