Home > other >  Form POST method does not send request to correct route
Form POST method does not send request to correct route

Time:01-07

I have following Razor code:

 <form method="post" asp-controller="Cryptocurrency" asp-action="DeleteWatchedProduct">
                        <button type="submit" name="id" value="@providerItem.Item.Id" >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?

CodePudding user response:

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">
  • Related