Frage

I'm trying to validate a model containing other objects with validation rules using the TryUpdateModel:

public class Post
{
    public User User;
}

public class User : IValidatableObject
{
    public string Captcha;

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {            
        if (/* check if captcha valid */)
        {
            yield return new
                ValidationResult("Captcha invalid.",
                    new[] { "Captcha" });
        }
}

public ActionResult Edit(int postId, string title)
{
    var post = postsRepository.Get(postId);
    if (TryUpdateModel(post))
    {
        /* save */
    }
}

The problem is that nested user is also validated but this is updating of the post and there is no captcha field in the form so modelstate always is invalid. How can I validate only value-type properties of the post?

War es hilfreich?

Lösung

I don't particularly agree with having a CAPTCHA check on a user model unless you require a CAPTCHA everywhere you use the User model.

That being said, you could...

  • Create a flag that must be set in order to actually check the CAPTCHA, and return valid otherwise.
  • Create another model which matches the current form exactly
  • Remove the CAPTCHA from the model and just take it in as a parameter to actions that require it
  • Set a sentinel value for CAPTCHA as a default which always returns valid
  • tons of other ideas...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top