Last active
October 12, 2015 23:38
-
-
Save hudo/4104991 to your computer and use it in GitHub Desktop.
Validation helper
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
public static class Extensions | |
{ | |
public static MvcHtmlString WriteIfError<M, P>(this HtmlHelper<M> htmlHelper, Expression<Func<M, P>> expression, string value) | |
{ | |
string expressionText = ExpressionHelper.GetExpressionText(expression); | |
string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText); | |
if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName)) | |
{ | |
return null; | |
} | |
ModelState modelState = htmlHelper.ViewData.ModelState[modelName]; | |
ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors; | |
ModelError modelError = (((modelErrors == null) || (modelErrors.Count == 0)) | |
? null | |
: modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]); | |
if (modelError == null) | |
{ | |
return null; | |
} | |
return MvcHtmlString.Create(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment