我已经使用searchstring构建了一个searchmodel并用minlength进行了修饰。在我的视图中,我想显示搜索字符串的需求,但我怎样才能进入装饰?
型号:
public class SearchModel
{
[StringLength(50,MinimumLength = 4)]
public string Searchname { get; set; }
}
剃刀:
@model Project.Models.SearchModel
<p>
The search value has to be a min length of: ...
</p>
答案 0 :(得分:2)
你可以这样做:
@(typeof(SearchModel).GetProperty("Searchname").GetCustomAttributes(true)
.OfType<StringLengthAttribute>().First().MinimumLength)
虽然为了MVC纯度,您应该避免将此逻辑放入视图代码中。之一:
答案 1 :(得分:1)
您可以从客户端的validator属性中获取此值。
$('#Searchname').attr('data-val-length-min')
或者你需要在剃须刀的服务器端吗?
@{
var attr = typeof(NAMESPACE.SearchModel).GetProperty("Searchname").GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true)[0];
var min = attr.GetType().GetProperty("MinimumLength").GetValue(attr, null);
}
.
.
.
<p>The search value has to be a min length of: @min</p>