【问题标题】:Invoke controller from ViewComponent从 ViewComponent 调用控制器
【发布时间】:2016-11-23 14:43:09
【问题描述】:

你知道我是否可以从 asp.net 核心中的 ViewComponent 调用控制器吗? 我正在尝试这样的事情

public MyViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
         return (IViewComponentResult) new RedirectToActionResult
                        ("actionName", "controllerName", null);
    }

}

但我显然得到了 InvalidCastException。

【问题讨论】:

  • 您是否尝试过创建控制器并调用您的操作?
  • 我已经有了控制器和我需要调用的动作。问题是如何在视图组件中调用它
  • 我的意思是你不能在你的 ViewComponent 中创建你的控制器类的对象实例吗?如果可以,您可以通过创建的对象调用操作。

标签: c# asp.net-core asp.net-core-viewcomponent


【解决方案1】:

你知道我是否可以从 asp.net 核心中的 ViewComponent 调用控制器吗?我正在尝试这样的事情return (IViewComponentResult) new RedirectToActionResult("actionName", "controllerName", null);

做你想做的事是没有意义的。

控制器处理 HTTP 请求; ViewComponent 不处理 HTTP 请求 (see this section)。事实上,您更有可能从 Controller 调用 ViewComponent,而从 ViewComponent 调用 Controller。

您尝试使用的 RedirectToActionResult 将尝试将现有 HTTP 请求从 URL 重定向到不同的 URL。由于 ViewComponent 不处理 HTTP 请求,因此没有什么可重定向的,RedirectToActionResult 不合适。

如果您真的想从 ViewComponent 调用 Controller,那么您有两种选择:

  1. 在您的 ViewComponent 中,创建一个 Controller 实例并直接调用其中一个 Action。这会有点奇怪,因为您必须手动管理控制器上下文和依赖项。

  2. 在您的 ViewComponent 中,获取一个 HttpClient 的实例,并使用它向 Controller Action 发出 HTTP 请求。

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2021-06-21
    • 2011-06-29
    • 2018-02-02
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多