Different validation on multiple models in a view?

If you're using a single view model class, you could implement IValidatableObject and its Validate method.

Up vote 1 down vote favorite share g+ share fb share tw.

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) Flight Booking @Html. Partial("_CreateOrEditBookingFlight") @Html.

Partial("_CreateOrEditPassenger") @grid.GetHtml() Add New Passenger Submit Booking } 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? Mvc asp. Net-mvc-3 razor link|improve this question edited Jun 10 '11 at 12:06 asked Jun 10 '11 at 11:22Spoon83.

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 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 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.

Thanks David, this should do the trick :) – Spoon Jun 12 '11 at 16:22.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions