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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With