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

旧时模样 提交于 2019-11-30 08:36:22

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!