ASP.NET MVC ViewModel with methods - is it "legal"?
That's a really good question regarding the correct placement of logic. Your approach is certainly legal - but does it follow the spirit of MVC? :)
I'd say it depends on whether the logic in your method applies just to this View/ViewModel, or could be potentially applied to other ViewModels that deal with this underlying Model type (in your case, Person).
If this is a one-off calculation for the purposes of this specific ViewModel, keep it in the Model. If this calculation might be used for Person objects generally, consider using a static Service class e.g. PersonService
, and place your methods there.
You can have methods in your ViewModel
. If it's a single result you want to calculate each time then I'd suggest adding the evaluation code to your Controller
and storing the result in the ViewModel
instead but if you need to evaluate things using a method more dynamically and a Property can't do this for you then doing this in the ViewModel
is probably fine.
In your example above I'd recommend doing this in the ViewModel
as then the ViewModel
contains the logic in a single place rather than doing this many times copy and pasted in your View
.