I created a Html Helper
to check if the ModelState is valid, and if has a error on the field, return a string (class name). I could have done this directly on the view, but I like a cleaner view. So, my class:
public static class ErrorHelper
{
private static string GetPropertyName<TModel, TValue>(Expression<Func<TModel, TValue>> expression)
{
// Get field name
// Code from: https://stackoverflow.com/a/2916344/4794469
MemberExpression body = expression.Body as MemberExpression;
if (body != null) return body.Member.Name;
UnaryExpression ubody = expression.Body as UnaryExpression;
if (ubody != null) body = ubody.Operand as MemberExpression;
return body?.Member.Name;
}
public static MvcHtmlString ReturnOnError<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, string @class)
{
var propertyName = GetPropertyName(expression);
if (propertyName == null)
return MvcHtmlString.Empty;
if (htmlHelper.ViewData.ModelState.IsValid || !htmlHelper.ViewData.ModelState.ContainsKey(propertyName))
return MvcHtmlString.Empty;
return htmlHelper.ViewData.ModelState[propertyName].Errors.Any()
? MvcHtmlString.Create(@class)
: MvcHtmlString.Empty;
}
}
Imports:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
How to use in the view:
<div class="form-group @Html.ReturnOnError(m => m.Name, "has-error")">
...
</div>
My original answer: https://stackoverflow.com/a/45329194/4794469