Reputation: 23690
How do I check if a single property in my model has a validation error, from within my view?
I realise that I can do this, but it's not strongly typed so I'm concerned it's prone to errors:
@if (ViewData.ModelState["MyProperty"].Errors.Count() > 0)
{
// Show validation error
}
Upvotes: 0
Views: 94
Reputation: 76238
You can use something like this:
public static bool IsValidFor<TModel, TProperty>(this TModel model,
System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
ModelStateDictionary modelState)
{
string name = ExpressionHelper.GetExpressionText(expression);
return modelState.IsValidField(name);
}
Usage:
if (!model.IsValidFor(x => x.MyProperty, ModelState))
{
// Show validation error
}
Courtesy: this answer
Upvotes: 1