.net core 3.1 - 查看组件 - 找不到我的 Default.cshtml
.net core 3.1 - View Components - Not finding my Default.cshtml
我刚刚开始了解我的 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 出现
谢谢
通过返回 View("123")
,您正在使用 this overload:
public ViewViewComponentResult View (string viewName)
Returns a result which will render the partial view with name viewName.
所以您传递的是视图名称,而不是字符串值作为视图的模型。
您可以通过显式调用 View<TModel>(TModel)
重载来更改它:
public IViewComponentResult Invoke()
{
var result = "123";
return View<string>(result);
}
在长 运行 中,我建议您改为创建一个模型 class,这样您就可以传递一个对象而不仅仅是一个字符串。这将避免出现这个特殊问题,您也可以在以后轻松扩展模型内容。
我刚刚开始了解我的 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 出现
谢谢
通过返回 View("123")
,您正在使用 this overload:
public ViewViewComponentResult View (string viewName)
Returns a result which will render the partial view with name viewName.
所以您传递的是视图名称,而不是字符串值作为视图的模型。
您可以通过显式调用 View<TModel>(TModel)
重载来更改它:
public IViewComponentResult Invoke()
{
var result = "123";
return View<string>(result);
}
在长 运行 中,我建议您改为创建一个模型 class,这样您就可以传递一个对象而不仅仅是一个字符串。这将避免出现这个特殊问题,您也可以在以后轻松扩展模型内容。