Created
November 26, 2013 14:12
-
-
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
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.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>"); | |
} | |
} | |
} | |
} |
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 (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