开发者

Is it a good practice to call a method from a model in ASP.NET MVC

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 ViewModel requires a BusinessService object it should be given it by the Controller; finding a BusinessService object by its id is the job of a Repository class, which a ViewModel is not. Also, in the example given, BusinessServices should be injected into the Controller in 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 ViewModels as data holders containing model data and properties indicating if a View should display certain elements.


While basicaly having helper methods inside a ViewModel is not forbidden, it sounds like the problem is actually in your View.

One of the goals of the MVC pattern (IMO) was to leave as much of the logic possible inside the controller's Actions.

So again while having helper methods inside a ViewModel is not a bad practice by itself, adding more logic to the View than required is.

EDIT: for example, maybe in your example changing the BusinessServices IList inside your ViewModel to a Dictionary would be a better solution


Yes, it is perfectly valid and common to have methods in your Model classes.

You are probably thinking of other kind of classes. For example, most of the times ViewModels have only properties but no (or very few) methods.

Classes that have only properties and no methods are typically called DTO for "Data Transfer Objects" and Models certainly don't fall on this category.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜