我有一个抽象类和几个子类,并且我正在使用this answer中的抽象模型绑定器将它们绑定到特定的类中。
public abstract class BaseProductViewModel
{
public int Id { get; set; }
public string Type { get => GetType().FullName; }
public int DealerId { get; set; }
}
public class MortgageViewModel : BaseProductViewModel
{
// other properties with validation attributes
}
public class InsuranceViewModel : BaseProductViewModel
{
// other properties with validation attributes
}
我的编辑视图模型具有这些类和其他一些属性的集合。
public class EditFormViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
// other properties with validation attributes
public IList<BaseProductViewModel> Products { get; set; }
}
映射工作正常,但是验证“产品”列表是一个问题。我还将验证添加到BindModelAsync方法中:
using (bindingContext.EnterNestedScope(metadata, bindingContext.FieldName, bindingContext.ModelName, model: null))
{
await binder.BindModelAsync(bindingContext);
result = bindingContext.Result;
var validationResult = from prop in TypeDescriptor.GetProperties(result.Model).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(result.Model))
select new { Propertie = prop.Name, ErrorMessage = attribute.FormatErrorMessage(string.Empty) };
foreach (var validationResultItem in validationResult)
bindingContext.ModelState.AddModelError(validationResultItem.Propertie, validationResultItem.ErrorMessage);
}
ModelState.IsValid始终返回false(ValidationState为Unvalidated),因此我尝试清除它并再次明确地对其进行验证。现在,它正在验证,但只有EditFormViewModel的属性而不是Products项的属性。