Skip to content

Instantly share code, notes, and snippets.

@jaredhoyt
Last active December 18, 2015 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredhoyt/5725338 to your computer and use it in GitHub Desktop.
Save jaredhoyt/5725338 to your computer and use it in GitHub Desktop.
CheckBoxLabelExtension
namespace System.Web.Mvc.Html {
using System.Collections;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
public static class CheckBoxLabelExtensions {
public static MvcHtmlString CheckBoxLabel(this HtmlHelper html, string expression) {
return CheckBoxLabel(html, expression, null);
}
public static MvcHtmlString CheckBoxLabel(this HtmlHelper html, string expression, string labelText) {
return CheckBoxLabelHelper(html, ModelMetadata.FromStringExpression(expression, html.ViewData), expression, labelText);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString CheckBoxLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
return CheckBoxLabelFor<TModel, TValue>(html, expression, null);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString CheckBoxLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText) {
return CheckBoxLabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), labelText);
}
public static MvcHtmlString CheckBoxLabelForModel(this HtmlHelper html) {
return CheckBoxLabelForModel(html, null);
}
public static MvcHtmlString CheckBoxLabelForModel(this HtmlHelper html, string labelText) {
return CheckBoxLabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText);
}
internal static MvcHtmlString CheckBoxLabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null) {
string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText)) {
return MvcHtmlString.Empty;
}
TagBuilder label = new TagBuilder("label");
label.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
label.InnerHtml = String.Format("<span></span>{0}", resolvedLabelText);
return new MvcHtmlString(label.ToString(TagRenderMode.Normal));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment