I am toying around with an MVC application just to learn the technology. I am mocking up a check register application that keeps track of a checking account, what has cleared the bank and what has not. I am using EF for my model and everything seems to be working correctly insofar as Edit, Create, etc. However, I have a couple of totals at the top. One to show the bank's balance and another to show the actual balance. It works most of the time but when I do Edit's it does not always accurately reflect the new total and I need it to update everytime a change is made (i.e when something clears the bank):
[Authorize(Roles = "admin, checkUser")]
public ActionResult Index()
{
var resultSet = from myChecking in chk.tblCheckings
orderby myChecking.id descending
select myChecking;
ViewData.Model = resultSet.Take(45).ToList();
//for balances
var actualBalance = from theChecking in chk.tblCheckings
select theChecking.deposit - theChecking.withdrawal;
var bankBalance = from theChecking in chk.tblCheckings
where theChecking.cleared == true
select theChecking.deposit - theChecking.withdrawal;
//get bank balance
ViewData["bankBalance"] = bankBalance.Sum();
//get actual balance
ViewData["actualBalance"] = actualBalance.Sum();
return View();
}
I am showing the actual and other balance in the Index view as follows:
<td colspan="9" style="text-align: center; font-size: 11pt; color: white;">
<%= string.Format("Bank Balance: {0:c}", ViewData["bankBalance"]) %> ------
<%= string.Format("Actual Balance: {0:c}", ViewData["actualBalance"]) %>
</td>
You are missing part of the MVC... the M.
You should be populating a model that contains all the data items needed by the view. This is what your controller should look like.
[Authorize(Roles = "admin, checkUser")]
public ActionResult Index()
{
IndexModel model = new IndexModel();
var resultSet = from myChecking in chk.tblCheckings
orderby myChecking.id descending
select myChecking;
model.Transactions = resultSet.Take(45).ToList();
//for balances
var bankBalance = from theChecking in chk.tblCheckings
where theChecking.cleared == true
select theChecking.deposit - theChecking.withdrawal;
model.BankBalance = bankBalance.Sum();
//get actual balance
var actualBalance = from theChecking in chk.tblCheckings
select theChecking.deposit - theChecking.withdrawal;
model.ActualBalance = actualBalance.Sum();
return View(model);
}
Then your view would look like this (note, everything in your model is strongly typed):
<td colspan="9" style="text-align: center; font-size: 11pt; color: white;">
<%= string.Format("Bank Balance: {0:c}", Model.BankBalance) %> ------
<%= string.Format("Actual Balance: {0:c}", Model.ActualBalance) %>
</td>
You will need to create a model, which is just a class with all the properties you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With