I created an attribute class to attach metadata to properties, so I can display tooltips for form input fields.
HelpAttribute
implements IMetadataAware
:
Public Class HelpAttribute Inherits Attribute Implements System.Web.Mvc.IMetadataAware Public Sub New(text As String) _text = text End Sub Private _text As String Public ReadOnly Property Text As String Get Return _text End Get End Property Public Sub OnMetadataCreated(metadata As System.Web.Mvc.ModelMetadata) Implements System.Web.Mvc.IMetadataAware.OnMetadataCreated metadata.AdditionalValues.Add("HelpText", _text) End Sub End Class
I use this metadata in my extension method:
<Extension()> Public Function HelpFor(Of TModel, TProperty)(ByVal htmlHelper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As MvcHtmlString Dim metaData = ModelMetadata.FromLambdaExpression(Of TModel, TProperty)(expression, htmlHelper.ViewData) If metaData.AdditionalValues.ContainsKey("HelpText") Then Dim helpText = metaData.AdditionalValues("HelpText") Return MvcHtmlString.Create(String.Format("<span class=""help""></span><div class=""tooltip"" style=""display: none""><div class=""border-top""></div><div class=""close""><a href=""#"">close</a></div><br class=""clear""><div class=""content"">{1}</div></div>", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(metaData.PropertyName), helpText, metaData.DisplayName)) End If Return MvcHtmlString.Create(String.Format("<span class=""no_help""></span>", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(metaData.PropertyName), metaData.DisplayName)) End Function
Therefore, I can call Html.HelpFor
for any of my model properties, and if it has the appropriate metadata, I show a help icon that shows a tooltip on click (js).
Everything works fine as long as the HelpAttribute
is defined in the same assembly as the classes that I decorate with their properties. Today I had to move HelpAttribute
to a separate dll (another namespace), so I did this, I referenced the project and expected it to work. I do not get compiler errors, the application works fine, but help icons do not appear on it. I debugged the code, and I see that the HelpAttribute
constructor is HelpAttribute
called for different properties with the correct text, but OnMetadataCreated
never being called. Does anyone have an idea why this is so and how to fix it?