asp.net-core-mvc - Asp.Net Core MVC 如何通过 RediretToAction 传输 ModelState?
问题描述
我想将我的 signIn Post 方法重定向回索引页面(索引页面上有登录和注册表单)但是使用模型状态,所以如果登录失败,我可以显示错误。
我已经阅读了多篇关于此的文章,但它们要么已经过时,要么不适用于 asp.net 核心。我找不到解决方案。我试图将 ViewData 或 ModelState 存储在 TempData 中,但这不起作用。
[AllowAnonymous]
[HttpGet]
public IActionResult Index()
{
//How to access have the modelstate from SignIn here?
return View();
}
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(SignInModel model)
{
if (ModelState.IsValid)
{
....
return RedirectToAction("","");
}
// here i need to save the modelstate
return RedirectToAction(nameof(Index));
}
解决方案
不要尝试按原样传递ModelState
,ASP.NET 会覆盖它。但是你可以通过其他任何东西。您的索引方法必须支持状态作为参数:
public IActionResult Index(bool? IsValidAuth = null)
{
if(IsValidAuth!=true) {} // do something
}
然后你可以在的第二个参数中传递状态RedirectToAction
:
public async Task<IActionResult> Index(SignInModel model)
{
// ...
return RedirectToAction(nameof(Index), new {IsValidAuth = false});
}
推荐阅读
- java - Float to Int vs Int to Float 自动转换
- c# - SMART SSD 信息 C#
- marklogic - MarkLogic - 摄取和协调性能调整
- javascript - 如何遍历 Django 模板中的字典?
- javascript - javascript提示不显示
- javascript - CORS 策略已阻止从来源 *** 获取 *** 的访问权限:无“访问控制允许来源”
- android-recyclerview - 为 RecyclerView 项添加底部菜单
- excel - If 语句条件错误 - 对所有条件返回 true
- java - LinkedList输出null的Java实现
- razor - Web.config 相当于“使用静态 MyClass;” 在