Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

In it, he describes how the ModelMetaData class is now exposed in the Views and templated helpers. What I'd like to do is display an asterisk beside a form field label if the field is required, so I thought about using the IsRequired property of ModelMetaData. However, IsRequired by default is true for all non-nullable properties, while it's false for all nullable properties. The problem is, strings are always nullable, so the IsRequired property is always false for strings. Does anyone know how to override the default of how IsRequired is set? Alternatively, I thought about leveraging the RequiredAttribute attribute that I've been decorating my properties with, but the RequiredAttribute doesn't seem to be exposed through the ModelMetaData class. Does anyone know how to get around this problem?

Thanks in advance.

like image 890
Johnny Oshika Avatar asked Nov 02 '09 16:11

Johnny Oshika


1 Answers

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();
like image 88
zowens Avatar answered Oct 02 '22 20:10

zowens