【问题标题】:Inherited = false doesn't work for attribute of field in viewModelInherited = false 不适用于 viewModel 中的字段属性
【发布时间】:2013-12-26 17:15:31
【问题描述】:

我做了测试属性

    [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 始终无效。在验证时,它使用 NonInheritedRequired 的验证,尽管它具有 Inherited = false。 我该如何解决这个问题?

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc custom-attributes asp.net-mvc-viewmodel


    【解决方案1】:

    Inherited 属性在 MVC 中不受尊重。

    可能的解决方案:

    1. 实现一个custom ModelValidatorProvider,它将过滤掉不可继承的验证属性。

    2. 通过提供自定义TypeDescriptionProvider过滤掉不可继承的属性

    3. 在模型中使用 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,但我建议改为重新设计模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2016-05-31
      • 1970-01-01
      • 2010-11-30
      • 2012-11-26
      相关资源
      最近更新 更多