0

I want to get the StringLength attribute.

Class code :

var type1 = Type.GetType("MvcApplication4.Models.Sample.SampleMasterModel");
var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, type1);
var properties = metadata.Properties;
var prop = properties.FirstOrDefault(p => p.PropertyName == "Remark");

?? Get StringLength attr?

Model Code:

public class SampleModel 
{
    [StringLength(50)]
    public string Remark { get; set; }
}

Based on wudzik and Habib help. I modified the code. Final Code:

PropertyInfo propertyInfo = type1.GetProperties().FirstOrDefault(p => p.Name == "Remark");
if (propertyInfo != null)
{
    var attributes = propertyInfo.GetCustomAttributes(true);
    var stringLengthAttrs =
        propertyInfo.GetCustomAttributes(typeof (StringLengthAttribute), true).First();
    var stringLength = stringLengthAttrs != null ? ((StringLengthAttribute)stringLengthAttrs).MaximumLength : 0;
}
4

2 回答 2

0

You can get CustomAttributes through PropertyInfo like:

PropertyInfo propertyInfo = type1.GetProperties().FirstOrDefault(p=> p.Name == "Remark");
if (propertyInfo != null)
{
    var attributes = propertyInfo.GetCustomAttributes(true);
}
于 2013-11-05T15:13:28.490 回答
0
    /// <summary>
    /// Returns the StringLengthAttribute for a property based on the property name passed in.
    /// Use this method in the class or in a base class
    /// </summary>
    /// <param name="type">This type of the class where you need the property StringLengthAttribute.</param>
    /// <param name="propertyName">This is the property name.</param>
    /// <returns>
    /// StringLengthAttribute of the propertyName passed in, for the Type passed in
    /// </returns>
    public static StringLengthAttribute GetStringLengthAttribute(Type type, string propertyName)
    {
        StringLengthAttribute output = null;

        try
        {
            output = (StringLengthAttribute)type.GetProperty(propertyName).GetCustomAttribute(typeof(StringLengthAttribute));
        }
        catch (Exception ex)
        {
            //error handling
        }

        return output;

    } //GetStringLengthAttribute


    /// <summary>
    /// Returns the StringLengthAttribute for a property based on the property name passed in.
    /// Use this method in the class or in a base class
    /// </summary>
    /// <param name="propertyName">This is the property name.</param>
    /// <returns>
    /// StringLengthAttribute of the propertyName passed in, for the current class
    /// </returns>
    public StringLengthAttribute GetStringLengthAttribute(string propertyName)
    {
        StringLengthAttribute output = null;

        try
        {
            output = (StringLengthAttribute)this.GetType().GetProperty(propertyName).GetCustomAttribute(typeof(StringLengthAttribute));
        }
        catch (Exception ex)
        {
            //error handling
        }

        return output;

    } //GetStringLengthAttribute

}
于 2015-09-30T20:03:39.933 回答