BruceHill
BruceHill

Reputation: 7174

Tag helpers do not resolve when view is outside the Views folder

With Asp .Net 5 beta 6 the tag helpers do not resolve when the view is located outside the Views folder. The folder structure that I would like is one based on function rather than on file types. The controller, view models and views for a particular function I would like grouped together in a folder that reflects the controller name. Here is an example of the folder structure that I would like in the project:

 UI
   - Account
        - AccountController.cs
        - AccountViewModels.cs
        - Login.cshtml
        - Register.cshtml
   - Students
        - StudentsController.cs
        - StudentsViewModels.cs
        - CaptureStudent.cshtml

To accomplish this I have created a custom view engine:

public class CustomUIViewEngine : RazorViewEngine
{
    public CustomUIViewEngine(IRazorPageFactory pageFactory,
       IRazorViewFactory viewFactory,
       IOptions<RazorViewEngineOptions> optionsAccessor,
       IViewLocationCache viewLocationCache) :
       base(pageFactory, viewFactory, optionsAccessor, viewLocationCache)
    {
    }
    public override IEnumerable<string> ViewLocationFormats
    {
        get
        {
            var viewLocationFormats = base.ViewLocationFormats
            .Union(new string[] { "~/UI/{1}/{0}.cshtml" });
            return viewLocationFormats;
        }
    }
}

Which I register in startup.cs as follows:

services.AddMvc().ConfigureMvcViews(options =>
        {
            options.ViewEngines.Clear();
            options.ViewEngines.Add(typeof(CustomUIViewEngine));
        });

This custom view engine does work and the view gets located and rendered, with the only problem being that the tag helpers are not correctly rendered, so instead of seeing this:

<form method="post" class="form-horizontal" role="form" action="/Account/Login">

I am seeing this in the rendered source:

<form asp-controller="Account" asp-action="Login" method="post" class="form-horizontal" role="form">

Does anyone know why the tag helpers are not rendering correctly when the view is located outside the Views folder and if there is any way to correct this in an Asp.Net 5 web application?

Upvotes: 5

Views: 968

Answers (1)

RickAndMSFT
RickAndMSFT

Reputation: 22830

Are you adding your TH's in the _ViewImports file, and if so are the using statements being recognized? Have you tried adding the @addTagHelper directly to a view?

Some of this is mentioned in my Authoring Tag Helpers I go into to detail on inheritance hierarchy, adding, removing in an upcoming article.

Upvotes: 5

Related Questions