有一个很好的解释为什么@Html.Action(..)在GitHub问题中被删除:Why was @Html.Action removed?。
我们删除了它们,因为我们提出了一个我们认为整体更好的功能,称为视图组件。
鉴于该建议,很明显,您的示例的建议是创建一个View Component,按照惯例将其命名为TopNavViewComponent。
ViewComponents/TopNavViewComponent.cs
public class TopNavViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
// Code to instantiate the model class.
var yourModelClass = ...
return View(yourModelClass);
}
}
对View 的调用在已知位置查找Default.cshtml Razor 文件。这是该文件的外观示例(其预期位置以粗体显示):
Shared/Components/TopNav/Default.cshtml
@model YourModelClassType
@*
Your HTML, etc.
Standard Razor syntax and HTML can be used here.
*@
要使用这个新的视图组件,请将以下内容添加到您的 Layout 视图中,无论您希望在哪里呈现输出:
Shared/_Layout.cshtml
@await Component.InvokeAsync("TopNav")
这应该足以让您开始使用 View Components。需要了解的其他一些有用的信息是:
- 视图组件支持依赖注入。
- 在调用
InvokeAsync 时可以将参数传递到视图组件中。
我不会在这里讨论这两个功能,因为它们都包含在文档中并且超出了这个问题的范围。