【问题标题】:IViewLocationExpander not working for Partial Views (MVC Core)IViewLocationExpander 不适用于部分视图(MVC 核心)
【发布时间】:2023-04-09 07:21:01
【问题描述】:

我定义了一个自定义 IViewLocationExpander 来检查多租户 Web 应用程序中特定于站点的视图。

假设有两个租户 WebsiteA 和 WebsiteB 以及 HomeControllerIndex 视图的以下文件结构

  • 查看次数
    • 首页
      • 网站A
        • Index.cshtml
      • Index.cshtml

我的 IViewLocationExpander 将为 WebsiteA 呈现 Views/Home/WebSiteA/Index.cshtml 并为 WebsiteB 呈现 Views/Home/Index.cshtml - 因为没有特定的索引视图到 WebsiteB,所以它使用默认的。

我还在 Views 中设置了一个名为“Common”的文件夹来保存任何部分视图 - 想法是我可以以相同的方式呈现自定义的部分视图(例如标题)。

  • 查看次数
    • 普通
      • 网站A
        • _Header.cshtml
      • _Header.cshtml

这是我的 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 中,我看到您可以通过设置 ViewLocationFormatsPartialViewLocationFormats 来专门定义它们,但在 MVC Core 中我无法在任何地方看到该选项?

抱歉,如果这在其他地方被掩盖了 - 我无法在任何地方找到答案。

提前致谢!

【问题讨论】:

    标签: c# asp.net-core model-view-controller


    【解决方案1】:

    对于任何可能遇到相同问题的阅读本文的人 - 您似乎需要从部分标记中省略“.cshtml”。

    <!--- Works with all ViewLocations defined in IViewLocationExpander --->
    <partial name="_Header" />
    

    如果您包含如下所示的“.cshtml”,它似乎只搜索默认的部分视图位置 - “视图/共享”

    <!--- Only looks in 'Views/Shared' --->
    <partial name="_Header.cshtml" />
    

    不确定这是否是故意的,但在我看来,这绝对是 MVC 中的一个奇怪错误。

    【讨论】:

    • 谢谢!我以为我疯了。对我来说绝对是一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多