ASP.NET MVC ModelMetaData: Is there a way to set IsRequired based on the RequiredAttribute?

前端 未结 1 1952
难免孤独
难免孤独 2020-12-31 08:02

Brad Wilson posted a great blog series on ASP.NET MVC\'s new ModelMetaData: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

相关标签:
1条回答
  • 2020-12-31 08:49

    You need to create your own ModelMetadataProvider. Here's an example using the DataAnnotationsModelBinder

    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;
            }
    }
    

    Then in your AppStartup in Global.asax, you will want to put the following in to hookup the MyMetadataProvider as the default metadata provider:

    ModelMetadataProviders.Current = new MyMetadataProvider();
    
    0 讨论(0)
提交回复
热议问题