Skip to content

Instantly share code, notes, and snippets.

@topas
Created February 26, 2012 23:48
Show Gist options
  • Save topas/1919858 to your computer and use it in GitHub Desktop.
Save topas/1919858 to your computer and use it in GitHub Desktop.
ASP.NET MVC Html.LabelFor helper with html attributes
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));
}
}
@arunzer0
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment