获取模型类型和StringLength属性

时间:2013-11-05 14:57:25

标签: c# asp.net-mvc

我想获取StringLength属性。

班级代码:

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");

??获取StringLength attr?

型号代码:

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

基于wudzik和Habib的帮助。我修改了代码。 最终守则:

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

2 个答案:

答案 0 :(得分:0)

您可以通过PropertyInfo获取CustomAttributes,如:

PropertyInfo propertyInfo = type1.GetProperties().FirstOrDefault(p=> p.Name == "Remark");
if (propertyInfo != null)
{
    var attributes = propertyInfo.GetCustomAttributes(true);
}

答案 1 :(得分: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

}