tags:

views:

331

answers:

2

I am using MVC in asp.net.

i want to change font size & color of html.label control.

so how can i make helper class of this?

+2  A: 

Here is my code for such an extension. Note that the ParameterDictionary is my own class. I think the MVC extensions use RouteValueDictionary instead, but it seems wrong to me to rely on that so I made my own class for this specific purpose. You'll need to import the namespace containing your HtmlExtensions class into the view where you want to use these extensions (and add a reference to the project containing the class if not in your web project).

public static class HtmlExtensions
{
    public static string Label( this HtmlHelper helper,
                                string labelFor,
                                string value,
                                object htmlAttributes )
    {
        TagBuilder labelBuilder = new TagBuilder( "label" );
        if (!string.IsNullOrEmpty( labelFor ))
        {
            labelBuilder.Attributes.Add( "for", labelFor );
        }
        labelBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
        labelBuilder.SetInnerText( value );
        return labelBuilder.ToString( TagRenderMode.Normal );
    }    
}

Usage:

<%= Html.Label( "Name", new { @class = "input-label" } ) %>
<%= Html.TextBox( "Name" ) %>
tvanfosson
Hi i am getting error on ParameterDictionary => Missing reference
Vikas
Yes. ParameterDictionary is my own class. You could replace it with RouteValueDictionary from the framework.
tvanfosson
A: 

Wouldn't you just do that in the markup (style / css):

<label for="Name" ***here***>Name:</label>
Marc Gravell
Certainly could -- and, in fact, I normally do. A helper extension can be good, though, to make the construction of labels consistent and testable -- for example, if you always wanted to have a certain class applied you could modify the extension to add it.
tvanfosson