C# 继承=假不';不适用于viewModel中字段的属性
我做了测试属性C# 继承=假不';不适用于viewModel中字段的属性,c#,asp.net-mvc,custom-attributes,asp.net-mvc-viewmodel,C#,Asp.net Mvc,Custom Attributes,Asp.net Mvc Viewmodel,我做了测试属性 [AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field, Inherited = false)] public class NonInheritedRequiredAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value,
[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field, Inherited = false)]
public class NonInheritedRequiredAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
return new ValidationResult((validationContext.DisplayName));
return null;
}
}
和视图模型
public class ViewModelA
{
[NonInheritedRequired]
public virtual string Property{ get; set; }
}
public class ViewModelB : ViewModelA
{
public override string Property{ get; set; }
}
作用方法
[HttpPost]
public ActionResult Index(ViewModelB viewModel)
{
if (ModelState.IsValid)
{
return View("OtherView");
}
return View(viewModel);
}
ModelState始终无效。在验证时,它使用nonheritedRequired的验证,尽管它已继承=false。
我怎样才能解决这个问题
谢谢。继承的
属性在MVC中不受尊重
可能的解决办法:
实现将筛选出不可继承的验证属性的
通过提供自定义的TypeDescriptionProvider
在模型中使用MetadataType
属性。这是最简单的
样品
[MetadataType(typeof(ModelAMetadata))]
public class ModelA
{
public virtual string Property { get; set; }
}
public class ModelAMetadata
{
[Required]
public string Property { get; set; }
}
[MetadataType(typeof(ModelBMetadata))]
public class ModelB : ModelA
{
public override string Property { get; set; }
}
public class ModelBMetadata
{
//notice that there is no Required attribute here
public string Property { get; set; }
}
最优雅的解决方案是#1,但我建议改为重新设计模型