c# - 横截面 View 组件

标签 c# asp.net-core asp.net-core-viewcomponent

我有一个 ViewComponent 存储在名为“仪表板”的区域中,但现在我想在另一个名为“应用程序”的区域中使用此 ViewComponent。是的,我可以将其添加到 Root View /共享文件夹中,但我正在努力通过区域的强大包含使用来制作一个非常模块化的应用程序。

ASP.NET 5 RC1 MVC 6 似乎不支持对其他组件的跨区域引用。

如何添加其他查看位置?我需要补充: /Areas/Dashboard/Views/Shared/Components/DashboardMenu/Default.cshtml 作为 View 渲染器的搜索位置

InvalidOperationException: The view 'Components/DashboardMenu/Default' was not found. The following locations were searched:
/Areas/Applications/Views/Application/Components/DashboardMenu/Default.cshtml
/Areas/Applications/Views/Shared/Components/DashboardMenu/Default.cshtml
/Views/Shared/Components/DashboardMenu/Default.cshtml.

最佳答案

解决了...

启动.cs

// Add additional razor view engine configuration to facilitate:
// 1. Cross area view path searches
services.Configure<RazorViewEngineOptions>(options =>
{
    options.ViewLocationExpanders.Add(new RazorViewLocationExpander());
});

然后创建一个名为 RazorViewLocationExpander.cs 的类

using Microsoft.AspNet.Mvc.Razor;
using System.Collections.Generic;
using System.Linq;

public class RazorViewLocationExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context) { }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        List<string> locations = viewLocations.ToList();

        locations.Add("/Areas/dashboard/Views/Shared/{0}.cshtml");

        return locations;
    }
}

我一般不会推荐这个。我将此解决方案用作特殊情况,因为我使用一个区域来隔离模板和核心代码,以供其他(仅限成员(member))区域使用 - 因此他们需要知道在哪里可以找到此共享代码。我试图将公共(public)代码与管理代码分开,这是我能想到的最干净、最模块化的解决方案。所有需要成员(member)专用管理区域的网站都将显示仪表板区域。它稍微改变了 MVC 的规则。

关于c# - 横截面 View 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34438561/

相关文章:

c# - 如何在 Ubuntu 18.04 上运行 OpenCvSharp?

c# - asp.net MVC自定义Authorize属性,传递参数和方法细节

c# - 从 Visual Studio 运行 Outlook 应用程序时找不到自动发现服务

c# - Docker Copy 使用 ASP.net Core 失败

c# - SignInManager.PasswordSignInAsync() 成功,但 User.Identity.IsAuthenticated 为 false

c# - 呈现 ViewComponent 返回 HTML 500 错误

c# - 使用 Razor Pages 在 Asp.NET Core 2.2 中找不到 ViewComponent

c# - 如何将 net tcp 绑定(bind)合并到 web api 环境中?

c# - 选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?

jquery - 确认删除模式/对话框,Twitter Bootstrap 不起作用