Maneksh Veetinal Maneksh Veetinal - 1 month ago 4x
C# Question

Set DataFormatString in Annotations from a Global Variable

Suppose if I have an Annotation like the following

[DisplayFormat(DataFormatString = "{0:#.00#}", ApplyFormatInEditMode = true)]

It works great. But suppose I want to replace the DataFormatString in real time i.e. some times like this {0:#.00#} and sometimes {0:#.000#} based on some application settings the user chooses. Is there a way to do that?

I tried storing the format string in a global variable, but it gives me the following error.

An attribute argument must be a constant expression, typeof expression
or array creation expression of an attribute parameter type

If I make the global variable constant it works but then the purpose is lost. Any advice on a work around?

Basically I would like to give the users an option to set the decimal spaces universally with out having to implement the feature on a per View/Controller basis.

I know I can put the culture using NumberFormat.CurrencyDecimalDigits. But this will ignore Zeros after the decimal.


Attribute requires constant string, you can't change that. Also this attribute does not provide ability to provide resource name. So, I think best way to you is creating DisplayTemplate and EditorTemplate for this property.

public decimal Bar { get; set; }

And in Bar template you can change format based on some application settings chosen by user:

@model decimal