您正在寻找view components。它们在功能上与MVC 5和之前的子操作类似。
public class LatestBlogPostsViewComponent : ViewComponent
{
private readonly BlogDbContext db;
public LatestBlogPostsViewComponent(BlogDbContext context)
{
db = context;
}
public async Task<IViewComponentResult> InvokeAsync(int limit, string orderBy)
{
var posts = // get latest posts;
return View(posts);
}
}
接下来,创建视图Views/Shared/Components/LatestBlogPosts.cshtml
并添加您想使您的最新博客文章列表的代码。您的视图的模型将是视图组件返回的posts
的类型。
最后,在你想要的最新博客文章要呈现的视图或布局调用使用组件:
@await Component.InvokeAsync("LatestBlogPosts", new { limit = 3, orderBy = "date asc" })
或者,如果你喜欢的TagHelper语法:
<vc:latest-blog-posts limit="3" orderBy="date asc"></vc:latest-blog-posts>
的后一种方法需要你register the view component(s)。
你为什么想从标签助手调用操作方法?你想达到什么目的? – Shyju
我想要做的事情使我的观点和模型尽可能简单。我收到包含属性基本集合的_potential_组件集合。我可以很容易地将它们作为上面提到的标签进行渲染,但实际上,每个组件都可能很复杂。在这个例子中,我需要调用CMS并检索最近的三篇博文。我对后端代码中的HTML编辑有内置的仇恨,并决定用某种视图管理控制器中的每个组件会使我在整个应用程序中具有更大的灵活性和可重用性。 – mnield
应使用标记助手来呈现内容,而不是向服务器发送更多请求。你能通过使用部分视图和子操作来实现你想要的吗? – Fran