gpt4 book ai didi

c# - 以列表的形式访问所有可用的 ViewComponents

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:56 25 4
gpt4 key购买 nike

我想在 asp.net core 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>
}
}

现在,我已经设法通过在运行时可用的列表中手动注册每个组件来做到这一点。但我想要完成的是在每个组件类文件中简单地注册每个 View 组件,如下所示:

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();
}
}

问题是每个 View 组件的构造函数在 View 组件被渲染之前不会被执行,我需要以某种方式“自动”注册所有组件。这可能吗?

最佳答案

为此,您需要使用反射。使用Assembly,可以获取项目中所有的Type,然后过滤其中BaseTypetypeof(ViewComponent)的地方。

var listOfViewComponents = Assembly
.GetEntryAssembly()
.GetTypes()
.Where(x => x.GetTypeInfo().BaseType == typeof(ViewComponent));

希望这对您有所帮助。

关于c# - 以列表的形式访问所有可用的 ViewComponents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42833917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com