Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

asp.net mvc - how to work with two forms in a single view

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...