Can I add more than one form in a single view , how to work with it. Can this be done using only one model or do I need to use different models for different forms. Can any one explain me with a good example or suggest me a good article which is explaining in detail.
问题:
回答1:
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.
回答2:
Lars's answer is a good solution. I would even go with something like this:
public class RegisterModel : LoginModel
{
public int UserId { get; set; }
}
This way you only extend your basic model class and save a couple of lines of code.
回答3:
You should probably use two models and use partial view for each. Otherwise when you post the form you will need to take into consideration that one form may not have been filled out and model may be missing data.