有没有一种方法可以在用作 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/