Ehsan Tavakoli

Writing About .NET Programming and other stuff

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

Advertisements

Written by Ehsan Tavakoli

March 10, 2011 at 1:40 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: