ASP.NET MVC - How to maintain ModelState from a different controller?

后端 未结 5 2451
时光取名叫无心
时光取名叫无心 2021-02-20 18:43

I have a HomeController with an Index action that shows the Index.aspx view. It has a username/password login section. When the user clicks the submit button, it POSTs to a Lo

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 19:25

    Three options

    1. You could call the action directly, but the client side will not have its URL changed. So instead of calling RedirectToAction you could call the Index() method of the HomeController class directly.

      HomeController c = new HomeController();
      c.ViewData = this.ViewData;
      return c.Index(data);
      

      The one is a bit tricky. Maybe you will have to set other things as well apart from ViewData which is needed for ModelState.

    2. You could as well use TempData dictionary and fill it with whatever data you want and use that.

    3. The simplest one where you provide full path to the view

      return View("~/Views/Home/Index.aspx", data);
      

    A better suggestion used by big players

    If we look at how other sites do this kind of scenario. Take for instance Twitter (As @David says Facebook apparently does it the same). You can sign in from the Home/Index action (so to speak if it was developed using Asp.net MVC). But when login fails it displays a separate login page, that displays validation errors. In your case it would be Account/SignIn. Which would make sense and you could directly return its view with validation errors. When everything would be ok, you'd do it as you do it now. Redirect back to Home/Index.

提交回复
热议问题