【问题标题】:.net core 3.1 - View Components - Not finding my Default.cshtml.net core 3.1 - 查看组件 - 找不到我的 Default.cshtml
【发布时间】:2020-10-25 16:55:36
【问题描述】:

我刚刚开始在我的 Razor 页面应用程序中使用 ViewComponents。

我的项目中有一个 ViewComponents 文件夹,其中包含我的 ViewComponent .cs 代码:

 public class RemoveFromCartViewComponent : ViewComponent
    {  
       
        public IViewComponentResult Invoke()
        {
             
            var result = "123";    
            return View(result);    

        }   
    
    }

然后我在 Pages/Shared/Components 中有另一个文件夹,名为 RemoveFromCart。在这个文件夹中,我有我的 default.cshtml

@model string

<h2>
    @Model
</h2>

只需将字符串放在 h2 标记中即可。

在我的项目 Layout.cshtml 文件中,我正在调用这个 ViewComponent:

   <div>
          @await Component.InvokeAsync("RemoveFromCart") 
   </div>

当我开始我的项目时,我得到的错误是:

*InvalidOperationException: The view 'Components/RemoveFromCart/123' was not found. The following locations were searched:
/Pages/Components/RemoveFromCart/123.cshtml
/Pages/Shared/Components/RemoveFromCart/123.cshtml
/Views/Shared/Components/RemoveFromCart/123.cshtml*

这表明我的观点应该被称为 123.cshtml,这似乎不正确。我在这里做错了什么?我应该只是期望看到文本 123 出现

谢谢

【问题讨论】:

    标签: razor-pages asp.net-core-3.1 asp.net-core-viewcomponent


    【解决方案1】:

    通过返回View("123"),您正在使用this overload

    public ViewViewComponentResult View (string viewName)

    返回一个结果,该结果将呈现名称为 viewName 的局部视图。

    因此,您传递的是视图名称,而不是字符串值作为视图的模型。

    您可以通过显式调用 View&lt;TModel&gt;(TModel) 重载来更改它:

    public IViewComponentResult Invoke()
    {
        var result = "123";    
        return View<string>(result);    
    }
    

    从长远来看,我建议您创建一个模型类,以便您可以传递一个对象而不仅仅是一个字符串。这将避免出现这个特殊问题,并且您以后还可以轻松扩展模型内容。

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多