Reputation:
How would one add an "id" attribute to Html.LabelFor() in ASP.NET MVC2?
This is my label code:
<%=Html.LabelFor(x => x.FirstName)%>
This is my failed attempt:
<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" } )%>
Thanks.
Upvotes: 5
Views: 7669
Reputation: 25601
Perhaps the behavior has changed since MVC2 because, although I'm using Razor and VB.NET, I got this code to work, and it should be about the same with the possible exception of the @
you put before id
(I'm now using MVC4):
@Html.LabelFor(Function(model) model.ItemNumber, New With {.id = "ItemNumberL"})
This generated the following HTML:
<label for="ItemNumber" id="ItemNumberL">ItemNumber</label>
Upvotes: 0
Reputation: 9318
Here is an helper that 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);
}
a simple modification from the LabelFor helper in the asp.net mvc source.
Upvotes: 4
Reputation: 24847
How about this extension method
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);
}
}
Edit
I think the better way would be to use the tagbuilder similar to this example and use the MergeAttribute function to include the id.
Upvotes: 0
Reputation: 34810
The LabelFor, TextBoxFor, XXXFor methods automatically add the id based on the name of the property. I don't think you can override that. If you want to be able to set the id, you'll need to use the "non-For" methods like Html.TextBox.
Upvotes: 0