简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM