我的代码有问题。我的ViewBag.Message无效,我不知道为什么它没有显示在我的页面上,最终它没有将我重定向到索引并卡在我当前的控制器上。这是我的代码:
控制器
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();
}
查看
<h2>Create Payment</h2>
<span>@ViewBag.Message</span>
<a asp-controller="Payment" asp-action="AddPayments" class="btn btn-primary">Secondary</a>
&#13;
任何帮助将不胜感激!
答案 0 :(得分:1)
使用TempData而不是ViewBag,它会在重定向上持续存在......但正如人们在评论中指出的那样 - 这是一个坏主意,你应该重构代码以避免不得不这样做...... / p>
更好的想法是将消息作为RouteValue传递给索引视图,但这又不是很干净所以如果我是你,我会重构...
编辑(简化示例):
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);
}
然后在你的索引视图中 - 你做@Model来显示消息。
注意:理想情况下,您可以将其包装在ViewModel中,而不是仅传递裸字符串,但希望这能为您提供正确的想法吗?