我想通過一個asp.net核心MVC(mvc6?)項目中的所有可用ViewComponents列表進行搜索,像這樣。以列表形式訪問所有可用的ViewComponents
Default.cshtml爲ViewComponent
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的構造將不會被執行,我需要以某種方式「自動」註冊所有組件。那可能嗎?
不知道是否有任何方法列出子類ViewComponent的所有類(假設您通過從項目中的ViewComponent繼承來創建視圖組件)。可以在中間件級別獲得這些視圖組件的列表嗎? –