Created
May 30, 2013 07:47
-
-
Save danielgreen/5676321 to your computer and use it in GitHub Desktop.
Some MVC-specific extension methods. The built-in LabelFor methods do not allow you to specify HTML attributes to be applied to the label element, so these LabelFor extensions plug the gap.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
using System.Linq.Expressions; | |
namespace Web.Extensions | |
{ | |
public static class MVCExtensions | |
{ | |
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) | |
{ | |
return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes)); | |
} | |
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes) | |
{ | |
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); | |
string htmlFieldName = ExpressionHelper.GetExpressionText(expression); | |
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); | |
if (String.IsNullOrEmpty(labelText)) | |
{ | |
return MvcHtmlString.Empty; | |
} | |
TagBuilder tag = new TagBuilder("label"); | |
tag.MergeAttributes(htmlAttributes); | |
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); | |
tag.SetInnerText(labelText); | |
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment