问题描述
有没有办法使ASP MVC 5像对待所有类型一样应用最小值和最大值?
[Range(0,int.MaxValue,ErrorMessage = "Value beyond accepted range")]
public int? Thing{ get; set; }
[Range(0,ErrorMessage = "Value beyond accepted range")]
public int? AnotherThing { get; set; }
在该属性指定了range属性的地方,使用该属性(替代默认行为)吗?
我认为可以在每种属性类型的编辑器模板中完成此操作吗?
解决方法
设法解决:
编辑器模板: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;
}