Using constants to determine the format of a property in MVC

In my MVC application, I have many DateTime type properties , and I define a DataFormatString for each new property in this data type, as follows:

Model:

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


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

Instead, I think there is another way to define these DataFormatStrings for just one place, and immediately by creating a new class containing a constant value or using a web configuration, etc. So, in this case, what is the best way to use constant values, i.e. date format, etc. I am using the globalization string on my web.config, but I'm not sure if I am setting the DataFormatStrings date in web.config. Any help would be appreciated.

0
source share
2 answers

I would choose a custom attribute

public class ShortDateFormatAttribute : DisplayFormatAttribute
{
    public ShortDateFormatAttribute()
    {
        DateFormat = "{0:dd/MM/yyyy}";
        ApplyFormatInEditMode = true;
    }
}
....
[ShortDateFormat]
public DateTime StartDate { get; set; }
[ShortDateFormat]
public DateTime EndDate { get; set; }
+4
source

There is a limitation that you come across here - attribute parameters can only be compiled. Because of this, you have two options:

  • Just define a constant and use it in all models, e.g.

    private const string DateFormat = "{0:dd/MM/yyyy}";
    
    [DisplayFormat(DataFormatString = DateFormat, ApplyFormatInEditMode = true)]
    
  • Define the format in web.config and create your own attribute, possibly inheriting from DisplayFormat, which will go to web.config to retrieve the necessary data. It should be very simple - you just need another constructor that gets the param parameter from web.config. Something like that:

    public class WebConfigDateDisplayFormatAttribute : DisplayFormatAttribute
    {
        public WebConfigDateDisplayFormatAttribute()
        {
            DataFormat = System.Configuration.ConfigurationManager.AppSettings["DateFormat"];
        }
    }
    
+1
source

Source: https://habr.com/ru/post/1780083/


All Articles