0

Using MVC5, what is the best practice for transforming a model property into a view?

For example, I have a;

class Person
{
    DateTime DateOfBirth { get; set; }
}

And I'd like to display this property as Age (i.e; determine number of years between now and DateOfBirth). I could just put an extra property on the Person type, but wondering if there's a better way to consolidate this code into a single function I can invoke from multiple views as necessary?

RJ Lohan
  • 6,497
  • 3
  • 34
  • 54
  • 1
    Assuming you didn't want to add some sort of adapter or extension method on DateTime, an HtmlHelper extension would be relatively easy to write. – Tieson T. Apr 06 '14 at 00:27
  • If I used a DateTime extension, which is a good idea, how do I invoke that from the view? – RJ Lohan Apr 06 '14 at 00:32
  • here's a good reference if you want to go the extension route, including how to use it in the view http://stackoverflow.com/questions/5052752/adding-your-own-htmlhelper-in-asp-net-mvc-3 – aw04 Apr 06 '14 at 00:38
  • 1
    If you namespace the extension class to the base project namespace or register the extension namespace in your web.config, you use it just like a normal DateTime object: `@DateTime.ToAge()` – Tieson T. Apr 06 '14 at 00:38

0 Answers0