如何通过 asp.net mvc 中的按钮将 Id 发送到控制器

how to send an Id to controller by Button in asp.net mvc

我有一个 table,他们记录的末尾是 Buy Button。 如何将 foreach 中的产品 ID 发送到控制器。

@foreach(var model in Model)
{
   <tr>
       <td>@model.Title</td>
       <td>@model.Counts</td>
       <td>@model.Price</td>
       <td> <button class="btn btn-warning">Buy</button> </td>
   </tr> 
}

您可以使用任一 @Html.ActionLink() or HTML anchor tag with @Url.Action() 助手来发送模型的 Id 属性 并将其样式设置为看起来像一个按钮:

锚标签版本

<a href="@Url.Action("Buy", "ControllerName", new { id = model.Id })" class="btn btn-warning" role="button">Buy</a>

ActionLink 助手版本

@Html.ActionLink("Buy", "Buy", "ControllerName", new { id = model.Id }, new { @class = "btn btn-warning", @role = "button" })

两种方法将产生相同的结果(X指传递的ID值):

<a href="/ControllerName/Buy?id=X" class="btn btn-warning" role="button">Buy</a>