代码之家  ›  专栏  ›  技术社区  ›  Johnny Oshika

ASP。NET MVC模型元数据:是否有方法根据RequiredAttribute设置IsRequired?

  •  14
  • Johnny Oshika  · 技术社区  · 16 年前

    Brad Wilson在ASP上发布了一个很棒的博客系列。NET MVC的新模型元数据: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

    1 回复  |  直到 16 年前
        1
  •  17
  •   zowens    16 年前

    public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
    {
            protected override ModelMetadata CreateMetadata(Collections.Generic.IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
            {
                var _default = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
                _default.IsRequired = attributes.Where(x => x is RequiredAttribute).Count() > 0;
                return _default;
            }
    }
    

    ModelMetadataProviders.Current = new MyMetadataProvider();