Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application level number format asp.net mvc

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

like image 992
Zia Avatar asked Dec 03 '25 16:12

Zia


1 Answers

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! :)

like image 178
lucask Avatar answered Dec 06 '25 05:12

lucask