Using constant for defining property format in MVC

吃可爱长大的小学妹 提交于 2019-12-25 03:34:39

问题


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:

  1. 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)]
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!