ASP.NET MVC LabelFor Helper With HtmlAttributes

    Introduction:

          In ASP.NET MVC you have low-level control over your HTML. This simply means that you can write any html elements in your view as you wish. However for getting the advantage of Model Binding and Visual Studio Intellisense, ASP.NET MVC provides a shorter and tidier way to write html elements with the help of html helpers method. LabelFor helper is one of the html helper method used to render html label element. ASP.NET MVC 2 ships with just a single overload for LabelFor helper method. There is no such overload of LabelFor helper which accepts htmlAttributes parameter like other html helpers accept. This parameter is very important when you need to style html label with CSS class or when you need to add a tooltip message. Therefore in this article I will show you how easily you can creates your own LabelFor helper extension method which also accept htmlAttributes parameter.

   Description:

          Before I started to write some simple helper extension methods for LabelFor, it is worth to see the current helper method's signature for LabelFor helper method. Here it is,

 

LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)

 

          It only accept a single parameter expression. Here is the two new extension methods which accept another additional parameter htmlAttributes,

 

    public static class NewLabelExtensions
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
        {
            return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, 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.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }

 

          Note that there is nothing magic happening here. All the above code is same code used for LabelFor helper method with one parameter, except method signature and the code, tag.MergeAttributes(htmlAttributes). This code is necessary to embed html attributes in label element.


          Now just add this new LabelFor helper method in your view with htmlAttributes parameter,

 

             <%=Html.LabelFor(a => a.Name, new { @class="A",title="Enter Name"})%>

           You will find the following rendered html,

 

              <label class="A" for="Name" title="Enter Name">Name</label>

 

   Summary:

          Html helpers method provides an easy and tidier way to write html elements, but some times you may need to create your own helper method to meet your requirement. So in this article I shows you how to create two simple html helper extension methods for LabelFor helper which also render html attributes in html label element. Hopefully you enjoy it much.

Published Saturday, July 3, 2010 6:20 AM by imran_ku07
Filed under: , , ,

Comments

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, July 5, 2010 2:53 PM by Anders Lybecker

Nice :-)

Simple solution with extension method. Why havn't I thought of that...

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Friday, July 9, 2010 8:04 AM by dkarantonis

thanks!

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, September 23, 2010 9:23 AM by Philip Quarles

Exactly what I was looking for!

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Wednesday, October 27, 2010 7:01 AM by Paul Hadfield

Another big thanks, you've saved me a lot of time or from abandoning the LabelFor idea.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, January 24, 2011 12:23 AM by rohitvermasrt

Thanks for this code.. But can i get this in vb.net? becuase I m trying this in vb.net but not getting success...

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, January 24, 2011 10:39 PM by imran_ku07

@rohitvermasrt, lot of C# to VB.NET Converter present online.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Friday, March 11, 2011 10:53 AM by Sumit Khanna

It's so stupid that you even have to do this. That overloaded method should be built-in, or there should be some standard way to add html attributes to html generated from those helper function.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, March 24, 2011 9:28 AM by jan.nemec

Is it possible with this helper to change the inner text of the label?

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, March 24, 2011 1:51 PM by imran_ku07

@jan.nemec

SetInnerText is doing this

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, May 3, 2011 8:55 AM by pfowles

Simple solution glad I found this quickly,

By the way is Line 11 correct is there a Last() method for the System.Array when I write this code the complier goes red squiggly on the Last();

string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

Did you use other using statements apart from the following :-

using System;

using System.Linq.Expressions;

using System.Runtime.CompilerServices;

using System.Web.Routing;

using System.Web.Mvc;

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, May 3, 2011 9:05 AM by imran_ku07

@pfowles,

This is Linq extesnion.Add

<b>using System.Linq</b>

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, May 3, 2011 9:14 AM by pfowles

I've written an array instead and linked that to the last index

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, June 7, 2011 6:00 AM by Nuri Yılmaz

hello,

I am wondering that is LabelFor source code or your personel recommended implementation?

thanks in advance.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, June 7, 2011 6:16 AM by imran_ku07

@Nuri,

The source code is same present in ASP.NET MVC except this line,

tag.MergeAttributes(htmlAttributes).

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, June 16, 2011 7:18 PM by Tom Stickel

I have written extension methods for other classes, but when I tried this out I knew the View needed to reference the overloaded LabelFor, but this didn't work @OVR.Helpers.ObjectExtensions.LabelFor(m => m.Deceased, new { @class = "floatleft",title = "test"})   So then once I downloaded the project, I noticed that you used the namespace System.Web.Mvc.Html .... so once I changed mine It worked.  Thanks.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, July 14, 2011 11:07 AM by e-ticaret

An excellent site for a long time I am following the site almost every day, but I added your site or landing pages get into the commonly used rate slowed down in recent days I wonder if they have a problem with my computer is also unclear to me. Nevertheless, this site would like to thank those who contributed.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Thursday, July 21, 2011 4:13 AM by eticaret

That overloaded method should be built-in, or there should be some standard way to add html attributes to html generated from those helper function. thank you

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Friday, August 19, 2011 9:15 PM by eticaret

Is it possible with this helper to change the inner text of the label?

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Saturday, August 20, 2011 3:11 AM by imran_ku07

@eticaret,

Yes, you can change it using,

tag.SetInnerText

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, December 5, 2011 8:38 AM by Bertje

Why do i get the error:

Argument type '{@class:string} is not assignable to parameter type 'string'

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Tuesday, December 6, 2011 11:13 AM by imran_ku07

@Bertje,

Use the equalto sign. @class="A"

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, January 16, 2012 12:21 PM by jarnail

Please can you describe step by step where  write the "public static class NewLabelExtensions" code.

Thanks

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Monday, January 16, 2012 12:36 PM by imran_ku07

@jarnail,

Please download the sample code and see.

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Friday, July 20, 2012 4:43 PM by Charles

This doesnt seem to work when you need to add attributes with dashes such as "data-..." attributes.

@Html.DisplayFieldTextFor(x => x, new { data_validate_account_url = Url.Action("Account", "Validate") }) makes the attribute render as "data_validate_account_url" in the html (which causes jquery's data().validateAccountUrl to fail).

# re: ASP.NET MVC LabelFor Helper With HtmlAttributes

Saturday, July 21, 2012 11:16 AM by imran_ku07

@Charles, Can you please share a sample project?