【问题标题】:Customising ViewComponent View location自定义 ViewComponent 查看位置
【发布时间】:2020-09-18 16:32:52
【问题描述】:

所以我按照 MSDN 指南查看了 ViewComponents,它为我提供了关于自定义 ViewComponent 将在何处查找其视图的建议:

services.AddMvc()
    .AddRazorOptions(options =>
    {
        options.ViewLocationFormats.Add("/{0}.cshtml");
    })
.SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);

{0} 变成 Components/{View Component Name}/{View Name}

这意味着在 ViewComponent 中我会使用:

public class CreateVC : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        return View("Hello");
    }
}

它会寻找Components/CreateVC/Hello.cshtml

我想摆脱Components 部分。实际上我也想去掉那个默认字符串中的CreateVC部分,所以我可以把options.ViewLocationFormats.Add("/Views/{0}.cshtml");放在startup中,用return view(nameof(namespacefolder) + "Hello")调用它,然后它会在Views/namespacefolder/Hello.cshtml中查找/p>

如何将{0} 改为不是Components/{View Component Name}/{View Name} ??而只是/{View Name} ??

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

    原来 LocationExpanders 应该能够做到这一点,但是

    https://github.com/dotnet/aspnetcore/issues/10277

    表明存在一个被微软忽略的错误,这意味着我们不能为 ViewComponents 覆盖此字符串 - 我将不得不想出一些迂回的方法来指定我的确切位置,而不使用魔术字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      相关资源
      最近更新 更多