【问题标题】:Calling non-action method from another controller从另一个控制器调用非动作方法
【发布时间】:2015-02-01 20:05:45
【问题描述】:

我是 MVC 新手,我找不到解决问题的方法。我想从另一个控制器调用非操作方法(返回字符串、int 等)。甚至可能吗?如何正确地做到这一点?我正在使用 ninject,我的控制器如下所示:

public class ShopController : Controller
{
  private IShopRepository repository;

  public ShopController(IShopRepository shopRepository)
  {
    this.repository = shopRepository;
  }

  public int GetShopId(string shopName)
  {
    // how to call this method from another controller?
    // here is linq query which needs shop table repository!
  }
}

抱歉我的英语不好,非常感谢您的回复!:)

【问题讨论】:

  • 只需将此非操作方法声明为静态

标签: asp.net-mvc asp.net-mvc-4 ninject


【解决方案1】:

让控制器调用其他控制器的实例方法并不是最好的设计。我建议您将方法 GetShopId 添加到 IShopRepository 中,以便使用存储库的每个组件都可以访问它(包括您的其他控制器)。毕竟,IShopRepository 是该方法所属的地方。

【讨论】:

    【解决方案2】:

    我认为最简单的解决方案是从您要使用其方法的控制器继承(前提是该方法不是私有的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2010-09-29
      • 2011-09-23
      • 1970-01-01
      相关资源
      最近更新 更多