Reputation: 33
If I have a view model looking something like this:
public class FlightViewModel {
public BookingFlight BookingFlight { get; set; } // contains list of FlightPassengers
public FlightPassenger AddedPassenger { get; set; }
}
I have a view that displays the editor for both models along with a webgrid outputting the list of FlightPassengers contained in BookingFlight, similar to this:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<legend>Flight Booking</legend>
@Html.Partial("_CreateOrEditBookingFlight")
@Html.Partial("_CreateOrEditPassenger")
@grid.GetHtml()
<p>
<button name="button" value="addPassenger">Add New Passenger</button>
<button name="button" value="submitBooking">Submit Booking</button>
</p>
}
My issue is: both buttons cause require both the BookingFlight and FlightPassenger parts to be correctly validated. In an ideal scenario a user could add a valid passenger without any flight info being valid.
So what's the best way to only validate parts of a viewmodel? Or am I going about this all the wrong way?
Upvotes: 2
Views: 1305
Reputation: 10753
If you're using a single view model class, you could implement IValidatableObject
and its Validate
method
public class FlightViewModel : IValidatableObject {
public BookingFlight bookingFlight { get; set; } // contains list of FlightPassengers
public FlightPassenger addedPassenger { get; set; }
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext) {
// .IsValid properties are made up
if (!bookingFlight.IsValid && !addedPassenger.IsValid)
yield return new ValidationResult("Something blew up", new string[] { "addedPassenger", "bookingFlight" });
// implement other validation and yield additional
// ValidationResult's as needed
}
}
So, if the IEnumerable<ValidationResult>
returned has .Count > 0, then the view model will not validate.
Keep in mind, if you're using Validation Messages in your view, I think you might need the Validation Summary for any yield
'ed ValidationResult
's added.
Upvotes: 1