Lyn*_*ark 1 asp.net-core razor-pages
希望这不是一个愚蠢的问题-我正在将应用程序从.net core mvc重写为.net core Razor。在MVC中,我使用Viewbags创建并显示操作成功的确认,否则显示错误消息。.net核心2.1中的Razor页面似乎没有以相同的方式使用或使用Viewbag。
如何在Razor页面上实现上述目标?以任何代码段为例将很有帮助。谢谢
我们可以使用Post-Redirect-Get模式在操作后显示一条消息。
这是一个示例,该示例用于TempData在POST期间存储消息,然后重定向到GET。使用TempData存储消息特别适合于重定向,因为数据仅存在,直到有人读取为止。
SomePage.cshtml
@page
@model SomePageModel
@if(TempData[SomePageModel.MessageKey] is string message)
{
<p>@message</p>
}
<form method="POST">
<button type="submit">POST!</button>
</form>
Run Code Online (Sandbox Code Playgroud)
SomePage.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace temp.Pages
{
public class SomePageModel : PageModel
{
public const string MessageKey = nameof(MessageKey);
public void OnGet() { }
public IActionResult OnPost() {
TempData[MessageKey] = "POST Success!";
return RedirectToAction(Request.Path); // redirect to the GET
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种模式也适用于HTTP方法,例如PUT和DELETE。只需替换任何其他HTTP动词即可;例如,我们可以执行Put-Redirect-Get。
| 归档时间: |
|
| 查看次数: |
1022 次 |
| 最近记录: |