Multiple Forms in same page ASP.net MVC
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)
}