如何避免在 ASP.NET Core 中使用 viewbag

问题描述 投票:0回答:1

我刚开始学习 ASP.NET Core MVC。目前我正在学习如何避免在我的任何代码中使用 viewbag,因为有人告诉我这不是好的做法。我想知道在将方法数据传递给控制器并在视图中显示数据时如何避免使用 viewbag。下面是我的简单代码的副本。

这是我的控制器:

    [HttpGet]
    public IActionResult Index()
    {
        ViewBag.FV = 0;
        return View();
    }

    [HttpPost]
    public IActionResult Index(FutureValueModel model)
    {
        ViewBag.FV = model.CalculateFutureValue();
        return View(model);
    }

这是我的模型类:

  public class FutureValueModel
  {
      public decimal MonthlyInvestment { get; set; }
      public decimal YearlyInteresRate { get; set; }
      public int Years { get; set; }
      public decimal FV { get; set; }

      public decimal CalculateFutureValue()
      {
           int months = Years * 12;
           decimal monthlyInterestRate = YearlyInteresRate / 12 / 100;
           decimal futureValue = 0;

           for (int i = 0; i < months; i++)
           {
               futureValue = (futureValue + MonthlyInvestment) * (1 + monthlyInterestRate);
           }
           return futureValue;
      }
   } 

这里的观点:

   @model FutureValueModel

   @{
       ViewData["Title"] = "Future Interest Calculator";
    }

    <h1>Future Value Calculator</h1>

    <form asp-action="Index" method="post">
        <div>
           <label asp-for="MonthlyInvestment">Monthly Investment:</label>
           <input asp-for="MonthlyInvestment" />
        </div>
        <div>
           <label asp-for="YearlyInteresRate">Yearly Interest Rate:</label>
           <input asp-for="YearlyInteresRate" />
        </div>
        <div>
           <label asp-for="Years">Number of Years:</label>
           <input asp-for="Years" />
        </div>
        <div>
           <label>Future Value:</label>
           <input value="@ViewBag.Fv.ToString("C2")" />
       </div>
       <button type="submit">Calculate</button>
       <a asp-action="Index">Clear</a>
    </form> 

几周来我每天都在谷歌上搜索,现在我还没有想出解决方案。我没有可以请教编码合作伙伴的工作,所以我在 StackOverflow 上。仅供参考,此代码来自 Murach 的 ASP.NET Core MVC 书籍。

c# asp.net-core-mvc viewbag
1个回答
0
投票

我想知道如何在通过时避免使用 viewbag 方法数据到控制器并在视图中显示数据。

如果你不想使用viewbag,你可以使用模型来传递数据,如下所示:

        [HttpGet]
        public IActionResult Index()
        {
            var model = new FutureValueModel();
            model.FV = 0;
            return View(model);
        }

        [HttpPost]
        public IActionResult Index(FutureValueModel model)
        {
            model.FV= model.CalculateFutureValue();           
            return View(model);
        }

索引视图:

    <div>
        <label>Future Value:</label>    
        <input value="@Model.FV.ToString("C2")" />
    </div>

结果:

© www.soinside.com 2019 - 2024. All rights reserved.