How to add id attribute in Html.LabelFor () in ASP.NET MVC2?

How to add id attribute in Html.LabelFor () in ASP.NET MVC2?

This is my shortcut code:

<%=Html.LabelFor(x => x.FirstName)%>

This is my unsuccessful attempt:

<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" } )%>

Thank.

+5
source share
4 answers

Here is an assistant who should do what you need:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string id)
{
    ModelMetadata meta = ModelMetadata.FromLambdaExpression(expression, html.ViewData), 
    string 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.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
    tag.MergeAttribute("id", id);
    tag.SetInnerText(labelText);
    return tag.ToMvcHtmlString(TagRenderMode.Normal);
}

simple modification from LabelFor helper in asp.net mvc source.

+4
source

LabelFor, TextBoxFor, XXXFor methods automatically add an identifier based on the name of the property. I do not think you can override this. If you want to set the identifier, you need to use non-For methods such as Html.TextBox.

0
source

public static class LabelExtensions

    {
        public static string Label(this HtmlHelper helper, string target, string id, string text)
        {
            return String.Format("<label for='{0}' id='{1}'>{2}</label>", target,id, text);
        }
    }

, - tagbuilder, , MergeAttribute .

0

Perhaps the behavior has changed from MVC2, because although I use Razor and VB.NET, I got this code to work, and it should be about the same, with the possible exception @that you put in front of id(now I use MVC4):

@Html.LabelFor(Function(model) model.ItemNumber, New With {.id = "ItemNumberL"})

This created the following HTML:

<label for="ItemNumber" id="ItemNumberL">ItemNumber</label>
0
source

All Articles