I am trying to create a custom LabelFor helper to apply by default instead of the standard LabelFor helper include in System.Web.Mvc.Html. I want my LabelFor to take model properties that are PascalCase and make a label that appears as multiple words. For example the property FirstName
would appear as "First Name".
I found this post that shows how to make a custom LabelFor helper that allows the addition of html attributes.
I recreated this helper in VB.Net and modified it to do what I want, but I am not able to get it to work.
Imports System.Linq.Expressions
Imports System.Runtime.CompilerServices
Public Module LabelExtensions
<Extension()> _
Public Function LabelFor(Of Tmodel, TValue)(html As HtmlHelper(Of Tmodel), expression As Expression(Of Func(Of Tmodel, TValue))) As MvcHtmlString
Dim metadata As ModelMetadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
Dim htmlFieldName As String = ExpressionHelper.GetExpressionText(expression)
Dim labelText As String = If(metadata.DisplayName, If(metadata.PropertyName, htmlFieldName.Split(".").Last()))
If String.IsNullOrEmpty(labelText) Then Return MvcHtmlString.Empty
labelText = Regex.Replace(labelText, ".[A-Z]", Function(m) m.ToString()(0) & " " & Char.ToLower(m.ToString()(1)))
Dim tag As TagBuilder = New TagBuilder("label")
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName))
tag.SetInnerText(labelText)
Return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal))
End Function
The sample includes this Module in Namespace System.Web.Mvc.Html
but when I add the namespace declaration to this module everything in the rest of the project goes haywire. For example, each of my models has a Primary Key property that is a Guid
datatype and as soon as I add the namespace above to the module, I get several errors stating that System.Guid is not defined
among other similar errors.
I've tried to import my project namespace into a view in order to use the custom helper, but then I get an error that says Overload resolution failed because no 'LabelFor' is most specific for these arguments
.
I'm stuck. Can anybody help?
I am trying to avoid having to specify a DisplayName
for every PascalCase property I have in many models.
System.Web.Mvc.Html
, but that broke other references toSystem
objects in my project. – Brian Jun 20 '12 at 15:39