I was thinking it would be super cool if I could hook up something that would add a display name attribute on the fly to any model property that didnt already have one. The idea开发者_如何学Python would be that if I have a property called FirstName I could just tiltlize it and make it "First Name"
MVC seems to have a provider model for everything. Is there anything I could use to do this?
This is just the expanded version of Doug's answer
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
{
var result = base.GetMetadataForProperty(modelAccessor, containerType, propertyName);
if (result.DisplayName.IsEmpty()) result.DisplayName = propertyName.InflectTo().Titleized;
return result;
}
}
and register it with mvc in the global asax like so:
ModelMetadataProviders.Current = new MyModelMetadataProvider();
Yes, you can do that. You just need to create your own ModelMetaDataprovider and override the DisplayName.
You can Use [DisplayName] attribute to achieve the goal For property, if You want to use for Model Basis, Then GoFor MOdelMetaDataProvider
ModelMetaDataProvider MSDN Docs
Sample Tutorial for ModelMetaDataProvider
Another Sample For ModelMetaDataProvider
精彩评论