I have a user object that is instantiated when a user logs in, this object stores all the user’s settings:
public class SiteUser
{
public string LoginId { get; set; }
public string Name { get; set; }
public DateTime PasswordChangedOn { get; set; }
public string Language { get; set; }
public string DateFormat { get; set; }
public string RoleName { get; set; }
public ICollection<SitePermission> SitePermissions { get; set; }
}
And a UserContext class that stores and manages the user’s session
public class UserContext
{
public SiteUser SiteUser { get; internal set; }
public static UserContext Current
{
get
{
if (HttpContext.Current == null || HttpContext.Current.Session == null)
return null;
if (HttpContext.Current.Session["UserContext"] == null)
CreateUserContext();
return (UserContext)HttpContext.Current.Session["UserContext"];
}
}
}
Now, whenever I have to display a date, be it in a grid, or in a text field, I would always want to reference the DateFormat property of the SiteUser object.
In most of the examples I see, data annotations are used to define the format of the date as such:
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PasswordChangedOn { get; set; }
I have tried modifying it to this:
[DataType(DataType.Date), DisplayFormat(DataFormatString = UserContext.Current.SiteUser.DateFormat, ApplyFormatInEditMode = true)]
But it didn’t work, giving me an error stating that the attribute argument must be a constant.
So what’s the best approach to set the format of my date to my models in an MVC application?
You could add a property in your view model and use that to render the date rather which would take into account the user specific date and render that in the view instead e.g.
Alternatively, you could just render the date in the view itself using the
DateFormatproperty. This actually gives you a bit more flexibility if wanted to change it later (e.g. went for a system-wide convention) as you wouldn’t need to recompile the site e.g.