支持MVC3多种形式与验证annotiation最好的方法 [英] Best way to support multiple forms in mvc3 with validation annotiation

查看:309
本文介绍了支持MVC3多种形式与验证annotiation最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个MVC3项目,我想有一个页面上2种形式。一种形式是,以注册用户和另一个是登录

In an mvc3 project I want to have 2 forms on one page. One form is to register a user and the other one is to logon.

有两个提交按钮。一个注册,一个登录。

There are two submit buttons. One to register, one to logon.

在模型中,有验证annotiation例如用户名是必需的,密码必须等匹配,

In the model there are validation annotiation e.g. username is required, passwords must match and so on.

的问题是,即验证annotiation相互影响。这样,当注册按钮为pressed,为登录用户验证是无效的。

The problem is, that the validation annotiation affect each other. So that when the register button is pressed, the validation for the logon username is invalid.

我曾尝试写局部视图,或在一个视图中做的一切的编写一些定制annotiations,尊重pressed按钮。

I have tried to write partial views, or to do everything in one view an write some custom annotiations, respecting the pressed button.

但是,这一切似乎都错了。那不可能是最好的解决方案。

But that all seems to wrong. That can not be the best solution.

什么是实现这一目标的最佳途径。

What would be the best way to achieve this.

推荐答案

我处理这个问题的方法;你需要2个或更多的ViewModels绑定到你的观点,是创建一个视图模型encompasing与2个属性,然后分配给个人的登录的和的注册的模型,每个属性。例如(减去你希望的任何验证添加)

The way I approach this problem; where you need 2 or more ViewModels binding to your view, is to create a encompasing ViewModel with 2 properties, then assign the individual login and register models to each property. e.g. (minus any validation you wish to add)

public class LogOnViewModel {
    public string UserName { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel {
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

public class WelcomeScreenViewModel {
    public LogOnViewModel LogOnModel { get; set; }
    public RegisterViewModel RegisterModel { get; set; }
}

在我的欢迎查看我早就 @model namespace.WelcomeScreenViewModel 顶部有2个部分景色指向_LogOn和_Register像这样一起

In my Welcome view I would have @model namespace.WelcomeScreenViewModel at the top together with 2 partial views pointing to _LogOn and _Register like this:

@Html.Partial("_LogOn", Model.LogOnModel)
@Html.Partial("_Register", Model.RegisterModel)

您的局部视图传递正确的模型,也可重复使用的其他局部视图这样,凡在你的Web应用程序。

That way your partial views are passed the correct models and are also re-usable as partial view else where in your web app.

这篇关于支持MVC3多种形式与验证annotiation最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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