tags:

views:

62

answers:

1

How do I create an ASP.Net MVC Helper for an Html.Label which takes in attributes?

Currently when I define an Html.TextBox I am able to pass in a list of attributes. Sort of like below:

new {disabled="disabled", @class="pcTextBoxWithoutPaddingDisabled"})%> 

However, it does not look as though the Html.Label has this feature. As a result, I have to define my labels using the label tag. Sort of like below:

<label class="pcLabelBlackWithoutPadding">

I would like to be consistent I how my Html element get created.

So, how do I create an Html.Label that will take in a list of attributes?

Thanks for your help.

+1  A: 

I'd suggest creating your own HtmlHelper extension method and using a TagBuilder to create the label.

 public static HtmlHelperExtensions
 {
      public static Label( this HtmlHelper helper, string labelText, object properties )
      {
           var builder = new TagBuilder("label");
           builder.MergeAttributes( new RouteValueDictionary( properties ) );
           builder.SetInnerText( labelText );
           return builder.ToString( TagRenderMode.Normal );
      }
 }

See the MVC source code for ideas on how to create a strongly-typed label helper. Note that you'll need to add the namespace containing your extensions either to the page or the web.config to be able to use it.

tvanfosson