ASP.NET MVC has lots of html helpers to take models and generate html controls in your views. Most of them support passing in an anonymous object which is translated into html attributes on the markup for the element. For example:
@Html.TextBoxFor(m => m.SomeProperty, new { foo = "bar" })
Which becomes this:
<input type="text" name="SomeProperty" id="SomeProperty" foo="bar" />
There is however a shortcoming in one of these helpers. LabelFor does not support passing the HtmlAttributes anonymous object. They’ve added support for that into ASP.NET MVC 4 but in the meantime, I’ve written the helper. Here it is.
public static MvcHtmlString LabelFor(
this HtmlHelper html,
Expression<Func> expression,
object htmlAttributes = null)
{
var htmlAttributesDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string resolvedLabelText =
metadata.DisplayName ??
metadata.PropertyName ??
htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText))
{
return MvcHtmlString.Empty;
}
var tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(
html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder.SetInnerText(resolvedLabelText);
tagBuilder.MergeAttributes(htmlAttributesDict, replaceExisting: true);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Enjoy.