It’s been a long time between posts and as evidenced by the new category, I’ve been busy.

Of late, I’ve been really getting into the .NET MVC framework and for some things, it’s been an absolute wonder. For others, I’d love to point the developers to some Zend Framework features.

In keeping with the tradition of blogging about things that I discover in my day-to-day development work, I’d like to contribute this little snippet of code that’s come in very handy for me.

The LabelFor helper in .NET MVC gives you a nice, easy way to set a strongly typed label for your model properties. One problem though, you can’t set the label text.

Whilst you can use the [DisplayName] component model attribute, this doesn’t help if say, your model is part of a collection and needs a unique label. It also feels a bit odd putting presentation data in the model but that’s just me.

So here’s my very simple override

public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string text)
    string propertyName = ExpressionHelper.GetExpressionText(expression);
    TagBuilder label = new TagBuilder("label");
    label.MergeAttribute("for", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName));
    return MvcHtmlString.Create(label.ToString());