Skip to content

Instantly share code, notes, and snippets.

@hudo
Last active October 12, 2015 23:38
Show Gist options
  • Save hudo/4104991 to your computer and use it in GitHub Desktop.
Save hudo/4104991 to your computer and use it in GitHub Desktop.
Validation helper
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