[英]IViewLocationExpander not working for Partial Views (MVC Core)
我定義了一個自定義IViewLocationExpander來檢查多租戶Web應用程序中特定於站點的視圖。
想象一下,有兩個租戶WebsiteA和WebsiteB,以及HomeController和Index View的以下文件結構
我IViewLocationExpander將呈現瀏覽/首頁/ WebSiteA / Index.cshtml為WebsiteA和查看/主頁/ Index.cshtml為WebsiteB -因為有專門針對WebsiteB沒有索引視圖,以便它使用默認的。
我還在Views中設置了一個名為“ Common”的文件夾來保存任何局部視圖-這個想法是我可以以相同的方式呈現自定義的局部視圖(例如Header)。
這是我的IViewLocationExpander的代碼
public sealed class TenantViewLocationExpander : IViewLocationExpander
{
private ITenantService _tenantService;
private string _tenant;
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
string[] locations =
{
"/Views/{1}/" + _tenant + "/{0}.cshtml",
"/Views/Common/" + _tenant + "/{0}.cshtml",
"/Views/Shared/" + _tenant + "/{0}.cshtml",
"/Pages/Shared/" + _tenant + "/{0}.cshtml",
"/Views/{1}/{0}.cshtml",
"/Views/Common/{0}.cshtml",
"/Views/Shared/{0}.cshtml",
"/Pages/Shared/{0}.cshtml"
};
return locations;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
_tenantService = context.ActionContext.HttpContext.RequestServices.GetRequiredService<ITenantService>();
_tenant = _tenantService.GetCurrentTenant();
}
}
一切都適用於標准視圖,但是當我嘗試渲染部分視圖時,總是得到默認的返回值(例如,上例中的Views / Common / _Header.cshtml )。
我在布局中渲染部分像這樣...
<partial name="_Header.cshtml" />
如果我刪除Views / Common / _Header.cshtml文件-僅保留特定於站點的文件-我會得到一個異常,指出找不到該視圖
InvalidOperationException: The partial view '_Header.cshtml' was not found. The following locations were searched:
/Views/Shared/_Header.cshtml
似乎擴展器未在局部視圖的額外位置中添加。 所以我的問題是,如何配置IViewLocationExpander與Partials一起使用?
在舊版本的MVC中,我看到您可以通過設置ViewLocationFormats和PartialViewLocationFormats專門定義它們,但是在MVC Core中,我在任何地方都看不到該選項?
抱歉,如果這個問題在其他地方已被掩蓋-我在任何地方都找不到答案。
提前致謝!
對於閱讀此書的任何人來說,可能會有相同的問題-似乎您需要從partial標簽中省略“ .cshtml”。
<!--- Works with all ViewLocations defined in IViewLocationExpander --->
<partial name="_Header" />
而如果您包含如下所示的“ .cshtml”,則似乎僅搜索默認的部分視圖位置-“視圖/共享”
<!--- Only looks in 'Views/Shared' --->
<partial name="_Header.cshtml" />
不知道這是否是故意的,但對我而言,這絕對似乎是MVC中的一個奇怪錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.