[英]How can I access the attributes from my model in my view
I have a model with a Range Attribute on one of the properties:我有一个在其中一个属性上具有范围属性的模型:
using System;
using System.ComponentModel.DataAnnotations;
namespace Example
{
public class modelClass
{
[Range(-1, int.MaxValue)]
public int property { get; set; }
}
}
TextBoxFor already accesses the min and max values of the attribute to pass to Jquery validation. TextBoxFor 已经访问了要传递给 Jquery 验证的属性的最小值和最大值。 I would like to be able to access the min and max values of the Range attribute from the view, so that I can set the html 5 min and max attributes as well, rather than hard-coding them as below.
我希望能够从视图中访问 Range 属性的最小值和最大值,以便我也可以设置 html 5 min 和 max 属性,而不是将它们硬编码如下。
@using System;
@using Example;
@model modelClass
@Html.TextBoxFor(x => x, new { @type="number", @class = "form-control", min=-1, max=2147483647 })
Here is an idea in how it can be achieved by using Reflection:这是如何通过使用反射来实现的想法:
We add two extra properties to hold the min and max我们添加了两个额外的属性来保存最小值和最大值
public class modelClass
{
[Range(-1, int.MaxValue)]
public int property { get; set; }
public int Min { get; set;}
public int Max { get; set; }
}
Then in the constructor we do as following:然后在构造函数中,我们执行以下操作:
RangeAttribute attribute = (RangeAttribute)typeof(modelClass).GetProperty("property").GetCustomAttributes(false).FirstOrDefault();
this.Min = Convert.ToInt32(attribute.Minimum);
this.Max = Convert.ToInt32(attribute.Maximum);
Then in the HTML you can access @Model.Min and @Model.Max.然后在 HTML 中您可以访问@Model.Min 和@Model.Max。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.