如何解决ASP MVC模型属性的默认范围验证
有没有办法使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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。