Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. There are many built-in Tag Helpers for common tasks - such as creating forms, links, image version number.
We are going to solve the issue that URL is not generated properly. There are several things to check:
Import tag helper correctly
In the _ViewImports.cshtml file, import tag helper as follow.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Notice: _ViewImports.cshtml should under the "Views" folder, since it works only for files in the "Views" directory or sub-directory.
Include tag helper in dependencies
Make sure "Microsoft.AspNetCore.Mvc.TagHelpers" is referred in the dependencies folder in Nuget.
Check self-defined routes in Startup.cs
Check the routes whether the codes in .cshtml files is consist with the template route.
For example in my case, my route is :
Startup.cs:
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=home}/{action=index}/{id?}");
});
When using tag helper for generate link, codes are like this in _​Layout.cshtml :
<ul class="navbar-nav">
<li class="nav-item">
<a asp-action="index" asp-controller="home" class="nav-link">List</a>
</li>
<li class="nav-item">
<a asp-action="create" asp-controller="home" class="nav-link">Create</a>
</li>
</ul>
Then the links are generated :
<div class="collapse navbar-collapse" id="collapseNabar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/">List</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/home/create">Create</a>
</li>
</ul>
</div>
Notice: If you only use app.UseMvc() in the Startup.cs, without a route defination. There might have issues, such as links are not generated. This is because you didn't give a template for routes, tag helper only return a "" as the value of href.
Check Attribute routing
Strange results occur when you define both self-defined routes in Startup.cs and attribute routing in controller. Try to use self-defined routes in Startup.cs only when using tag helper, or use app.UseMvc() + attribute routing in controller.
HomeController:
[Route("")] // delete these attribute routing when use self-defined routes
[Route("Home")]
[Route("Home/Index")]
public ViewResult Index()
{
var model = _employeeRepository.GetAllEmployee();
return View(model);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
}