1 /* ****************************************************************************
\r
3 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5 * This software is subject to the Microsoft Public License (Ms-PL).
\r
6 * A copy of the license can be found in the license.htm file included
\r
7 * in this distribution.
\r
9 * You must not remove this notice, or any other, from this software.
\r
11 * ***************************************************************************/
\r
13 namespace System.Web.Mvc.Html {
\r
15 using System.Diagnostics.CodeAnalysis;
\r
17 using System.Linq.Expressions;
\r
19 public static class LabelExtensions {
\r
20 public static MvcHtmlString Label(this HtmlHelper html, string expression) {
\r
21 return LabelHelper(html,
\r
22 ModelMetadata.FromStringExpression(expression, html.ViewData),
\r
26 [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
\r
27 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
\r
28 return LabelHelper(html,
\r
29 ModelMetadata.FromLambdaExpression(expression, html.ViewData),
\r
30 ExpressionHelper.GetExpressionText(expression));
\r
33 public static MvcHtmlString LabelForModel(this HtmlHelper html) {
\r
34 return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty);
\r
37 internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName) {
\r
38 string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
\r
39 if (String.IsNullOrEmpty(labelText)) {
\r
40 return MvcHtmlString.Empty;
\r
43 TagBuilder tag = new TagBuilder("label");
\r
44 tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
\r
45 tag.SetInnerText(labelText);
\r
46 return tag.ToMvcHtmlString(TagRenderMode.Normal);
\r