Home > database >  Calling post method from another controller's view
Calling post method from another controller's view

Time:11-17

Problem: Hi there, so in a view where a product is displayed I have a button to call post method to add this product in the cart but the button does not do it at all.

<div >
    <input  type="submit" value="Add to cart" asp-controller="Cart" asp-action="Add" asp-route-id="@Model.Id"/>
</div> 

And this is the method in the cart's controller

[HttpPost]
public async Task<IActionResult> Add(int productId)
{
    //Console.WriteLine("HelloCartAdd!");
    //Some logic.
    return RedirectToAction("Detail", "Product", productId);
}

CodePudding user response:

When the route parameter is defined as asp-route-id="@Model.Id" the action method should use 'id' parameter name:

[HttpPost]
public async Task<IActionResult> Add(int id)
{          
    ...
}

If the [HttpPost] attribute is applied to the action method add the formmethod="post" attribute to the <input> tag. I suppose the button is already located inside the form.

<form>
    <input  type="submit" formmethod="post"  value="Add to cart" asp-controller="Cart" asp-action="Add" asp-route-id="@Model.Id" />
</form>
  • Related