问题
In my MVC application I have many properties of DateTime datatype and I define DataFormatString on every new property in this datatype is defined as below:
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 of this, I think there is another option to define these DataFormatStrings for just one place and at once by creating a new class containing constant value or using web config, etc. So, in this case what is the best way to use constant values i.e. date format, etc. I use globalization string on my web.config, but I am not sure defining date DataFormatStrings in web.config as well. Any help would be appreciated.
回答1:
I'd opt for 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; }
回答2:
There is a limitation that you are facing here - attribute parameters can be only compile-time ones. Because of this you have two options:
Just define a constant and use it in all the models, like this
private const string DateFormat = "{0:dd/MM/yyyy}"; [DisplayFormat(DataFormatString = DateFormat, ApplyFormatInEditMode = true)]
Define the format in web.config and create your own attribute, perhaps inheriting from
DisplayFormat
, that will go to web.config to retrieve necessary data. Should be really simple - you just need another constructor that will get format param from web.config. Something like that:public class WebConfigDateDisplayFormatAttribute : DisplayFormatAttribute { public WebConfigDateDisplayFormatAttribute() { DataFormat = System.Configuration.ConfigurationManager.AppSettings["DateFormat"]; } }
来源:https://stackoverflow.com/questions/30255539/using-constant-for-defining-property-format-in-mvc