【发布时间】:2018-02-09 21:46:18
【问题描述】:
我有许多属性需要 1 个或多个验证属性,如下所示:
public class TestModel
{
[Some]
[StringLength(6)]
[CustomRequired] // more attributes...
public string Truck { get; set; }
}
请注意以上所有注释都有效。
我不想一直这样写,因为每当应用Some 时,所有其他属性也会应用到该属性。我希望能够做到这一点:
public class TestModel
{
[Some]
public string Truck { get; set; }
}
现在这可以通过继承来实现;因此,我写了一个自定义的DataAnnotationsModelMetadataProvider 并覆盖了CreateMetadata。这会查找用Some 装饰的任何内容,然后为其添加更多属性:
public class TruckNumberMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var attributeList = attributes.ToList();
if (attributeList.OfType<SomeAttribute>().Any())
{
attributeList.Add(new StringLengthAttribute(6));
attributeList.Add(new CustomRequiredAttribute());
}
return base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
}
}
如果有帮助,这些是属性:
public class CustomRequiredAttribute : RequiredAttribute
{
public CustomRequiredAttribute()
{
this.ErrorMessage = "Required";
}
}
public class SomeAttribute : RegularExpressionAttribute
{
public SomeAttribute()
: base(@"^[1-9]\d{0,5}$")
{
}
}
用法
@Html.TextBoxFor(x => x.Truck)
HTML 渲染:
<input name="Truck" id="Truck" type="text" value=""
data-val-required="The Truck field is required."
data-val-regex-pattern="^[1-9]\d{0,5}$"
data-val-regex="The field Truck must match the regular expression '^[1-9]\d{0,5}$'."
data-val="true">
</input>
问题/疑问
-
CustomRequired已应用。但是,如果我使用CustomRequired,它为什么会从基类RequiredAttribute中获取消息。data-val-required应该只是说必填。 - 不应用 6 个字符的
StringLenth。StringLength没有任何渲染迹象,为什么?
【问题讨论】:
-
关于(1),您是否在
global.asax.cs注册了您的自定义属性? -
@StephenMuecke 是的,我已经注册了他们。当我直接在我的模型上使用它们时,它们会起作用。您实际上可以获取代码,它会重现问题。
-
我没有将
Required应用于模型,因此它肯定是从自定义提供程序中获取它,但由于某种原因没有获取错误消息。
标签: c# asp.net-mvc razor asp.net-mvc-5