In my application I have many properties like
[DisplayFormat(ApplyFormatInEditMode=false,ConvertEmptyStringToNull=false,DataFormatString="{0:0.00}")]
public decimal somedecimalvalue { get; set; }
Is there any way i can generalize this whenever a decimal property is created above format is applied to it
You can manually assign metadata for decimal properties in your models by creating custom DataAnnotationsModelMetadataProvider:
public class DecimalMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (propertyName == null)
return metadata;
if (metadata.ModelType == typeof(decimal))
{
// Given DisplayFormat Attribute:
// if ApplyFormatInEditMode = true
// metadata.EditFormatString = "{0:0.00}";
// for DataFormatString
metadata.DisplayFormatString = "{0:0.00}";
// for ConvertEmptyStringToNull
metadata.ConvertEmptyStringToNull = false;
}
return metadata;
}
}
And then register this provider in Global.asax.cs in Application_Start() method:
ModelMetadataProviders.Current = new DecimalMetadataProvider();
Then you can remove DisplayFormat attribute from decimal properties. Note that this won't affect other properties and you can safely add other data annotations on your decimal properties.
Read more about MetaData class and its properties.
Happy coding! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With