Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Html.Label with Attribute List?

Tags:

asp.net-mvc

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.

like image 301
Richard Avatar asked Sep 06 '10 16:09

Richard


2 Answers

This is updated version for MVC3:

public static MvcHtmlString Label(this HtmlHelper helper, String htmlFieldName, String labelText, Object htmlAttributes)
{
    ModelMetadata metadata = ModelMetadata.FromStringExpression(htmlFieldName, helper.ViewData);

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

    if (String.IsNullOrEmpty(innerText))
    {
        return MvcHtmlString.Empty;
    }

    TagBuilder tagBuilder = new TagBuilder("label");
    tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
    tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    tagBuilder.SetInnerText(innerText);

    return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal));

}
like image 140
Alexandr Zubkov Avatar answered Oct 13 '22 00:10

Alexandr Zubkov


I have modified Alexandr code a bit with lambda expression, in case anyone needed the lambda expression.

usage:

@Html.LabelFor(model => model.Property , new { @class = "bigFont" })

code:

public static MvcHtmlString LabelFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression, Object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        var innerText = metadata.DisplayName ?? metadata.PropertyName;

        if (String.IsNullOrEmpty(innerText))
        {
            return MvcHtmlString.Empty;
        }

        var tagBuilder = new TagBuilder("label");
        tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName)));
        tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        tagBuilder.SetInnerText(innerText);

        return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal));
    }
like image 35
Heinnge Avatar answered Oct 12 '22 23:10

Heinnge