Click here to Skip to main content
15,911,360 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Still brand new to the MVC pattern, I'm unsure where to put some code.

In my controller action method, I'm retrieving database records and loading them into a viewmodel which is getting passed to a View. I've now got a different Action method in the same controller that retrieves the exact same records.

I'd like to put records retrieval code into its own method. But where do I put it as far as best practices go? A new method in the same Controller? Or in my Services namespace? or in my ViewModels namespace?

C#
public ActionResult Index(int id)
{
    var model = db.Reports.Find(id);
    // replace with GetReports(id)
    // or Models.Services.GetReports()
    // or ViewModels.GetReports()
    return View(model);
}
public ActionResult ExportToExcel(int id)
{
    var model = db.Reports.Find(id);
    // replace with GetReports(id)
    // or Models.Services.GetReports()
    // or ViewModels.GetReports()

    return ExcelResult;
}


What I have tried:

The code works. This is just a best practices question.
Posted
Updated 22-Jun-17 22:55pm

1 solution

People differ quite wildly here. You could just put a private "GetReports(int id)" on the controller, however MVC purists will say the logic should be in the model. So you can create a model and give it its ID and the model should self-populate from that id. If you want to create a service as an interface to your reports so you're not accessing EF context directly then you can certainly do that too, and your model would use those services to get its data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900