【问题标题】:Mvc Core 2.0 view componentsMvc Core 2.0 查看组件
【发布时间】:2017-06-13 14:35:26
【问题描述】:

我正在使用 mvc core 2.0 项目,但视图组件不工作。

我收到此错误

InvalidOperationException:找不到视图组件的“Invoke”或“InvokeAsync”方法

[ViewComponent(Name = "Footer")]
public class FooterViewComponent : ViewComponent
{
    public ViewViewComponentResult Invoke()
    {      
        var model = new FooterModel();

        return View(model);
    }
}

【问题讨论】:

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


    【解决方案1】:

    将 Invoke 的返回类型更改为 IViewComponentResult

    [ViewComponent(Name = "Footer")]
    public class FooterViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            var model = new FooterModel();
    
            return View(model);
        }
    }
    

    并在视图中使用它:@await Component.InvokeAsync(typeof(FooterViewComponent))

    我使用的是 ASP.Net Core 2.0,视图组件对我来说工作正常。

    【讨论】:

    • 我得到了同样的错误...对于在 VS 中打开的每个剃须刀页面,该错误都是重复的。这对我来说没有任何意义。我的视图组件类看起来与你的相同上面..但我仍然得到错误..
    • 你在哪个 .Net 版本上,@ZachPainter?你能分享一个回购什么的吗?
    • 我目前正在使用 .Net 5.. 我不想浪费时间来创建一个 repro.. 如果你想重现它,只需创建一个带有视图组件的新 web mvc 项目,然后然后在视图中渲染它.. 构建项目.. 然后打开任何视图.. 你应该会看到错误.. 一个细微的区别是我使用标签助手“<... url>
    【解决方案2】:

    在我的实现中,视图组件的 Invoke 方法必须是 Async 方法,并且应该返回一个 Task 作为输出。这就是它对我的工作方式:

    我的视图组件:

    public class XTestEntityViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync(int id)
        {
           // Put your stuff here . . . 
        }
    }
    

    您可以从应用程序中的任何视图访问它,如下所示:

    @await Component.InvokeAsync("XTestEntity", new { id = 4 })
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2018-04-09
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多