How to fix 'asp-controller and asp-action attributes not working in areas'

By FoxLearn 2/21/2025 2:44:04 AM   710
In ASP.NET Core, if you're facing issues where the asp-controller and asp-action attributes aren't working, or if you encounter errors like 'form asp-action in areas can't find a controller,' you can follow these steps to resolve the issue.

When working with Areas in ASP.NET Core, Visual Studio might not automatically load the tag helpers for controllers and views within those areas unless you explicitly define the @addTagHelper directive in each area's _ViewImports.cshtml file.

asp-controller asp-action not working

To fix the issue of 'asp-controller' and 'asp-action' not working, you need to create a _ViewImports.cshtml file in your Area (for example, Admin) if it doesn't already exist.

Path: /Areas/Admin/Views/_ViewImports.cshtml

Copy the @addTagHelper Directive In your _ViewImports.cshtml for the area, copy the @addTagHelper directive from the main _ViewImports.cshtml file located in the /Views folder.

Example of the _ViewImports.cshtml file in the area:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

This ensures that all tag helpers, including those for form handling, links, and other MVC helpers, are available to views within the Admin area.

If you have other tag helpers, like custom tag helpers or third-party ones, you can also add them in the same way. But the important part is making sure that the @addTagHelper line is present, so the core MVC tag helpers are loaded.

By default, tag helpers are registered globally via the root Views/_ViewImports.cshtml. However, when you're working with Areas, each area requires its own _ViewImports.cshtml file in the Views folder of that specific area. Without this, Visual Studio and the runtime won't know to apply the tag helpers to views inside that area.

Double-check that the asp-action and asp-controller attributes are correctly set and match the names of the controller and action method.

For example:

<form asp-controller="Home" asp-action="Index" asp-area="Admin">
    <input type="submit" value="Submit" />
</form>

If your controller method is named Index and resides in HomeController in the Admin area, this form should work properly.