我有一个MVC Model类,如下所示:
[ValidateNewRegistration]
public class NewRegistrationModel {
[System.ComponentModel.DisplayName("Profile Display Name")]
[Required(ErrorMessage = "Display Name must be specified.")]
[StringLength(50)]
public string DisplayName { get; set; }
[System.ComponentModel.DisplayName("Email Address")]
[Required(ErrorMessage = "Email address must be specified.")]
[RegularExpression("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$",
ErrorMessage = "The email address you specified is invalid.")]
[StringLength(100)]
public string EmailAddress1 { get; set; }
}
在我看来,我有这个:
@Html.ValidationSummary()
@Html.EditorForModel()
我理解如何使用元数据来标记属性,但我想要实现的是实现我自己的编辑模板,其中包含两个字段...名字和姓氏,将至少用于在我的网站上有1/2个地方。
如何添加错误消息以使它们出现在验证摘要中,但是以包含在EditorTemplate中的方式?
我正在寻找的长期内容是能够将“[UIHint(” - Editor Template--“)]”放入类中,并使编辑器模板自足以发布它的onw错误消息对于表单域。因此,我不必将元数据添加到[Required ...]或[RegularExpression ...]的类中。我的最终目标是这样一个类:
[ValidateNewRegistration]
public class NewRegistrationModel {
[System.ComponentModel.DisplayName("Profile Display Name")]
[UIHint("DisplayName")]
public string DisplayName { get; set; }
[System.ComponentModel.DisplayName("Email Address")]
[UIHint("EmailAddress")]
public string EmailAddress1 { get; set; }
[System.ComponentModel.DisplayName("Email Address (confirm)")]
[UIHint("EmailAddress")]
public string EmailAddress2 { get; set; }
}
答案 0 :(得分:0)
此处已经提出了类似的问题:Is there a way to reuse data annotations?
检查那里的解决方案,如果您需要任何特定
的帮助,请发表评论 class UIHintAttribute : ValidationAttribute
{
public string Field { get; set; }
public UIHintAttribute(string field)
{
Field = field;
}
public override bool IsValid(object value)
{
if (Field == "DisplayName")
{
if (new RequiredAttribute { ErrorMessage = "DisplayName cannot be blank." }.IsValid(value) && new StringLengthAttribute(50).IsValid(value))
return true;
return false;
}
if (Field == "EmailAddress")
{
if (new RequiredAttribute { ErrorMessage = "Email address cannot be blank." }.IsValid(value)
&& new RegularExpressionAttribute("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$") { ErrorMessage = "The email address you specified is invalid." }.IsValid(value)
&& new StringLengthAttribute(100).IsValid(value))
return true;
return false;
}
// Needs to return true by default unless Required exists
return true;
}
}
现在你应该能够以你想要的方式使用它。
编辑:
长期以来我所寻找的是能够投入的能力 “[UIHint(” - Editor Template--“)]”进入班级,并拥有 编辑器模板自足以发出它的onw错误 表单字段的消息。这样我就不必添加元数据了 表示[Required ...]或[RegularExpression ...]的类。
上述课程将使以下成为可能:
public class NewRegistrationModel {
[System.ComponentModel.DisplayName("Profile Display Name")]
[UIHint("DisplayName")]
public string DisplayName { get; set; }
[System.ComponentModel.DisplayName("Email Address")]
[UIHint("EmailAddress")]
public string EmailAddress1 { get; set; }
[System.ComponentModel.DisplayName("Email Address (confirm)")]
[UIHint("EmailAddress")]
public string EmailAddress2 { get; set; }
}