Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make configurable DisplayFormat attribute

I got a date format like:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? CreatedOn { get; set; }

Now, I want to make every datetime format in my application read from one config file. like:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = SomeClass.GetDateFormat())]
public DateTime? CreatedOn { get; set; }

but this will not compile.

How can I do this?

like image 876
Edi Wang Avatar asked Nov 27 '12 02:11

Edi Wang


1 Answers

The problem with this is .NET only allows you to put compile-time constants in attributes. Another option is to inherit from DisplayFormatAttribute and lookup the display format in the constructor, like so:

SomeClass.cs

public class SomeClass
{
    public static string GetDateFormat()
    {
        // return date format here
    }
}

DynamicDisplayFormatAttribute.cs

public class DynamicDisplayFormatAttribute : DisplayFormatAttribute
{
    public DynamicDisplayFormatAttribute()
    {
        DataFormatString = SomeClass.GetDateFormat();
    }
}

Then you can use it as so:

[DynamicDisplayFormat(ApplyFormatInEditMode = true)]
public DateTime? CreatedOn { get; set; }
like image 107
armen.shimoon Avatar answered Sep 20 '22 22:09

armen.shimoon