views:

59

answers:

2

Hi there,

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?

+1  A: 

Have you tried the TryValidateModel method on the Controller class?

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

amarsuperstar
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