Jernej Novak
Jernej Novak

Reputation: 3283

ASP.net mvc does not validate submodel

I have two mvc models

public class Model1
{
    [Required]
    public int Id {get;set;}
    [Required]
    public string Name {get;set;}
}

public class Model2
{
    public Model1 ValidateThis {get;set;}
    public Model1 DoNotValidateThis {get;set;}
}

In postback I fill both properties ValidateThis and DoNotValidateThis. I want to validation occurs only on ValidateThis property.

Upvotes: 2

Views: 1271

Answers (3)

Jernej Novak
Jernej Novak

Reputation: 3283

With a little bit more research I chose next solution which works just fine for me. In controller i put next code for validation.

        var results = new List<ValidationResult>();
        bool isValid = Validator.TryValidateObject(
        model2obj.ValidateThis,
        new ValidationContext(model2obj.ValidateThis, null, null), results,true);

        ModelState.Clear();

        foreach (ValidationResult validationResult in results)
        {
            ModelState.AddModelError("ValidateThis." + validationResult.MemberNames.First(), validationResult.ErrorMessage);
        }

Upvotes: 1

Rune
Rune

Reputation: 8380

The default model binder does not support this. You will have to implement your own model binder:

  • Create a new attribute, DoNotValidateMeAttribute
  • Create a new model binder that, when doing model binding, checks to see if the DoNotValidateMeAttribute is present and, if not, does model binding without validation.

Then you would annotate your model like this

public class Model2
{
    public Model1 ValidateThis {get;set;}

    [DoNotValidateMe]
    public Model1 DoNotValidateThis {get;set;}
}

Googling "Custom model binders in ASP.NET MVC" should get you started. Be aware, though, that this will probably turn out to be a non-trivial task.

Upvotes: 1

Andrew
Andrew

Reputation: 5430

You can implement the IValidatableObject interface on Model2

public class Model2 :  IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
       ....
    }
}

Upvotes: 0

Related Questions