ASP MVC模型属性的默认范围验证



有没有一种方法可以让ASP MVC 5像对待所有类型一样应用最小值和最大值范围?

也就是说,这不需要将范围属性添加到每个可能的属性中?

[Range(0, int.MaxValue, ErrorMessage = "Value beyond accepted range")]
public int? Thing{ get; set; }
[Range(0, int.MaxValue, ErrorMessage = "Value beyond accepted range")]
public int? AnotherThing { get; set; }

如果属性具有指定的范围属性,则使用该属性(覆盖默认行为(?

为每个属性添加一个范围验证器是令人难以置信的重复和乏味,而且会破坏DRY。

我想这可能在每个属性类型的编辑器模板中完成?

设法解决了这个问题:

编辑器模板:Int.cshtml

@model int?
@{

var htmlAttributes = new RouteValueDictionary();
var range = ViewData.ModelMetadata.GetPropertyAttribute<RangeAttribute>();
if (range == null)
{
htmlAttributes.Add("data-val-range_min", "0");
htmlAttributes.Add("data-val-range_max", int.MaxValue);
htmlAttributes.Add("data-val-range", "value exceeds allowed range");
}
htmlAttributes.Add("class", "form-control");
htmlAttributes.Add("type", "number");
}
@Html.TextBoxFor(model => model, htmlAttributes)

模型元数据扩展:

public static T GetPropertyAttribute<T>(this ModelMetadata instance)
where T : Attribute
{
var result = instance.ContainerType
.GetProperty(instance.PropertyName)
.GetCustomAttributes(typeof(T), false)
.Select(a => a as T)
.FirstOrDefault(a => a != null);
return result;
}

最新更新