有一个很好的解释why @Html.Action(..)
已在 GitHub 问题中删除:为什么@Html.Action 被删除? https://github.com/aspnet/Home/issues/343.
我们删除了它们,因为我们想出了一个我们认为总体更好的功能,称为“视图组件”。
鉴于该建议,很明显,您的示例的建议是创建一个查看组件 https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1,这将被命名为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 文件位于已知位置。以下是该文件的示例(其预期位置以粗体显示):
共享/组件/TopNav/Default.cshtml
@model YourModelClassType
@*
Your HTML, etc.
Standard Razor syntax and HTML can be used here.
*@
要使用这个新的视图组件,请将以下内容添加到您的Layout
view,无论您希望输出呈现在哪里:
共享/_Layout.cshtml
@await Component.InvokeAsync("TopNav")
这应该足以让您开始使用视图组件。其他一些有用的信息是:
- 视图组件支持依赖注入。
- 调用时可以将参数传递到视图组件中
InvokeAsync
.
我不会在这里讨论这两个功能,因为它们都包含在文档中,并且超出了这个问题的范围。