6

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?

0

2 Answers 2

8

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; }
Sign up to request clarification or add additional context in comments.

Comments

0

I created a string constant in a base class and subclassed my view models off that so I could use it.

For example:

public class BaseViewModel : IViewModel
{
    internal const string DateFormat = "dd MMM yyyy";
}

public class MyViewModel : BaseViewModel
{
    [DisplayFormat(ApplyFormatInEditMode = true,
                   DataFormatString = "{0:" + DateFormat + "}")]
    public DateTime? CreatedOn { get; set; }
}

This way I could also reference it with subclassing:

public class AnotherViewModel
{
    [DisplayFormat(ApplyFormatInEditMode = true,
                   DataFormatString = "{0:" + BaseViewModel.DateFormat + "}")]
    public DateTime? CreatedOn { get; set; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.