Seriously, why should the view have to do this?
Map your core model which has the date time object to your mvc view model.
//core model
public class Person
{
public DateTime? BirthDate { get; set;}
}
//view model
public class PersonForm
{
public string BirthDate { get; set; }
}
So mapping might look like:
public interface IDomainToViewMapper<TModel, TViewModel>
{
/// <summary>
/// Use an automapper or custom implementation to map domain model to presentation model.
/// </summary>
/// <param name="source">domain model</param>
/// <returns>presentation model</returns>
TViewModel MapDomainToView(TModel source);
}
public interface IPersonMapper : IDomainToViewMapper<Person, PersonForm>
{
}
public class PersonMapper : IPersonMapper
{
#region IDomainToViewMapper<Person,PersonForm> Members
public PersonForm MapDomainToView(Person source)
{
PersonForm p = new PersonForm();
if (source.BirthDate.HasValue)
{
p.BirthDate = source.BirthDate.Value.ToShortDateString();
}
return p;
}
#endregion
}
And your controller action might look like:
public ActionResult Index()
{
Person person = //get person;
var personForm = _personMapper.MapDomainToView(person);
return View(personForm)
}
You won't have to change your view example at all then.
From Chapter 2, MVC 2 in Action (Manning)
public class CustomerSummary
{
public string Name { get; set; }
public bool Active { get; set; }
public string ServiceLevel { get; set; }
public string OrderCount { get; set;}
public string MostRecentOrderDate { get; set; }
}
This model is intentionally simple; it consists mostly of strings. That’s what we’re representing,
after all: text on a page. The logic that displays the data in this object will be
straightforward; the view will only output it. The presentation model is designed to
minimize decision making in the view.