新手MVC问题。在控制器中重复自己 [英] Newbie MVC question. Repeating myself in controller

查看:73
本文介绍了新手MVC问题。在控制器中重复自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍然是MVC模式的新手,我不确定在哪里放一些代码。



在我的控制器操作方法中,我正在检索数据库记录和将它们加载到一个传递给View的viewmodel中。我现在在同一个控制器中有一个不同的Action方法来检索完全相同的记录。



我想将记录检索代码放入自己的方法中。但是,就最佳实践而言,我该把它放在哪里?同一个Controller中的新方法?或者在我的Services命名空间中?或者在我的ViewModels命名空间中?



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?

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.

推荐答案

人们在这里有很大差异。您可以在控制器上放置一个私有的GetReports(int id),但是MVC纯粹主义者会说逻辑应该在模型中。因此,您可以创建模型并为其提供ID,模型应该从该ID自行填充。如果您想创建一个服务作为报告的接口,这样您就不会直接访问EF上下文,那么您当然也可以这样做,并且您的模型将使用这些服务来获取其数据。
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.


这篇关于新手MVC问题。在控制器中重复自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆