1

I am trying to get a SUM from db and need to display it along with the list. I got the value of Sum in controller but don't know how to pass it to the view having a different model

This is my Controller

public class HomeController : Controller
    {
        public ActionResult About()
      {      

                return View(new Voucher().List());
       }
     public ActionResult Sum() {            
                Total Sum = new Voucher().SUM();
                ViewData["Sums"] = Sum;          
              }
    }

and here comes the two models

namespace Finance.Models
{

    public class AccountDetails
    {
        public DateTime Updated { get; set; }
        public DateTime Date { get; set; }
        public string Des { get; set; }
        public Decimal Amt { get; set; }
        public string VId { get; set; }
        public string AId { get; set; }
        public string LAId { get; set; }
        public string UId { get; set; }
        public string CId { get; set; }
        public int TXId { get; set; }
        public string Per { get; set; }
        //public Decimal Sum { get; set; }

    }
    public class Total
    {
        public Decimal Sum { get; set; }

    }

}

and the main model

        namespace Finance.Models
        {
            public class Voucher
         {      

public List<AccountDetails> List()
        {
            List<AccountDetails> ledger = new List<AccountDetails>();
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = CONNECTION_STRING;
                //using (SqlCommand cmd = new SqlCommand("SELECT * FROM Ledger UNION SELECT 0 AS TXID, 0 AS VID, '' AS AID, SUM(AMT) AS SM, '' AS DES, GETDATE() AS DATE, NULL AS LAID, 0 AS UID, 0 AS CID, '' AS PER FROM Ledger ", con))
                using (SqlCommand cmd =new SqlCommand("SELECT * FROM Ledger",con))
                {
                    try
                    {
                        con.Open();
                        SqlDataReader rdr = cmd.ExecuteReader();

                        while (rdr.Read() == true)
                        {

                            AccountDetails aclist = new AccountDetails();
                            aclist.Date = Convert.ToDateTime(rdr["DATE"]);
                            aclist.AId = (string)rdr["AID"];
                            aclist.Des = (string)rdr["DES"];
                            aclist.Amt = (Decimal)rdr["AMT"];
                            aclist.TXId = (int)rdr["TXID"];
                            aclist.CId = (string)rdr["CID"];



                            if (rdr["LAID"] != DBNull.Value)
                            {
                                aclist.LAId = (string)rdr["LAID"];
                            }
                            else { aclist.LAId = string.Empty; }

                            if (rdr["UID"] != DBNull.Value)
                            {
                                aclist.UId = (string)rdr["UID"];
                            }
                            else { aclist.UId = string.Empty; }


                            if (rdr["VID"] != DBNull.Value)
                            {
                                aclist.VId = (string)rdr["VID"];
                            }
                            else { aclist.VId = string.Empty; }

                            if (rdr["PER"] != DBNull.Value)
                            {
                                aclist.Per = (string)rdr["PER"];
                            }
                            else { aclist.Per = string.Empty; }

                            ledger.Add(aclist); }

                    }
                    catch (Exception e) { throw e; }
                    finally { if (con.State == System.Data.ConnectionState.Open) con.Close(); }
                    return ledger;
                }
            }
        }
                   public Total SUM()
                {

                    using (SqlConnection con = new SqlConnection())
                    {
                        con.ConnectionString = CONNECTION_STRING;
                        Total Tsum = new Total();
                        using (SqlCommand cmd = new SqlCommand("SELECT SUM(AMT)AS Sum FROM Ledger", con))
                        {

                            try
                            {
                                con.Open();
                                SqlDataReader rdr = cmd.ExecuteReader();
                                while (rdr.Read() == true)
                                {

                                    if (rdr["Sum"] != DBNull.Value)
                                    {
                                        Tsum.Sum = (Decimal)rdr["Sum"];
                                    }
                                    else { Tsum.Sum = Decimal.Zero; }
                                    //Sum.Add(Tsum);
                                }
                            }
                            catch (Exception e) { throw e; }
                            finally { if (con.State == System.Data.ConnectionState.Open) con.Close(); }
                            return Tsum ;
                        }
                    }
                }
            }
    }

and the view

@model IEnumerable<Finance.Models.AccountDetails>

    <link href="~/Content/ledger.css" rel="stylesheet" />
   <script src="~/Content/new.js"></script>
<hgroup class="title"> ...</hgroup>

<section class ="tops">
    <div class ="banners">...    </div>
    <div id ="tables">... </div>   
    <div id="base" class=" left">
        <label class ="lbls right"><i>Balance</i></label>
         <label class ="lbls">@ViewData["Sums"]</label>

    </div>
    <div class ="lowpanels">..</div>


</section>
JRU
  • 327
  • 2
  • 9
  • 18
  • you could use ViewBag.Sums = Sum; Or you could leverage the new tuple class and have Tuple,Total> as the model. You can then pull them out as Item1 and Item2 from the Model in the view. – Slicksim Jun 05 '13 at 08:00
  • I would agree with @Slicksim for a quick and dirty fix, but move to a strongly typed viewmodel as quickly as possible so when you come to maintain this in 3 months time you aren't left wondering what `Item1` and `Item2` correspond to. See my answer for details. – Andy Brown Jun 05 '13 at 08:09

1 Answers1

2

A single ActionResult corresponds to a single view, you need something more like:

public class AboutViewModel {
  public Total MyTotal { get; set; }
  public IEnumerable<AccountDetails> MyList { get; set; }
}

public ActionResult About()
{ 
  var voucher = new Voucher();
  var model = new AboutViewModel {
    MyTotal = voucher.SUM();
    MyList = voucher.List();
  }     
  return View(model);
}

And for Views/Home/About.cshtml:

@model Finance.Models.AboutViewModel
<link href="~/Content/ledger.css" rel="stylesheet" />
<script src="~/Content/new.js"></script>
<hgroup class="title"> ...</hgroup>

<section class ="tops">
    <div class ="banners">...    </div>
    <div id ="tables">... </div>   
    <div id="base" class=" left">
        <label class ="lbls right"><i>Balance</i></label>
<!-- ------- Change here ------------------------------------------------ -->
        <label class ="lbls">@Html.Raw(Model.MyTotal.Sum)</label>
    </div>
    @foreach (var item in Model.MyList) {
        ... render stuff ...
    }   
    <div class ="lowpanels">..</div>
</section>

You could also pass the new Voucher().List() as the view model, and use ViewBag to pass the sum, but I would steer away from this and make yourself a strongly typed model in most cases. See my answer here for more info about using ViewBag and ViewData, and also to "Is ViewBag and ViewData also part of state management in asp.net mvc?" for why I wouldn't usually use them. If you do want to use them, you could do:

public ActionResult About() {
    ViewData["Sums"] = Sum;
    return View(new Voucher().List());
}
<label class ="lbls">@Html.Raw(ViewData["Sums"].Sum)</label>
Community
  • 1
  • 1
Andy Brown
  • 18,961
  • 3
  • 52
  • 62