Asp.net-Core-Mvc
區域中的視圖組件
我可能做錯了(我找不到任何關於如何以其他方式做到這一點的文件)。在區域中創建 ViewComponent 時,搜尋路徑不正確:
namespace HelloWorld { [Area("Test")] public class HelloViewComponent : ViewComponent { public IViewComponentResult Invoke() { return View(); } } }
/Areas/Test/Views/Components/Hello/Default.cshtml而不是在以下異常中搜尋視圖:InvalidOperationException: The view 'Components/Hello/Default' was not found. The following locations were searched: /Views/Home/Components/Hello/Default.cshtml /Views/Shared/Components/Hello/Default.cshtml.我通過執行以下操作來呼叫視圖:(在
/Views/Home/Index.cshtml)@Component.Invoke("Hello")似乎沒有辦法包含一個區域來呼叫視圖。
關於從區域內呼叫 ViewComponent 的正確方法或上述內容是否不正確並且我犯了錯誤的任何想法。
該
Area屬性只能與控制器一起使用。當您向某個區域內的視圖發出請求時,如果該視圖中引用了任何視圖組件,則 MVC 會按特定順序查找該視圖組件的視圖。以下是當請求匹配基於區域的控制器與非區域控制器時,如何搜尋視圖組件視圖的區別。
例子:
- 查看組件的視圖搜尋路徑,用於請求諸如
/Admin/Home/IndexwhereAdminis a area 之類的請求。
- /Areas/Admin/Views/Home/Components/Products/Default.cshtml
- /Areas/Admin/Views/Shared/Components/Products/Default.cshtml
- /Views/Shared/Components/Products/Default.cshtml.
- 查看組件的視圖搜尋路徑之類的請求
/Home/Index(非區域請求)
- /Views/Home/Components/Products/Default.cshtml
- /Views/Shared/Components/Products/Default.cshtml.