asp.net-mvc 用于将一个属性与另一个属性进行比较的 MVC 数据注释?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2450922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:12:09  来源:igfitidea点击:

MVC data annotation to compare one property to another?

asp.net-mvcdata-annotations

提问by devlife

I've been playing around data annotations in MVC2 and am curious if there is an annotation to compare 2 properties (ie. password, confirm password)?

我一直在玩 MVC2 中的数据注释,并且很好奇是否有注释来比较 2 个属性(即密码、确认密码)?

回答by Cillié Malan

If you are using ASP.Net MVC 3, you can use System.Web.Mvc.CompareAttribute

如果您使用的是 ASP.Net MVC 3,则可以使用 System.Web.Mvc.CompareAttribute

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string PasswordConfirm { get; set; }

回答by Mitch

System.Web.Mvc.CompareAttribute has been deprecated.

System.Web.Mvc.CompareAttribute 已被弃用。

I was able to modify to work like this:

我能够修改为这样的工作:

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

回答by David Morton

There's not one built in, however, you can make your own. See this link, which shows the "PropertiesMustMatchAttribute" that does just what you're looking for.

没有内置的,但是,您可以自己制作。请参阅此链接,其中显示了符合您要求的“PropertiesMustMatchAttribute”。