使特定的控制器从子文件夹中获取视图

时间:2013-10-15 12:09:19

标签: c# asp.net-mvc asp.net-mvc-4 razor

假设我有一个名为Foo的基本控制器类和一个名为Bar的控制器实例。

我需要Bar在以下文件夹中搜索视图:

~\Views\Foo\Bar
~\Views\Foo\Shared
~\Views\Bar
~\Views\Shared

但我希望其他控制器能像以前一样工作,这就是在以下位置查找视图:

~\Views\ControllerName
~\Views\Shared

是否可以在asp.net-mvc中实现?

解决方案不必非常聪明,知道基本控制器类名为Foo。

1 个答案:

答案 0 :(得分:2)

这是一种肮脏的方法,但您可以在基本控制器(Foo)中尝试此操作:

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    if (filterContext.Result is ViewResult)
    {
        foreach (var engine in ViewEngineCollection.OfType<VirtualPathProviderViewEngine>())
        {
            var newViewLocations = engine.FileExtensions.Select(ext => "~/Views/Foo/{1}/{0}." + ext).ToList();
            newViewLocations.AddRange(engine.ViewLocationFormats);
            engine.ViewLocationFormats = newViewLocations.ToArray();
        }
    }

    base.OnResultExecuting(filterContext);
}

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
    if (filterContext.Result is ViewResult)
    {
        foreach (var engine in ViewEngineCollection.OfType<VirtualPathProviderViewEngine>())
        {
            var removeViewLocations = engine.FileExtensions.Select(ext => "~/Views/Foo/{1}/{0}." + ext).ToList();
            var removedLocations = engine.ViewLocationFormats.ToList();
            removedLocations.RemoveAll(x => removeViewLocations.Contains(x));
            engine.ViewLocationFormats = removedLocations.ToArray();
        }
    }

    base.OnResultExecuted(filterContext);
}