asp-controller and asp-action attributes not working
asp.net Coreasp.net Core-Mvcasp.net Core Problem Overview
Would anyone know what I am missing, why those asp-controller and asp-action tags are not working for me. I am implementing a project in ASP.NET MVC Core.
This does not fire:
<a asp-controller="App" asp-action="Trips" class="btn btn-lg btn-success">Go to Trips</a>
Razor works fine:
@Html.ActionLink("Go to Trips", "Trips", "App", new object { }, new { @class = "btn btn-lg btn-success" })
Do I need to configure some service for that to work. And also, which way is preferred? Razor is pretty popular with MVC, are those asp- tags a new, better way?
asp.net Core Solutions
Solution 1 - asp.net Core
After a little bit of digging I found that asp-controller
and asp-action
attributes are called anchor tag helpers, and are part of the
> Microsoft.AspNetCore.Mvc.TagHelpers namespace
Apparently it is an alternative to using Razor. I was able to resolve the issue by creating '_ViewImports.cshtml' and adding the below into the file:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Once done that, anchor tag helpers were recognized and button start working as anticipated.
Solution 2 - asp.net Core
When working with Areas I had to copy _ViewImport to the new Area\MyArea\Views
Solution 3 - asp.net Core
Adding @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
to the top of the cshtml file is worked.
Solution 4 - asp.net Core
took me a while to figure it out -- but if you are like me still struggling with
Cannot resolve symbol 'addTagHelper'
after trying the accepted answer, you are probably running an ASP.NET MVC
project instead of an ASP.NET Core
project and therefore can not use the taghelper. Instead you have to use the htmlhelper
TLDR;
If this answer didn't work for you, please use the htmlhelper (*)
@using (Html.BeginForm("Trips", "App"))
{
...
}
..instead of the taghelper (**)
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form asp-controller="App" asp-action="Trips">
...
</form>
(*) applies to > ASP.NET MVC 5.2
(**) applies to > ASP.NET Core 2.1, 1.0, 1.1, 2.0, 2.2, 3.0, 3.1, 5.0
Solution 5 - asp.net Core
@{
IDictionary<string, string> routeData = new Dictionary<string, string>();
routeData.Add("Id", point.Id.ToString());
routeData.Add("Name", point.Name);
routeData.Add("Address", point.Address);
}
<a asp-page="./AddCollectionPoint" asp-page-handler="Edit" asp-all-route-data="@routeData">
Razor Pages have modelcshtml.cs files, inherited from "PageModel", SO In my case my action methods in those files were not being recognized...I replaced asp-controller with asp-page and asp-action with asp-page-handler. Plus added a line for default route in startup.cs.
app.UseEndpoints(endpoints =>
{ endpoints.MapRazorPages(); endpoints.MapControllerRoute("default","{controller=Home}/{action=Index}");});
and it worked.