jahu
jahu

Reputation: 5667

Make a specific controller grab views from a subfolder

Let's say I have a base controller class named Foo and an instance of this controller named Bar.

I need Bar to search for views in the following folders:

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

But I want other controllers to work same as before, which is to look for views just in:

~\Views\ControllerName
~\Views\Shared

Is it possible to achieve in asp.net-mvc?

The solution doesn't have to be clever enough to know that the base controller class is named Foo.

Upvotes: 0

Views: 141

Answers (1)

haim770
haim770

Reputation: 49105

It's kind of dirty approach, but you can try this in your Base Controller (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);
}

Upvotes: 2

Related Questions