2

I wrote a custom DataAnnotation that works perfectly fine unless I use a ViewModel rather then the actual Model itself.

With a Model, the data annotation renders something to the effect of:

<label class="tooltip" for="title">Enter a title.</label>

When I use a ViewModel, the data annotation is still rendering the same thing. The problem here is the "for" should be something like "Product_title" instead of "title".

Here's the HTMLHelper I wrote that renders the label from the data annotation:

(Taken from asp.net MVC extending DataAnnotions)

public static MvcHtmlString TooltipFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
    var exp = (MemberExpression)expression.Body;
    foreach (Attribute attribute in exp.Expression.Type.GetProperty(exp.Member.Name).GetCustomAttributes(false)) {
        if (typeof(Tooltip) == attribute.GetType()) {
            return MvcHtmlString.Create("<label class=\"tooltip\" for=\"" + exp.Member.Name + "\">" + ((Tooltip)attribute).Description + "</label>");
        }
    }
    return MvcHtmlString.Create("");
}

I dug around in the expression object to figure out which property holds the model property name which would end up being the input ID; "exp.Member.Name".

Now that I'm using a ViewModel, I apparently need something different, because "exp.Member.Name" is still returning "title" instead of "Product_title", which ends up being the ID of the input field.

So, is there a property I can get at that I can use instead of "Member.Name" that will always return the proper ID, or will I have to get around this issue with JavaScript (which I can do if everything else fails)?

Community
  • 1
  • 1
Kizmar
  • 2,465
  • 3
  • 20
  • 27

1 Answers1

0

I recently implemented something similar, taking the "Description" attribute of the Display annotation and outputting it to the screen:

    public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) {
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        var description = metadata.Description;

        return MvcHtmlString.Create(description);
    }

I output these helpers to tooltip type controls. I considered implementing my own tooltip attribute, but it seemed to be more than I needed...

Spikeh
  • 3,540
  • 4
  • 24
  • 49