如何解决如何在 ASP.NET Core 的不同位置使用 View Component 的视图?
我在我的项目中使用视图组件。有时,我需要使用与各种样式相同的视图组件。我研究了很多,但没有找到解决方案。
下面的代码工作正常,但是当我这样做时,我无法按照我想要的方式使用它。
查看组件类:
public IViewComponentResult Invoke(BlogSidebarviewmodel vm)
{
vm.BlogTags = _uow.BlogTag.GetAllByPriority(true,vm.LangId,vm.WebsiteId);
vm.BlogCategories = _uow.BlogCategory.GetAllByPriority(true,vm.WebsiteId).Include(p=>p.BlogTag);
vm.RecentBlogs = _uow.Blog.GetAllByEnabledDate(true,vm.WebsiteId);
//return View(vm); //For Default Blog Sidebar View Component
//return View("RedComponent",vm); //For Red Blog Sidebar View Component
//return View("GreenComponent",vm);//For Green Blog Sidebar View Component
}
@await Component.InvokeAsync("BlogSidebar/RedComponent");
或
@await Component.InvokeAsync("~/Views/Shared/Components/BlogSidebar/GreenComponent.cshtml");
我想在各种视图中使用视图组件。我能怎么做?我可以吗?
编辑
我可以同时使用视图组件的视图吗?例如,当我在“Blogs/ABC.cshtml”视图中使用“GreenComponent”时,我想在“Blogs/XYZ.cshtml”视图中使用“RedComponent”视图。
解决方法
请按照以下步骤使用视图组件:
1.在文件夹GreenComponent.cshtml
中创建Views/Shared/Components/BlogSidebar
。
2.创建名为 BlogSidebar
的视图组件:
public class BlogSidebar : ViewComponent
{
public IViewComponentResult Invoke(BlogSidebarViewModel vm)
{
vm.Id = 1;
vm.Name = "aaa";
return View("GreenComponent",vm);
}
}
3.GreenComponent.cshtml:
@model BlogSidebarViewModel
Name: @Model.Name
4.Index.cshtml:
@model BlogSidebarViewModel
@await Component.InvokeAsync("BlogSidebar",new BlogSidebarViewModel())
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。