1

ASP.NET Core具有用於重用視圖部分的View Components機制。您可以在使用Component.InvokeAsync通話剃刀模板文件中的視圖組件:如何在ASP.NET Core中的剃鬚刀視圖中呈現之前檢查視圖組件是否存在

@await Component.InvokeAsync("MyComponent", new { data = 1 }) 

如果考慮到與給定的名稱組件不存在的InvalidOperationException拋出異常。

InvalidOperationException: A view component named 'MyComponent' could not be found. 

我想知道如何查看組件是否存在之前呈現在剃刀視圖。理想的情況是這樣的:

@if (Component.Exists("MyComponent") 
{ 
    @await Component.InvokeAsync("MyComponent", new { data = 1 }) 
} 
else 
{ 
    <p>Component not found</p> 
} 

回答

2

你可以注入IViewComponentSelector到您的視圖,以檢查是否組件存在:

@inject Microsoft.AspNetCore.Mvc.ViewComponents.IViewComponentSelector selector 

@if (selector.SelectComponent("MyComponent")!= null) 
{ 
    @await Component.InvokeAsync("MyComponent", new { data = 1 }) 
} 
else 
{ 
    <p>Component not found</p> 
} 
+0

這證實了我得到的它找不到的錯誤,但我不知道爲什麼,因爲它沒有給出任何其他線索,爲什麼它沒有找到組件。見http://stackoverflow.com/questions/43902264/viewcomponent-in-external-assembly-cannot-be-found –

2

@adem答案可能是最正確的爲你的問題,但您可以添加編譯時安全並通過他的類名調用視圖組件。 我相信這是一個更清潔的解決方案。爲視圖分量定義

兩個選項:

1 - 刪除ViewComponent sufix

public class MyComponent : ViewComponent 

2 - 添加[ViewComponent]屬性

[ViewComponent(Name = "MyComponent")] 
public class MyComponentViewComponent : ViewComponent 

要調用該組件

@await Component.InvokeAsync(nameof(MyComponent)) 

如果組件不存在,則會引發編譯錯誤。

相關問題