Travis Travis - 1 month ago 14
C# Question

Generate URL Without Index Using Tag Helpers

I have an action link that looks like this

<a asp-controller="Complaint" asp-action="Index" asp-route-id="@complaint.Id">


This will then generate the link /Complaints/Index/be8cd27e-937f-4b7d-9004-e6894d1eebea

I'd like the link to not have Index. I've tried to add a new route to Startup but with no success.

routes.MapRoute(
"defaultNoAction",
"{controller=Complaint}/{action=Index}/{id}");


I can't find any documentation to see if it's possible to generate the URL with tag helpers without Index. Perhaps someone here knows how?

Answer

Decorate your controller's action with a route attribute that would have the route you need.

[Route("Complaints/{id}")]
public IActionResult Index(string id)
{
    return View();
}

This way your controller's action becomes the default one. Please make sure other methods have different signature.

UPDATE

To set up routing in Startup class it's important to define the order of routing rules correctly. Per ASP.NET Routing Documentation:

The route collection is processed in order. Requests look for a match in the route collection by URL matching. Responses use routing to generate URLs.

This means your specific rules should go first, and the default route template should go afterwards like a catch-all rule. In your case the following should do the trick.

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "complaints",
        template: "complaints/{id}",
        defaults: new { controller = "Complaints", action = "Index" });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});