Search code examples
c#asp.net-coreasp.net-core-2.0asp.net-core-tag-helpers

Generating a nice URL with tag helpers in ASP.Net Core 2


How can I generate a nice URL with tag helpers?

For example:

 <a asp-controller="Article" 
    asp-action="FilterByTag" 
    asp-route-tagId="@tag.Id" 
    title="@tag.Description">
         <span class="badge badge-dark">@tag.Title</span>
 </a>

This code generate a URL like /Article/FilterByTag?tagId=2

But I would like to have /Article/FilterByTag/tagId=2 or /Article/FilterByTag/2

How can I generate this URL by using tag helpers?


Solution

  • Use attribute routing on the action like [Route("Article/FilterByTag/{tagId}")]

    Or for example

    [Route("[controller]")]
    public class ArticleController : Controller {
    
        //...other actions
    
        [HttpGet]
        [Route("FilterByTag/{tagId}")] // Matches GET Article/FilterByTag/2
        public IActionResult FilterByTag(int tagId) {
            //...
    
            return View();
        }    
    }
    

    That way, when the action is referenced from tag helpers the generated link will map to the route template for the action and return the desired format like Article/FilterByTag/2

    Attribute routing requires more input to specify a route; the conventional default route handles routes more succinctly. However, attribute routing allows (and requires) precise control of which route templates apply to each action.

    Reference Routing to Controller Actions