跨区域ViewComponents

时间:2015-12-23 15:10:27

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

我有一个ViewComponent存储在一个名为" Dashboard"的区域中。但是现在我想在另一个名为" Appplications"的区域中使用这个ViewComponent。是的我可以将它添加到根视图/共享文件夹中,但我正努力通过强大的区域使用来创建一个非常模块化的应用程序。

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

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

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.

1 个答案:

答案 0 :(得分:2)

解决了......

Startup.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;
    }
}

我不会一般地推荐这个。我使用这个解决方案作为一个特例,因为我使用一个区域来隔离我的其他(仅限成员)区域的模板和核心代码 - 所以他们需要知道在哪里可以找到这个共享代码。我试图将公共代码与管理代码分开,这是我能想到的最干净,最模块化的解决方案。仪表板区域将出现在需要仅限会员管理区域的所有网站上。它略微弯曲了MVC的规则。