Skip to content

Instantly share code, notes, and snippets.

@kevinblake
Created November 26, 2013 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinblake/7658913 to your computer and use it in GitHub Desktop.
Save kevinblake/7658913 to your computer and use it in GitHub Desktop.
Html Helper class to add ASP.NET MVC error messages to a label wrapper class
using System.Linq;
using System.Linq.Expressions;
namespace System.Web.Mvc.Html
{
public static class BlockLabelExtensions
{
public static IDisposable BeginBlockLabel<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
string expressionText = ExpressionHelper.GetExpressionText(expression);
MvcHtmlString labelString = LabelValueHelper(
html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
expressionText);
bool isValid = html.ViewData.ModelState.IsValidField(expressionText);
return new LabelWrapper(html, isValid, labelString);
}
internal static MvcHtmlString LabelValueHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName)
{
string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText))
{
return MvcHtmlString.Empty;
}
return new MvcHtmlString(resolvedLabelText);
}
private class LabelWrapper : IDisposable
{
private readonly HtmlHelper htmlHelper;
public LabelWrapper(HtmlHelper html, bool isValid, MvcHtmlString labelText)
{
TagBuilder tagBuilder = new TagBuilder("label");
if (!isValid)
{
tagBuilder.AddCssClass("error");
}
html.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
html.ViewContext.Writer.Write(labelText);
this.htmlHelper = html;
}
public void Dispose()
{
this.htmlHelper.ViewContext.Writer.Write("</label>");
}
}
}
}
@using (Html.BeginBlockLabel(m => m.Email))
{
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "validation" })
@Html.EmailFor(m => m.Email)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment