This is a good question, I had problems with this myself when I was a newbie in mvc.
I think a good example here is the registration form and login form on the same page.
A keyword is ViewModel, which is essential to solve this.
In your Model class:
public class LoginModel
{
public string UserName { get; set; }
public string UserPassword { get; set; }
}
public class RegisterModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
}
public class ViewModel
{
public LoginModel LoginModel { get; set; }
public RegisterModel RegisterModel { get; set; }
}
In you Controller:
public ActionResult Index()
{
var model = new ViewModel();
model.LoginModel = new LoginModel();
model.RegisterModel = new RegisterModel();
return View(model);
}
In your View I've used 1 main View, and 2 Partial Views to split it up:
Main View:
@model YourProject.Models.ViewModel
@Html.Partial("_LoginForm", Model.LoginModel)
@Html.Partial("_RegisterForm", Model.RegisterModel)
Partial View _LoginForm:
@model YourProject.Models.LoginModel
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
@Html.TextBoxFor(x => x.UserName)
@Html.PasswordFor(x => x.UserPassword)
<input type="submit" value="Log In" />
}
Partial View _RegisterForm:
@model YourProject.Models.RegisterModel
@using (Html.BeginForm("Register", "Home", FormMethod.Post))
{
@Html.TextBoxFor(x => x.UserName)
@Html.PasswordFor(x => x.UserPassword)
<input type="submit" value="Register" />
}
Please ask if any of the code is unclear for you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…