Steve McNiven-Scott
Steve McNiven-Scott

Reputation: 1902

Using TagHelpers in Area Views

I spent the last hour refactoring to use Areas, now all my Views don't seem to have function taghelpers :/

So this is what's in the Index.cshtml

       <div class="btn-group">
           <a asp-controller="Survey" asp-area="Admin" asp-action="Create" class="btn btn-primary">Create New</a>
       </div>

...and this is the rendered HTML :/

<div class="btn-group">
  <a asp-controller="Survey" asp-area="Admin" asp-action="Create" class="btn btn-primary">Create New</a>
</div>

Intellisense doesn't even show the asp- prefixes and syntax highlighting on the asp- attributes is also lost.

Other SO issues reference "asp-route-area" but that just renders out verbtim like the rest.

These all worked fine when they were in ~/Views/Name/Index.cshtml, move them out to ~/Areas/Name/Views/Name/ and nopers...

Any thoughts? Steve

Upvotes: 9

Views: 5223

Answers (2)

Dezzamondo
Dezzamondo

Reputation: 2318

As it turns out, adding the _ViewImports.cshtml file to the Areas/ folder cascades the visibility of the file to all Areas/{area}/views within the folder.

So rather than:

-> Areas
--> Area1
----> Views
------> _ViewImports.cshtml
--> Area2
----> Views
------> _ViewImports.cshtml

We can just do:

-> Areas
--> Area1
--> Area2
--> _ViewImports.cshtml

Or more visually

example file structure for _ViewImports in Areas

Upvotes: 6

adem caglin
adem caglin

Reputation: 24153

According to official docs:

The @addTagHelper directive makes Tag Helpers available to the view. In this case, the view file is Views/_ViewImports.cshtml, which by default is inherited by all view files in the Views folder and sub-directories; making Tag Helpers available. The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the Views directory or sub-directory.

If you use one layout per area, to use built-in tag helpers you should add _ViewImports.cshtml in ~/Areas/Name/Views/ folder(If you use shared layout you don't need. See MusicStore project for shared layout example).

I guess you used one layout per area and you didn't add _ViewImports.cshtml ~/Areas/Name/Views/. Copy /Views/_ViewImports.cshtml into ~/Areas/Name/Views/.

Upvotes: 17

Related Questions