ASP.NET MVC - Job of Controllers

做~自己de王妃 提交于 2019-12-22 10:54:53

问题


I think I'm beginning to be confused with the job of a controller in MVC.

I have a service that exposes five functions:

  • list packages in queue
  • get package
  • delete package
  • accept package
  • deny package

My ASP.NET MVC controller depends on this service, and can generally execute a service call on an Action. I'm happy so far.

The second part is then building the ViewModel result. If I do this inside of the controller, the controller now has an exploding dependency list -- each action added increases the dependencies in order to build the view model, and these are all inherited by the controller. I don't like this very much. I'm building this controller that depends on N different view model builders, but only using one of them per request.

So I was thinking of pulling all of this out and applying action filters specific to each view model. I haven't done this yet, but it seems okay.

The question this is raising for me is: what is the responsibility of the controller? If I end up pulling the view model building into filters, my controller is doing little more than having a route execute a service call (and providing a filter plugin). If I instead leave my controller responsible for building each view model, it becomes a mess.

It seems like I almost want to instantiate an action per request, not a controller, and I'm just abusing filters to get at that?


回答1:


Do you have dedicated ViewModels and Poco-Models? If this is the case you can handle the data from the services inside the ViewModel. I am quite happy with this uproach.

public class PackageViewModel()
{
    public PackageDetail{get;set;}
    public int PackageID{get;set;}
    public List<Package>Packages{get;set;}
    public string SomeFilterCriteria{get;set;}

    publlic void FillPackageList(IPackageService packageService)
    {       
        Packages = packageService.GetPackages(SomeFilterCriteria);      
    }
}

In Controller:

public ViewResult ListPackages(PackageViewModel model)
{
    model.FillPackageList(PackageService);
    return View("ListPackages",model);

}

I dont understand what you mean by "view model builders".




回答2:


The controller is supposed to orchestrate all actions you want to occur in your view. If you pull this logic out into action filters, it's still doing the logic per route request, it's just going to be cleaner in your case.



来源:https://stackoverflow.com/questions/1240483/asp-net-mvc-job-of-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!