0

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

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

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

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

~\Views\ControllerName
~\Views\Shared

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

该解决方案不必足够聪明就可以知道基控制器类名为 Foo。

4

1 回答 1

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);
}
于 2013-10-15T13:47:36.153 回答