I am new to learning ASP.NET Core MVC. Currently I'm learning how to avoid using viewbag in any of my code since I was told it was not good practice. I would like to know how can I avoid using viewbag when passing method data to the controller and displaying the data in the View. A copy of my simple code is below.
This is my controller:
[HttpGet]
public IActionResult Index()
{
ViewBag.FV = 0;
return View();
}
[HttpPost]
public IActionResult Index(FutureValueModel model)
{
ViewBag.FV = model.CalculateFutureValue();
return View(model);
}
This is my model class:
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;
}
}
Here's the view:
@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>
I have been Googling daily for weeks now I have not been able to come up with a solution. I do not have a job where I can ask a fellow coding partner, so here I am on StackOverflow. FYI this code is from Murach's ASP.NET Core MVC book.
If you don't want to use viewbag, you can use model to pass data like below:
Index view:
result: