c# - 有没有办法重用数据注释?

标签 c# asp.net-mvc viewmodel data-annotations code-reuse

有没有一种方法可以在用作 ASP.Net MVC 4 View 中的模型的类中实现数据域(在属性级别)的想法?

考虑这段代码:

public class LoginProfileModel {

    [DisplayName("Login ID")]
    [Required(ErrorMessage = "Login ID is required.")]
    public string LogonID { get; set; }

    [DisplayName("Password")]
    [Required(ErrorMessage = "Password cannot be blank.")]
    [StringLength(20, MinimumLength = 3)]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

这是 ASP.Net MVC 4 中的 LoginProfileModel。它使用各种元数据/数据注释,以便我可以使用此代码创建干净的 View :

@model myWebSite.Areas.People.Models.LoginProfileModel

@using ( Html.BeginForm( "Index" , "Login" ) ) {
    @Html.ValidationSummary()
    @Html.EditorForModel()
    <input type="submit" value="Login" />
}

我在不止一个 View 中使用“登录 ID”和“密码”的想法,因此,在不止一个 View 模型中。我希望能够在单个位置定义密码使用的属性,或者可能是密码本身及其所有数据注释,以便我可以在需要时重用所有这些定义,而不是每次使用时都重新指定它们:

    [DisplayName("Password")]
    [Required(ErrorMessage = "Password cannot be blank.")]
    [StringLength(20, MinimumLength = 3)]
    [DataType(DataType.Password)]
    public string Password { get; set; }

这有可能吗?

最佳答案

以下属性会影响 View 的验证过程。

[Required(ErrorMessage = "Password cannot be blank.")]
[StringLength(20, MinimumLength = 3)]

对于 Validation 属性,您可以像这样创建一个类:

public class PasswordRuleAttribute : ValidationAttribute
    {    
        public override bool IsValid(object value)
        {

            if (new RequiredAttribute { ErrorMessage = "Password cannot be blank." }.IsValid(value) && new StringLengthAttribute(20) { MinimumLength=3 }.IsValid(value) )
                return true;

            return false;
        }
    }

您可以按如下方式使用它:

[PasswordRule]
public string Password{get;set;}

您提到的其他两个属性是直接从 Attribute 类派生的,我认为没有办法将它们合并为一个属性。

我会尽快更新您的修改。

所以现在我们剩下:

[DisplayName("Password")]
[DataType(DataType.Password)]
[PasswordRule]
public string Password{get;set;}

编辑:

根据这篇文章:Composite Attribute , 无法合并属性。

关于c# - 有没有办法重用数据注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745741/

相关文章:

c# - 在 GridView 中显示增量数据的最佳方式是什么?

c# - 如何用C#查询硬盘型号?

c# - 为什么查询字符串参数包含两次 - asp.net boolean

Prism/MEF 新 View 未从 MEF 导入中获取新 View 模型

c# - 检查 XML 中空子节点的最佳方法?

c# - 如何提供可以正确定位.NET Dll作为COM提供程序的私有(private)并排 list ?

asp.net - 从 ASP.NET WebForms 迁移到 ASP.NET MVC

jquery - 在编辑时设置 iggrid 组合值

c# - 升级到 SignalR-2.0.0-beta2 时未生成/signalr/hubs

asp.net-mvc - 我应该使用 EF 在存储库模式中实现 DTO 吗?