Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to format Model properties in ASP.NET MVC(3)?

I've been looking a lot recently as best practices within the ASP.NET MVC framework, specifically around sparation of concern. My question here is, if I have a property on a model, where is the best place to do some formatting on that property?

I've thought about a few options but am not sure which is best. The example uses a DateTime. Sorry this got a bit long.

Option 1: In the view: @Model.TheDate.String("{0:'blah'dd/MM/yyyy}") I know this isn't right because the format string shouldn't be here (what if I want to change the format throughout the whole app)

Option 2: Extension method used within the view: @Model.TheDate.DisplayItNicePlease() This kind of makes sense because the view is chosing the extension method to use for formatting and the viewmodel just exposes the date property to the view. Not sure if the view or view model should be responsible for formatting though.

Option 3: In an Html Helper method, i.e. something like Where should I place Declarative HTML helpers in ASP.NET MVC 3 so you could use:

@Html.DisplayDateNice(Model.TheDate)

Option 4: Extra property on the view model to format it and return a string e.g.:

public string TheDateStr
{
    get
    {
        return TheDate.DisplayItNicePlease();
    }
}

And then in the view you just have

@Model.TheDateStr

Fairly similar to option 3 only it keeps the view really, really simple - the view literally just outputs what is in the model and doesn't care about the format of the data.

Option 5: DisplayFormat attributes, e.g.: On the view model:

[DisplayFormat(DataFormatString = "{0:'blah'dd/MM/yyyy}")]
public DateTime TheDate { get; set; }

And then on the view:

@Html.DisplayFor(m => m.TheDate)

I like this apart from again the format string is not reused, so bring on option 5...

Option 6: Some kind of custom DisplayFormatAttribute e.g. NiceDateDisplayFormatAttribute. This seems to me like it might be the nicest solution and works well if you just want a simple string formatting. I think this gets more complicated if you want something more complicated, e.g showing relative time (Calculate relative time in C#), in which case maybe this is best being in an extension method/html helper.

There are probably other ways I'm not even aware of...

like image 924
Ian Routledge Avatar asked Sep 23 '11 10:09

Ian Routledge


1 Answers

Either use an extension helper to format the type if this type formatting will be used a lot or add an extra property in the Model to return a formatted version of the original property.

like image 69
Chris Snowden Avatar answered Oct 06 '22 00:10

Chris Snowden