簡體   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