简体   繁体   中英

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. 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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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