首页 > 解决方案 > 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));
        }

标签: asp.net-core-mvc

解决方案


不要尝试按原样传递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});
}

推荐阅读