Joel, Rafael, Byron and I just had a conversation about flattening domain objects to view models with AutoMapper. Rafael suggested that almost everything should end up as a string on the display model as that is what any one data point displayed in HTML is going to end up as anyway. This means that when one flattens a DateTime to a string, that there is a need to make the DateTime presentable as it is being flattened. For example, the absence of .AddFormatter<TextBoxDateFormatter>() below would make the string version of the DateTime by way of a .ToString() operation, creating a very ugly string for a user to see.
private static void CreateGlobalFormatters()
{
Mapper.ForSourceType<DateTime>().AddFormatter<TextBoxDateFormatter>();
}
TextBoxDateFormatter:
using System;
using OurApp.Core.Infrastructure;
using AutoMapper;
namespace OurApp.Web.UI.Config.AutoMapper.Formatters
{
public class TextBoxDateFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
DateTime? value = context.SourceValue as DateTime?;
return value.HasValue ? value.Value.ToString(DefaultFormats.TextBoxDate) : null;
}
}
}
DefaultFormats:
namespace OurApp.Core.Infrastructure
{
public static class DefaultFormats
{
public const string DatePickerDate = "yy-mm-dd";
public const string JavaScriptDate = "yyyy-mm-dd";
public const string TextBoxDate = "yyyy-MM-dd";
public const string ListItemDelimiter = ", ";
public const string CustomAttributeEmptySelectionText = "Any";
}
}
Now our point of debate: Should this be done or should the DateTime just end up as a DateTime at the DTO for a view? Joel wondered how one might conditionally set a date to be bright red in the view if the date signified something a month overdue? Rafael suggested that for such a calculation, a separate Boolean value would also need to be kept on the DTO in lieu of making a calculation in the view off of a DateTime on the DTO.
No comments:
Post a Comment