【问题标题】:How can I access the attributes from my model in my view如何在我的视图中访问我的模型的属性
【发布时间】:2020-01-27 17:56:52
【问题描述】:

我有一个模型,其中一个属性具有范围属性:

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 })

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

以下是如何使用反射来实现的想法:

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

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多