问题描述
我的工作我的第一次ASP.net MVC项目,我得到了使用同一页多形式的一些问题。
首先,我创造了2分类别:
(*注册将允许用户注册,
*登录它允许用户登录)。
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.)
然后我用HTML.render他们在我的Logpage集成。
所以我必须使用2个不同的操作。像这样的:
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);
}
这在错误情况下,我重定向到新的页面(全白页包含验证摘要)问题。所以我wondring如何在我的默认页面Logpage显示此错误消息。
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
}
}
在您的code,确保您设置表单的动作:
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)
}
这篇关于在同一个页面ASP.net MVC多个窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!