如何从另一个控制器引用控制器功能
试图学习来自 Linux/LAMP 背景的 ASP MVC(换句话说,我是一个新手)...
出于某种原因,我似乎无法在另一个控制器中使用一个控制器中定义的函数。
这是我的 MessagesController.cs 文件中的函数:
public List<Message> GetMessagesById(string username)
{
return db.Messages.Where(p => p.user == username).ToList();
}
当我尝试引用它时:
using LemonadeTrader.Models;
using LemonadeTrader.Controllers; // added this to pull the Messages::getMesssagesById
...
ViewBag.messages = lemondb.Messages.GetMessagesById(Membership.GetUser().ProviderUserKey.ToString());
我得到了类似于柠檬数据库的内容。Messages 不包含名为 GetMesssagesById 的方法。
我该如何引用它?
Trying to learn ASP MVC coming from Linux/LAMP background (in other words I'm a newb) ...
For some reason I can't seem to use a function defined in a controller in another controller.
Here's the function in my MessagesController.cs file:
public List<Message> GetMessagesById(string username)
{
return db.Messages.Where(p => p.user == username).ToList();
}
When I try to reference it:
using LemonadeTrader.Models;
using LemonadeTrader.Controllers; // added this to pull the Messages::getMesssagesById
...
ViewBag.messages = lemondb.Messages.GetMessagesById(Membership.GetUser().ProviderUserKey.ToString());
I get something along the lines of lemondb.Messages does not contain a method called GetMesssagesById.
How do I reference it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该像这样链接控制器方法,更不用说控制器不应该直接执行数据访问。我建议您将此函数外部化到一个单独的类/存储库中,两个控制器都可以使用它。
示例:
然后:
好的,这是第一步。可以通过引入此存储库的抽象来将控制器与存储库解耦来改进此代码:
然后您可以对这些控制器使用构造函数注入:
最后您将配置您的 DI 框架以将相应的实现传递到这些控制器中。
我还建议您用强类型视图模型替换此
ViewBag
:然后:
You shouldn't be linking controller methods like this, not to mention that controllers shouldn't be performing data access directly. I would recommend you externalizing this function into a separate class/repository which could be used by both controllers.
Example:
and then:
OK, that's the first step. This code could be improved by decoupling the controllers from the repository by introducing an abstraction for this repository:
then you could use constructor injection for those controllers:
finally you would configure your DI framework to pass the corresponding implementation into those controllers.
I would also recommend you replacing this
ViewBag
with a strongly typed view model:and then:
将
GetMessageById
(以及访问消息所需的所有其他方法)放置在单独的类中,并在需要获取Message
数据的任何地方使用该类。Place
GetMessageById
(and all other methods needed for accessing messages) to separate class and use the class everywhere you need to getMessage
data.