Ryan Buening
Ryan Buening

Reputation: 1660

Using nameof around member name in ValidationResult

I have the following code in my view model which is working correctly and puts a validation message on my view:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    yield return new ValidationResult("Required", new[] { "Insured.FirstName" });
}

However, I would like to reference the member name without using a string literal so I tried changing it to the following:

yield return new ValidationResult("Required", new[] { nameof(Insured.FirstName) });

This does not work. The validation message does not appear on my view. Is this not supported or am I doing this incorrectly?

Upvotes: 1

Views: 1647

Answers (1)

Ryan Buening
Ryan Buening

Reputation: 1660

Thanks to the comments above I ended up putting this in a Utilities class:

public static class Utilities
{
    public static string GetPathOfProperty<T>(Expression<Func<T>> property)
    {
        string resultingString = string.Empty;
        var p = property.Body as MemberExpression;
        while (p != null)
        {
            resultingString = p.Member.Name + (resultingString != string.Empty ? "." : "") + resultingString;
            p = p.Expression as MemberExpression;
        }
        return resultingString;
    }
}

and then I can do the following:

yield return new ValidationResult("Required", new[] { Utilities.GetPathOfProperty(() => Insured.FirstName) });

Upvotes: 2

Related Questions