如何与两种形式在单个视图中工作 [英] how to work with two forms in a single view

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

问题描述

我可以在一个单一的视图,如何使用它添加多个表单。这可以只用一个模型来完成或者我需要使用不同的模型不同的形式。任何一个可以解释我一个很好的例子,或者建议我对此进行了详细解释好文章。

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.

一个关键字是视图模型,解决这个是至关重要的。

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

请询问是否有任何code不清你。

Please ask if any of the code is unclear for you.

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

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