【发布时间】:2017-03-16 21:01:34
【问题描述】:
我想在 asp.net 核心 MVC (mvc6?) 项目中搜索所有可用 ViewComponents 的列表,类似这样。
ViewComponent 的 Default.cshtml
foreach (var section in Model.sections)
{
var sectionId = section.Id;
if (_siteSettings.AvailableComponents.Any(c => c == sectionId))
{
@await Component.InvokeAsync(sectionId);
}
else
{
<p>Could not find component: @sectionId </p>
}
}
现在,我已经设法通过在运行时可用的列表中手动注册每个组件来做到这一点。但是我想要完成的是在每个组件类文件中简单地注册每个视图组件,如下所示:
public class NewsList : ViewComponent
{
private ISiteSettings _siteSettings;
private string ComponentName = "NewsList";
public NewsList(ISiteSettings siteSettings)
{
_siteSettings = siteSettings;
_siteSettings.AvailableComponents.Add(ComponentName);
}
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
问题是每个视图组件的构造函数在视图组件被渲染之前不会被执行,我需要以某种方式“自动”注册所有组件。这可能吗?
【问题讨论】:
-
不知道是否有任何方法可以列出所有子类 ViewComponent 的类(前提是您通过从项目中的 ViewComponent 继承来创建视图组件)。可以在中间件级别获得这些视图组件的列表吗?
标签: c# asp.net-mvc asp.net-core-mvc