1 namespace System.Web.Mvc.Html {
3 using System.Diagnostics.CodeAnalysis;
5 using System.Linq.Expressions;
7 public static class LabelExtensions {
8 public static MvcHtmlString Label(this HtmlHelper html, string expression) {
14 public static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText) {
15 return LabelHelper(html,
16 ModelMetadata.FromStringExpression(expression, html.ViewData),
21 [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
22 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
23 return LabelFor<TModel, TValue>(html, expression, null);
26 [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
27 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText) {
28 return LabelHelper(html,
29 ModelMetadata.FromLambdaExpression(expression, html.ViewData),
30 ExpressionHelper.GetExpressionText(expression),
34 public static MvcHtmlString LabelForModel(this HtmlHelper html) {
35 return LabelForModel(html, null);
38 public static MvcHtmlString LabelForModel(this HtmlHelper html, string labelText) {
39 return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText);
42 internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null) {
43 string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
44 if (String.IsNullOrEmpty(resolvedLabelText)) {
45 return MvcHtmlString.Empty;
48 TagBuilder tag = new TagBuilder("label");
49 tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
50 tag.SetInnerText(resolvedLabelText);
51 return tag.ToMvcHtmlString(TagRenderMode.Normal);