CodexBloom - Programming Q&A Platform

Handling a Custom Validation Attribute for Complex Objects in .NET 7 MVC

👀 Views: 161 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
asp.net validation mvc dotnet-7 csharp

I've been researching this but I've been struggling with this for a few days now and could really use some help... I'm working on a .NET 7 MVC application, and I'm trying to implement a custom validation attribute for a complex object that contains a nested collection. The object looks like this: ```csharp public class Order { public int OrderId { get; set; } public List<OrderItem> Items { get; set; } } public class OrderItem { public int ProductId { get; set; } public int Quantity { get; set; } } ``` I want to create a validation attribute that ensures that each `OrderItem` in the `Items` collection has a `Quantity` greater than zero. However, I'm running into issues with getting the error messages to bind correctly. I've implemented the custom attribute as follows: ```csharp public class OrderItemsMustBeValidAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var items = value as List<OrderItem>; if (items != null && items.Any(item => item.Quantity <= 0)) { return new ValidationResult("Each item must have a quantity greater than zero."); } return ValidationResult.Success; } } ``` And I'm applying it like this: ```csharp public class CreateOrderViewModel { [OrderItemsMustBeValid] public Order Order { get; set; } } ``` The issue arises when I submit the form: while the validation works fine, I'm not seeing the validation message appear on the view. I've tried using `Html.ValidationMessageFor(model => model.Order)` in the Razor view, but it doesn't display the message. I suspect it might be related to how the validation context is being set up or how the errors are being added to the model state. I've also checked the ModelState in the controller action, and the error is being captured there, but it doesn't show up in the UI. I've tried using `ModelState.AddModelError()` directly in the validation attribute, but that also didn't resolve the issue. Any help on how to properly propagate the validation errors from a custom attribute to the view would be greatly appreciated! Thanks in advance! Any ideas what could be causing this? The stack includes Csharp and several other technologies. Thanks in advance!