如何在一个视图中处理两个表单 [英] how to work with two forms in a single view

查看:28
本文介绍了如何在一个视图中处理两个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在一个视图中添加多个表单吗,如何使用它.这可以仅使用一种模型来完成,还是我需要为不同的形式使用不同的模型.谁能用一个很好的例子来解释我,或者给我推荐一篇详细解释的好文章.

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.

推荐答案

这是个好问题,当我还是 mvc 新手时,我自己也遇到了这个问题.

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.

一个关键字是ViewModel,这是解决这个问题必不可少的.

A keyword is ViewModel, which is essential to solve this.

在您的模型类中:

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; }
}

在你的控制器中:

    public ActionResult Index()
    {
        var model = new ViewModel();
        model.LoginModel = new LoginModel();
        model.RegisterModel = new RegisterModel();
        return View(model);
    }

在您的视图中,我使用了 1 个主视图和 2 个部分视图将其拆分:

In your View I've used 1 main View, and 2 Partial Views to split it up:

主视图:

@model YourProject.Models.ViewModel

@Html.Partial("_LoginForm", Model.LoginModel)
@Html.Partial("_RegisterForm", Model.RegisterModel)

部分视图_LoginForm:

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" />
}

局部视图_RegisterForm:

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.

这篇关于如何在一个视图中处理两个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆