Ehsan Tavakoli

Writing About .NET Programming and other stuff

Archive for the ‘Razor’ Category

LabelFor HtmlHelper with HtmlAttributes and custom Prefix and Postfix

leave a comment »

For some reason I needed to use Html.LabelFor MVC helper and I realised that by default this Html Helper just have two overloads which none of them support custom Html Attributes and if you want to add a simple prefix or postfix text to the label you are going to have few problems. It’s common for labels to be displayed in block mode therefore it’s going to be a bit tricky if you want to add your custom text just before or after the generated label without dropping to the next line in display. For example you want to add a colon or comma at the end of your label ([labelname]:). So I’ve written a extension for LabelFor helper like this:

public static class LabelForExtension
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string prefix, string postfix, object htmlAttributes)
        {
            return LabelFor(html, expression, prefix, postfix, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string prefix, string postfix, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.InnerHtml = prefix + labelText + postfix;
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }

and you can use it in your view like this (Razor view):

@Html.LabelFor(model => model.Attribute, "Custom Prefix Text", "Custom Postfix Text", new { @class = "customClass" })

it supports Html format for prefix and postfix so can customize it as you like

Written by Ehsan Tavakoli

March 10, 2011 at 1:40 pm