Ok, I’m not talking about making business logic decisions, but rather UI decisions.
For example, I’m rendering a table and one column displays a DateTime? property that needs to be formatted. Because the value is nullable I need to check that it’s not null before formatting.
If I wanted to be pedantic, I would have a FormattedDate property on my ViewModel:
public class MyViewModel
{
...
public DateTime? Date { get; set; }
public string FormattedDate
{
get
{
return this.Date.HasValue ? this.Date.Value.ToShortDateString() : "";
}
}
}
<%= Html.Encode(Model.FormattedDate) %>
Or I could save myself a few lines of code and simply slap it in the view:
<%= Html.Encode(Model.Date.HasValue ? Model.Date.Value.ToShortDateString() : "")%>
In this case, since this is something that only affects the view, I would argue that it’s OK to do it the second way (and also it’s more compact) but where do I draw the line between having my view cluttered with server-side code and having my ViewModel cluttered with “formatting” properties?
It doesn’t really save you any lines of relevant code if you put it directly in the View – it just moves it around.
However, if you put it in the View, you can only use it there. You can’t reuse the ViewModel’s logic elsewhere, and you can’t unit test it.
Keep your Views really dumb. I would say that Views should have as low a Cyclomatic Complexity as possible.
See this answer for more details.