Should viewmodels be limited to only have properties, and not methods?
Let’s say I have a radio button in my view, and wants to see if the radio button should be checked.
I could do this entirely in my view:
@Html.RadioButton("radiobuttonName", "The value", (id == Model.PersonId))
or I could move this logic into the viewmodel:
@Html.RadioButton("radiobuttonName", "The value", Model.IsChecked(id)
using this method in the viewmodel:
public int PersonId { get;set;}
public bool IsChecked(int id)
{
return (id == PersonId);
}
Is this OK to do, or should it be done entirely in the view, or in some other way?
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 yourControllerand storing the result in theViewModelinstead 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 theViewModelis probably fine.In your example above I’d recommend doing this in the
ViewModelas then theViewModelcontains the logic in a single place rather than doing this many times copy and pasted in yourView.