Luke
Luke

Reputation: 23690

Strongly Typed View Helper to Check Validation of a single property

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

Answers (1)

Mrchief
Mrchief

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

Related Questions