【发布时间】:2015-07-13 14:07:16
【问题描述】:
我正在尝试制作一个包含表格的 MVC 5 Razor 网页,该表格中的每一行都包含一个删除按钮,该按钮是发布操作:
<table>
<thead>
<tr>
<th>Name</th>
.
.
.
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach(var item in Model)
{
<tr>
<td>@item.Name</td>
.
.
.
<td>
@using(Html.BeginForm("Delete", "Person", FormMethod.Post))
{
@html.AntiForgetyToken()
@html.Hidden("personId", item.PersonId)
<button type="submit" class="btn">Delete</button>
}
</td>
</tr>
}
</tbody>
</table>
在控制器中:
public class PersonController : BaseController
{
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Delete(int personId)
{
// Do Something...
}
}
现在我的问题是,当在表格的任何行中按下删除按钮时,它总是提交页面中的第一个表单,这意味着无论我按什么提交按钮,表格中的第一个人总是被删除。 有什么想法可以解决这个问题吗?
编辑: 生成的页面html
<div class="page-header">
<h2>Person List</h2>
</div>
<table class="row table table-striped">
<thead>
<tr class="text-primary">
<th class="text-center">#</th>
<th>Name</th>
<th>Email</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">5</td>
<td>Ismail</td>
<td>ismail@example.com</td>
<td>Active</td>
<td>
<form action="/WebApp/Person/Delete?PersonID=5" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Uxhp0Bq1ATAwOXNODHmc74f12O2-dvFhQ5kletbmDkq64CEPWZlXXPKuHDoqSy4DXF6mJhYfGffc_YAn1yERxp69JCUT9IlGTKdfirvVvqE1" />
<div class="text-center">
<div class="btn-group btn-group-xs">
<a class="btn btn-default" href="/WebApp/Person/Details?PersonID=5">View</a>
<a class="btn btn-default" href="/WebApp/Person/Edit?PersonID=5">Edit</a>
<button class="btn btn-danger>Delete</button>
</div>
</div>
</form>
</td>
</tr>
<tr>
<td class="text-center">6</td>
<td>MoHaKa</td>
<td>MoHaKa@example.com</td>
<td>Active</td>
<td>
<form action="/WebApp/Person/Delete?PersonID=6" method="post">
<input name="__RequestVerificationToken" type="hidden" value="R4CUAuVpbGihZvrFxxCjCL_oJ7tgkS_Xxh67i_xCpMXpvZKR5ASUWrSCvjg52yRorF-Ypeau1oZwDi96caHyUj-gmBeHnx7NBgfJBLkLPnQ1" />
<div class="text-center">
<div class="btn-group btn-group-xs">
<a class="btn btn-default" href="/WebApp/Person/Details?PersonID=6">View</a>
<a class="btn btn-default" href="/WebApp/Person/Edit?PersonID=6">Edit</a>
<button class="btn btn-danger>Delete</button>
</div>
</div>
</form>
</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
我的眼睛可能在欺骗我,但我没有看到
hidden输入的personId,它应该是生成页面中 POST 有效负载的一部分。 -
是的,但是@AlexPolyankin 要求我删除隐藏的输入并改用 routeValues,顺便说一下,它给出了相同的结果
-
您的
controller仅限于HttpPost(而不是GET) - 调试您的控制器并检查您获得的personId参数的值。 -
我总是得到表中第一个人的Id值
-
嗯? 没有在您的
POST中传递int参数?鉴于上面的代码,您没有收到null异常?
标签: asp.net-mvc forms razor form-submit submit-button