Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created February 24, 2014 13:51
Show Gist options
  • Save hagbarddenstore/9188776 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/9188776 to your computer and use it in GitHub Desktop.
Provides ASP.NET MVC label extension methods for HtmlHelper.
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), null, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, IDictionary<string, object> htmlAttributes = null)
{
var resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (string.IsNullOrEmpty(resolvedLabelText))
{
return MvcHtmlString.Empty;
}
TagBuilder tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tag.SetInnerText(resolvedLabelText);
tag.MergeAttributes(htmlAttributes, replaceExisting: true);
return tag.ToMvcHtmlString(TagRenderMode.Normal);
}
internal static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
{
return new MvcHtmlString(tagBuilder.ToString(renderMode));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment