2

How would one go about validating a nested List of Objects in an MVC Model?

I have an "Item" object which has an attached List of Revenue Entries:

public class ItemModel
{
    public int ItemID { get; set; }

    public virtual List<RevenueEntryModel> Revenues { get; set;}
}

This list can be edited on the page dynamically, and each item is validated individually using it's own model - "RevenueEntryModel". However, I want to be able to restrict users from entering Items without any Revenues.

Is it possible to validate whether this Revenues list is empty using Data Annotations? I'm already using Foolproof but I'm pretty sure it doesn't include this functionality.

1

2 Answers 2

1

There's a previous answer that will help you here. It's a thorough answer, but basically you need to use custom validation attributes:

Sign up to request clarification or add additional context in comments.

Comments

0

You can apply your own logic that checks the number of items in the Revenues collection.

Apply a class level validation attribute to the ItemModel class. You could use System.ComponentModel.DataAnnotations.CustomValidationAttribute for this.

This points to a custom method you would create.

The attribute construct would look something like this:

[CustomValidation(typeof (MyClassWhereMethodIsLocated), "MyStaticMethodName")]

Checkout this blog for additional details

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.