In the past, when writing my code, I always assumed that the model should just consist of a bunch of auto properties populated by the controller. But I recently came across code like this and want to know if it’s valid for MVC:
public class SomeModel
{
public BusinessInfo BusinessInfo { get; set; }
public IList<BusinessService> BusinessServices { get; set; }
public IList<BusinessHour> BusinessHours { get; set; }
public BusinessService GetBusinessServiceByServiceId(int serviceId)
{
return BusinessServices.FirstOrDefault(businessService =>
businessService.Service.ServiceId == serviceId);
}
}
Is having a method like GetBusinessServiceByServiceId legitimate in this case?
EDIT:
This model is used as a strongly typed model for an ASP.NET MVC page, so it essentially acts like a ViewModel
I’d say no. If a
ViewModelrequires aBusinessServiceobject it should be given it by theController; finding aBusinessServiceobject by its id is the job of aRepositoryclass, which aViewModelis not. Also, in the example given,BusinessServicesshould be injected into theControllerin its constructor and accessed via in an interface rather than statically; the code example you’ve got there would be pretty difficult to test.I personally use
ViewModelsas data holders containing model data and properties indicating if aViewshould display certain elements.