繁体   English   中英

如何在我的视图中访问模型中的属性

[英]How can I access the attributes from my model in my view

我有一个在其中一个属性上具有范围属性的模型:

using System;
using System.ComponentModel.DataAnnotations;

namespace Example
{
    public class modelClass
    {
        [Range(-1, int.MaxValue)]
        public int property { get; set; }
    }
}

TextBoxFor 已经访问了要传递给 Jquery 验证的属性的最小值和最大值。 我希望能够从视图中访问 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 })

这是如何通过使用反射来实现的想法:

我们添加了两个额外的属性来保存最小值和最大值

public class modelClass
{
    [Range(-1, int.MaxValue)]
    public int property { get; set; }

    public int Min { get; set;}
    public int Max { get; set; }
}

然后在构造函数中,我们执行以下操作:

        RangeAttribute attribute = (RangeAttribute)typeof(modelClass).GetProperty("property").GetCustomAttributes(false).FirstOrDefault();
        this.Min = Convert.ToInt32(attribute.Minimum);
        this.Max = Convert.ToInt32(attribute.Maximum); 

然后在 HTML 中您可以访问@Model.Min 和@Model.Max。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM