2

I have a model with an Entity Framework object on it. The EF object implements IValidatableObject and has a Validate() method on it.

For some reason the method runs twice, so I get two identical model errors on my page.

Any idea why this happens or how to stop it?

I tried adding an _isValidated private member variable but it appears to be resetting to false every time it runs so it must be creating and validating two instances of the model.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (string.IsNullOrWhiteSpace(CatName))
    {
        yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
    }
}

Edit: My model:

    public class KittyModel
    {
        public Cat Cat { get; set; }

        public int? SomeId { get; set; }

        public string SomeString { get; set; }
    }

Then Cat is just an EF object

    [MetadataType(typeof(CatMetadata))]
    public partial class Cat : IValidatableObject
    {
    public sealed class CatMetadata
    {
        [Required]
        public int? CatTypeID { get; set; }
    }

    // Some other get; only properties here

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrWhiteSpace(CatName))
        {
            yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
        }
    }
}
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • and can you show your model? and code that use and validate model in controller? – teo van kot Aug 19 '15 at 09:21
  • The model validates automatically when the page is posted, before any controller actions are executed. The complete model just has an EF object on it with the above Validate method, nothing special. – NibblyPig Aug 19 '15 at 09:22
  • @SLC Check please (if you haven't yet) http://stackoverflow.com/questions/10129669/validation-attribute-get-triggered-two-times and http://forums.asp.net/t/1617919.aspx?MVC+3+IValidatableObject+s+Validate+is+called+twice – Artiom Aug 19 '15 at 09:52
  • The 2nd one may be correct (not entirely sure), but I couldn't find a way to mitigate it. Any ideas? – NibblyPig Aug 19 '15 at 09:53
  • @SLC could you show your model? Does it belong to another model with validation? – Artiom Aug 19 '15 at 09:55

1 Answers1

2

I ran into the same problem today... and I believe this is the reason that Validation Method is called 2 time, from here:

If your model is a complex model inside of a complex model, validation might be called twice for model-level validators (which IValidatableObject is considered to be). That's because it's validated once as a stand-alone object, and then again as the property of its containing object.

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137