Search code examples
c#asp.net-mvcasp.net-corerazor

Form POST method does not send request to correct route


I have following Razor code:

<form method="post" asp-controller="Cryptocurrency" asp-action="DeleteWatchedProduct">
    <button type="submit" name="id" value="@providerItem.Item.Id" class="btn btn-danger">Delete</button>
</form>

and following action

[HttpPost("watched-product/{id}")]
public IActionResult DeleteWatchedProduct([FromRoute]string id)
{
   return RedirectToAction("WatchedProducts",new
   {
       deletedId = id
   });
}

When I hit the Delete button, it sends request to https://localhost:5003/cryptocurrency/deletewatchedproduct but desired target URL is https://localhost:5003/cryptocurrency/watched-product/id-is-here

How can I set it up?


Solution

  • Try to set the asp-route-id attribute for the form tag instead of defining it in the button.

    The asp-route-{value} attribute enables a wildcard route prefix. Any value occupying the {value} placeholder is interpreted as a potential route parameter. If a default route isn't found, this route prefix is appended to the generated href attribute as a request parameter and value.

    <form method="post" asp-controller="Cryptocurrency" asp-action="DeleteWatchedProduct",
        asp-route-id="@providerItem.Item.Id">