在 MVC 视图中,您可以拥有尽可能多的表单和所需的字段。为简单起见,请使用单个视图模型,该模型具有页面上每个表单所需的所有属性。请记住,您只能访问您提交的表单中的表单字段数据。因此,如果您在同一页面上有登录表单和注册表单,您可以这样做:
LoginRegisterViewModel.cs
public class LoginRegisterViewModel {
public string LoginUsername { get; set; }
public string LoginPassword { get; set; }
public string RegisterUsername { get; set; }
public string RegisterPassword { get; set; }
public string RegisterFirstName { get; set; }
public string RegisterLastName { get; set; }
}
YourViewName.cshtml
@model LoginRegisterViewModel
@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {})) {
@Html.LabelFor(m => m.LoginUsername)
@Html.TextBoxFor(m => m.LoginUsername)
@Html.LabelFor(m => m.LoginPassword)
@Html.TextBoxFor(m => m.LoginPassword)
<input type='Submit' value='Login' />
}
@using (Html.BeginForm("Register", "Member", FormMethod.Post, new {})) {
@Html.LabelFor(m => m.RegisterFirstName)
@Html.TextBoxFor(m => m.RegisterFirstName)
@Html.LabelFor(m => m.RegisterLastName)
@Html.TextBoxFor(m => m.RegisterLastName)
@Html.LabelFor(m => m.RegisterUsername)
@Html.TextBoxFor(m => m.RegisterUsername)
@Html.LabelFor(m => m.RegisterPassword)
@Html.TextBoxFor(m => m.RegisterPassword)
<input type='Submit' value='Register' />
}
成员控制器.cs
[HttpGet]
public ActionResult LoginRegister() {
LoginRegisterViewModel model = new LoginRegisterViewModel();
return view("LoginRegister", model);
}
[HttpPost]
public ActionResult Login(LoginRegisterViewModel model) {
//do your login code here
}
[HttpPost]
public ActionResult Register(LoginRegisterViewModel model) {
//do your registration code here
}
不要忘记,在调用 BeginForm 时,您传递的控制器名称没有附加“控制器”:
@using (Html.BeginForm("Login", "Member", FormMethod.Post, new {}))
代替:
@using (Html.BeginForm("Login", "MemberController", FormMethod.Post, new {}))