Pages - Menu

Should MVC ViewModel have methods?


By design principle, ViewModel only contain properties, it certainly wouldn't have methods. However, there is always this temptation of convenience over convention, and to do this, we need excuses.

I have been working on MVC for a few years, but what is the big deal about it? In the old web form days, we always have this sort of ideas where front end developer will do layouts or javascripts, and then back end developers doing all these database calls and other logics. MVC and HTML5 bringing all these to the next level, View is predominantly used by front end developer, and they do not need to know anything about Controller or Repository, where a backend developer only responsible to populate the model and pass to the view then their jobs are done.

This is all achievable by having this separation of concern. With all these in minds, should MVC ViewModel have methods?

See it in sample

As usual, I pick example from first page result from google search.


The following method is inside a viewmodel. It claims that the method is for presentation only, therefore it is kinda legit.
   1: public IHtmlString Checked(double lower, double upper) {
   2:     return this.AverageRating > lower && this.AverageRating <= upper 
   3:         ? new HtmlString(" checked=\"checked\"") : null;
   4: }

But for real?

In my opinion, it is a no for me. If back end developer are to write this view model class, should I be concerned if the front end is using HTML5, JQuery or Flash?

My Alternative Solution


   1: public bool isAverage { get; set; }


   1: model.isAverage = (model.AverageRating > lower && model.AverageRating <= upper);


Checks isAverage and renders different HTML.

And you got the idea?


I still have not encountered a situation where I have to put methods in a model, if you got one, you are welcome to fire to me. :)

The closest one that I've got is this one. Taken from an example that I have written half a year ago.

   1: public int? Age {
   2:     get 
   3:     { 
   4:         return (DateTime.Today.DayOfYear >= DOB.DayOfYear) 
   5:             ? (DateTime.Today.Year - DOB.Year) : (DateTime.Today.Year - DOB.Year - 1); 
   6:     }
   7: }

It is not a method, but a property that loaded with some logic to calculate the age base on other properties of the model. And it has no concern of presentation layer!!

No comments:

Post a comment