Created
February 26, 2012 23:48
-
-
Save topas/1919858 to your computer and use it in GitHub Desktop.
ASP.NET MVC Html.LabelFor helper with html attributes
This file contains hidden or 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.Linq; | |
using System.Linq.Expressions; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
public static class LabelExtensions | |
{ | |
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) | |
{ | |
return LabelFor(html, expression, null, htmlAttributes); | |
} | |
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes) | |
{ | |
return LabelHelper(html, | |
ModelMetadata.FromLambdaExpression(expression, html.ViewData), | |
ExpressionHelper.GetExpressionText(expression), | |
labelText, | |
htmlAttributes); | |
} | |
private static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, object htmlAttributes = null) | |
{ | |
var innerText = labelText; | |
if (innerText == null) | |
{ | |
var displayName = metadata.DisplayName; | |
if (displayName == null) | |
{ | |
var propertyName = metadata.PropertyName; | |
if (propertyName == null) | |
{ | |
innerText = htmlFieldName.Split(new[] { '.' }).Last(); | |
} | |
else | |
{ | |
innerText = propertyName; | |
} | |
} | |
else | |
innerText = displayName; | |
} | |
if (string.IsNullOrEmpty(innerText)) | |
return MvcHtmlString.Empty; | |
var tagBuilder = new TagBuilder("label"); | |
tagBuilder.Attributes.Add("for", | |
TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName))); | |
if (htmlAttributes != null) | |
{ | |
tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); | |
} | |
tagBuilder.SetInnerText(innerText); | |
return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Topas,
Can please attach the full project? Current I am working on the extension method. If you attach complete sample project. It will be more helpful.
Thanks