MVC ViewData如何工作?

Mat*_*att 3 asp.net-mvc

我正在玩一个MVC应用程序只是为了学习这项技术.我正在嘲笑一个支票登记应用程序,它跟踪一个支票账户,什么清算了银行,什么没有.我使用EF作为我的模型,在编辑,创建等方面,一切似乎都正常工作.但是,我在顶部有几个总计.一个显示银行的余额,另一个显示实际余额.它大部分时间都可以工作,但是当我执行编辑时,它并不总是准确地反映新的总数,我需要在每次更改时更新(即当某些东西清除银行时):

[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();
}
Run Code Online (Sandbox Code Playgroud)

我在索引视图中显示实际和其他余额如下:

<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>
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 7

你错过了MVC的一部分...... M.

您应该填充包含视图所需的所有数据项的模型.这是你的控制器应该是什么样子.

[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);
}
Run Code Online (Sandbox Code Playgroud)

然后您的视图将如下所示(注意,模型中的所有内容都是强类型的):

<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>
Run Code Online (Sandbox Code Playgroud)

您将需要创建一个模型,它只是一个包含所需属性的类.