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)?