Search code examples
asp.net-mvcuiviewcontrollerviewdata

Is it acceptable to place view logic in a strongly typed view-data class?


Say you've got a view which requires some piece of data which requires some calculation, but no outside dependances. (For example, an enumerable string listing of the past 5 years.) Is it acceptable to place this in a strongly typed view class?

Something like this:

class HomeIndexViewData
{

// ...some view data...

public IEnumerable<String> LastThreeYears
        {
            get
            {
                return new string[] { 
                    DateTime.Now.Year.ToString(), 
                    (DateTime.Now.Year - 1).ToString(), 
                    (DateTime.Now.Year - 2).ToString() };
            }
        }
}

Now, what if that calculation is dependant on some other property in the view data class? Suppose that if the year appears in a list of dates this 'LastThreeYears' property appends an asterisk to the end of the year?

Disclaimers: This is only for data that is specific to a single view and wouldn't be properly handled by a repository, view model, etc.

On one hand it seems to me that the view data should be just that: a lifeless collection of properties which are simply passed to the view from the controller. On the other hand, this is so much prettier.


Solution

  • Personally, I would do this. I think that property is OK. If you think of it as a VIEW MODEL, then it has VIEW LOGIC that way, doesn't it? It is definitely better than a lump of spaghetti code intertwined with the markup (I don't like these, though sometimes there's no running).

    The property is read only, it is used to output a result which is specifically needed by the view. My vote is - yes, go for it.