开发者

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<Str开发者_JAVA百科ing> 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.


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.


I think it's a quite bad code. Because of view data is the data model for single view page. So, you shouldn't write some logic in here. It should be written in controller class.

By the way, if this view data is called from a lot of view pages, I suggest you to move initializing source code to constructor of view data class.

Update

Please use the following pattern. Don't calculate value when it is called. Because it may affects your performance. Moreover, it much likes method pattern more than get-only property.

public class SomeViewModel
{
    public SomeViewModel()
    {
        // Initial value of all fields and property
    }

    public IEumerable<string> SomeProperty { get; protected/private set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜