asp.net core and asp-route-id

isthat picture isthat · Apr 19, 2017 · Viewed 14.3k times · Source

I've created a contact controller with that signature :

public IActionResult Index(string id)

Nothing fancy in the route table :

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

In my home view, I tried to create a link to the contact/index :

<a asp-controller="Contact" asp-route-id="3255">Contact me</a>

The generated link seems fine and goes to the right action. With or without the asp-action, the generated link is :

<a href="/Contact/Index/3255">Contact me</a>

But the id is not set. But when I copy the link and do a "paste and go to", the id parameter is set. It also works if I view the page source and click on the link generated. It does not work when I click the link on the page.

Can you tell me what's wrong, please?

Answer

Nkosi picture Nkosi · Apr 19, 2017

Given the configured routes,

the route needs to include the action

<a asp-controller="Contact" 
   asp-action="Index" 
   asp-route-id="3255">Contact me</a>

Which should generate

<a href="/Contact/Index/3255">Contact me</a>