Reputation: 1201
I have problem in regards my code. My ViewBag.Message is not working and I don't know why it didn't shows up on my page and eventually it does not redirect me to the Index and stuck on my current controller. Here is my code:
Controller
public IActionResult AddPayments()
{
try
{
var sqlQuery = "INSERT INTO LoanPayments (LoanID, DateOfPayment, AmountOfPayment, Remarks) " +
"SELECT lc.LoanID, " +
" CONVERT(DATE, GETDATE(), 101), " +
" ISNULL(CAST(((lt.InterestRate/100 ) * lc.LoanAmount) + lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12) * 2) AS DECIMAL(18,2)), 0), " +
" 'Loan Ledger Created For ' + CAST(GETDATE() AS VARCHAR(50)) " +
" FROM LoanContract lc " +
" INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID ";
_Context.Database.ExecuteSqlCommand(sqlQuery);
ViewBag.Message = "Has successfully created payments today.";
return RedirectToAction("Index");
}
catch (Exception)
{
throw;
}
}
public IActionResult Index()
{
return View();
}
View
<h2>Create Payment</h2>
<span>@ViewBag.Message</span>
<a asp-controller="Payment" asp-action="AddPayments" class="btn btn-primary">Secondary</a>
Any help would be appreciated!
Upvotes: 0
Views: 910
Reputation: 6417
Use TempData instead of ViewBag and it will persist over the redirect... but as people have pointed out in the comments - this is a bad idea, and you should refactor your code to avoid having to do this...
Better idea would be to pass the message as a RouteValue to the index view, but again this is not very clean so I would refactor if I were you...
Edit (Simplified example):
public IActionResult AddPayments()
{
try
{
... // Omitted
return RedirectToAction("Index", "Home", new { message = "Has successfully created payments today.");
}
catch (Exception)
{
throw;
}
}
public IActionResult Index(String message)
{
return View((Object) message);
}
And then in your Index view - you do @Model to show the message.
Note: Ideally you would wrap this in a ViewModel instead of just passing the bare string but hopefully this gives you the right idea?
Upvotes: 1