Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c# - Get Custom Attributes from Lambda Property Expression

I am using ASP.NET MVC 2 Preview 2 and have written a custom HtmlHelper extension method to create a label using an expression. The TModel is from a simple class with properties and the properties may have attributes to define validation requirements. I am trying to find out if a certain attribute exists on the property the expression represents in my label method.

The code for the class and label is:

public class MyViewModel
{
    [Required]
    public string MyProperty { get; set; }
}

public static MvcHtmlString Label<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string label)
{
    return MvcHtmlString.Create(string.Concat("<label for="", expression.GetInputName(), "">", label, "</label>"));
}

public static string GetInputName<TModel, TProperty>(this Expression<Func<TModel, TProperty>> expression)
{
    return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
}

Then I would call the label like this:

Html.Label(x => x.MyProperty, "My Label")

Is there a way to find out if the property in the expression value passed to the Label method has the Required attribute?

I figured out that doing the following does get me the attribute if it exists, but I am hopeful there is a cleaner way to accomplish this.

public static MvcHtmlString Label<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string label)
{
    System.Attribute.GetCustomAttribute(Expression.Property(Expression.Parameter(expression.Parameters[0].Type, expression.GetInputName()), expression.GetInputName()).Member, typeof(RequiredAttribute))

    return MvcHtmlString.Create(string.Concat("<label for="", expression.GetInputName(), "">", label, "</label>"));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your expression parsing logic could use some work. Rather than deal with the actual types, you are converting to strings.

Here is a set of extension methods that you might use instead. The first gets the name of the member. The second/third combine to check if the attribute is on the member. GetAttribute will return the requested attribute or null, and the IsRequired just checks for that specific attribute.

public static class ExpressionHelpers
{
    public static string MemberName<T, V>(this Expression<Func<T, V>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression == null)
            throw new InvalidOperationException("Expression must be a member expression");

        return memberExpression.Member.Name;
    }

    public static T GetAttribute<T>(this ICustomAttributeProvider provider) 
        where T : Attribute
    {
        var attributes = provider.GetCustomAttributes(typeof(T), true);
        return attributes.Length > 0 ? attributes[0] as T : null;
    }

    public static bool IsRequired<T, V>(this Expression<Func<T, V>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression == null)
            throw new InvalidOperationException("Expression must be a member expression");

        return memberExpression.Member.GetAttribute<RequiredAttribute>() != null;
    }
}

Hopefully this helps you out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...