how to work with two forms in a single view

前端 未结 3 1077
南笙
南笙 2020-12-09 22:59

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

相关标签:
3条回答
  • 2020-12-09 23:44

    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.

    0 讨论(0)
  • 2020-12-09 23:46

    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.

    0 讨论(0)
  • 2020-12-09 23:58

    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.

    0 讨论(0)
提交回复
热议问题