Created
February 24, 2014 13:51
-
-
Save hagbarddenstore/9188776 to your computer and use it in GitHub Desktop.
Provides ASP.NET MVC label extension methods for HtmlHelper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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