Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Forms in same page ASP.net MVC

Tags:

asp.net-mvc

I working on my first ASP.net MVC project and and i got some problems using multi forms in same page. First i have created 2 partial Class : (*Register will allow user to register, *Login it allow user to login.)

Then i used HTML.render to integrate them in my "Logpage". So i have To uses 2 different Action. Like this one:

    [HttpPost]
    public ActionResult Login(LogModel.Login Model)
    {
        if (ModelState.IsValid)
        {

            if (LogModel.Login.Verifuser(Model.IDUser, Model.Password))
            {
                FormsAuthentication.SetAuthCookie(Model.IDUser, false);
                if (LogModel.Login.IsAdmin(Model.IDUser, Model.Password))
                {
                    return View("Admin/Index");
                }
                else
                {
                    return View("Agence/Index");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalide username or Password");
                return View(Model);
            }
        }
        return View(Model);
    }

The problem that on error case i'm redirect to new Page(White page contain validation summary). So i'm wondring how to show this error message in my default page Logpage.

like image 766
Chlebta Avatar asked Apr 03 '12 16:04

Chlebta


1 Answers

You can solve this with three actions and a complex model.

 public class LoginOrRegisterViewModel
 {
      public Models.RegisterViewModel Register { get; set; }
      public Models.LoginViewModel Login { get; set; }
 }


 [HttpGet]
 public ActionResult Login()
 {
      return View("Login", new LoginOrRegisterViewModel());
 }

 [HttpPost]
 public ActionResult Register(Models.LoginViewModel model)
 {
      if(!ModelState.IsValid)
           return View("Login", new LoginOrRegisterViewModel(){ Register = model });
      else
      {
           //TODO: Validate the user
           //TODO: Write a FormsAuth ticket
           //TODO: Redirect to somewhere
     }
 }

 [HttpPost]
 public ActionResult Login(Models.RegistrationViewModel model)
 {
      if(!ModelState.IsValid)
           return View("Login", new LoginOrRegisterViewModel(){ Login = model});
      else
      {
           //TODO: CRUD for registering user
           //TODO: Write forms auth ticket
           //TODO: Redirect
     }
 }

In your code, make sure that you set the action of the Form:

 @model Models.LoginOrRegisterViewModel

 @using(Html.BeginForm("Login", "Controller", FormMethod.Post, new { id = "loginForm"}))
 {
       @Html.EditorFor(m => Model.Login)
 }

 @using(Html.BeginForm("Register", "Controller", FormMethod.Post, new { id = "registerForm"}))
 {
       @Html.EditorFor(m => Model.Register)
 }
like image 195
Nick Bork Avatar answered Sep 19 '22 04:09

Nick Bork