将Id传递给ActionMethod

时间:2015-07-02 12:38:59

标签: asp.net-mvc-5

我的表格中有一个删除按钮,我试图删除所选的行。

问题是我总是在post方法中获得一个空ID

<div>
<table class="table">
    <thead>
        <tr>
            <th>Role Name</th>
            <th>Action</th>
        </tr>
    </thead>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @using (Html.BeginForm("Delete","Role", new { id = item.Id },FormMethod.Post))
                {
                    <div class="form-actions no-color">
                        <input type="submit" value="Delete" class="btn btn-default" /> |
                    </div>
                }
            </td>
        </tr>
    }

</table>

在我的控制器中

// POST: Jobs/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult Delete(int id)
        {
            IdentityRole role = _context.Roles.Find(id);
            _context.Roles.Remove(role);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

每当我点击按钮时,id为空

1 个答案:

答案 0 :(得分:2)

根据您的评论,<form>代码中生成的html是

action="/Role/Delete/b1bc13ca-a855-48b0-90e2-9e5fc081ac86"

表示模型的Id属性为Guid的typeof。将POST方法签名更改为

public ActionResult Delete(Guid id)