1

I'm using ASP.NET MVC 2 and want to figure out how to re-trigger the validation on my model after it has been populated using a custom binder.

So, I start with a couple of EF classes which are associated, Booking and Traveller (each booking can have one or more travellers)

Here's the buddy class I'm using to place balidation on Booking:

[MetadataType(typeof(Booking_Validation))]
public partial class Booking {
    // partial class compiled with code produced by VS designer
}

[Bind(Include="Name")]
public class Booking_Validation {

    [Required(ErrorMessage="Booking name required")]
    public string Name { get; set; }

    [AtLeastOneTraveller(ErrorMessage="Please enter at least one traveller")]
    public EntityCollection<Traveller> Travellers;

}

public class AtLeastOneTraveller : ValidationAttribute {        
    public override bool IsValid(object value) {
        if (value != null) 
            return ((EntityCollection<Traveller>)value).Count > 0;
        return true;            
    }
}

I use a custom model binder to populate the booking and it's associated travellers, except that ModelState.IsValid seems to be set even before my custom model binder has had a chance to add the travellers to the booking object, even even after doing so, ModelState["Travellers"] still contains the validation error saying there must be at least one traveller attached.

Is there any way to re-trigger validation after the custom model binder has done its thing?

Kris van der Mast
  • 16,343
  • 8
  • 39
  • 61
Brendan
  • 1,033
  • 10
  • 12

3 Answers3

4

Have you tried the TryValidateModel method on the Controller class?

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryvalidatemodel.aspx

amarsuperstar
  • 1,783
  • 1
  • 17
  • 22
  • Thanks, but I can't seem to get it doing the right job. When I run TryValidateModel, it returns false, but never seems to re-trigger my custom ValidationAttribute (which I have a breakpoint set on) – Brendan Sep 21 '10 at 20:59
  • belated - You will need to clear the ModelState of errors before calling TryValidateModel I found, the TryValidateModel method adds the errors back to the ModelState – m.t.bennett Sep 26 '12 at 07:00
-2

Once you have fixed the error items, you can clear the ModelState using

ModelState.Clear();

and then revalidate using

ModelState.IsValid
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281