0
votes

I am using C# MVC 4 serversided. The Gerenel purpose of the site is to get some textual information entered as well as a file committed by the user.

Therefore I use a ViewModel which is the "parent" ViewModel holding information about the textual information entered by the user called FileInformationViewModel. This "parent" ViewModel contains another "child" ViewModel, lets call it FileUploadViewModel.

Each of these ViewModels are derived from the IValidateObject and own their custom Validate function validating only the current attributes of the Model. This means that the "parent" ViewModel will not do any validation for the "child" ViewModel because the "child" ViewModel owns it's own specific validation function.

The "child" ViewModel will be validated through the automated Model Validation offered by MVC 4 and the ModelState will be set as expected. After that the "child" ViewModel is successfully bound to the "parent" ViewModel by MVC Model binding logic. If the validation fails for the "child" ViewModel the Validate function for the "parent" ViewModel will not be handled anymore but I would like to handle both Validations automated on Model Binding. Is there any way to achieve this or is the only possibility to manually validate the ViewModels on my controller?

To illustrate my construction, here's the "parent" ViewModel:

public class FileInformationViewModel : IValidatableObject
{
    public FileInformationViewModel()
    {
        ViewModel1 = new FileUploadViewModel();
    }

    public FileUploadViewModel ViewModel1 { get; set; }
    public string InputFieldToBeSet { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (!string.IsNullOrWhiteSpace(InputFieldToBeSet))
        {
            var result = new ValidationResult("Enter some information, please!", new[] { nameof(InputFieldToBeSet) });
            yield return result;
        }
    }
1

1 Answers

0
votes

Using IValidatableObject short-circuits validation. The first error returned will cause further validation to stop. That's just the breaks of the game. There's no way around that.

If you need all the errors at once, then you need to let the model binder handle the validation, using data annotations on your view model properties. You can actually handle pretty much every scenario imaginable this way, as you can always add your own validation attributes or there's multiple libraries of validation attributes out there.