我的应用程序中有一个索引页。当我从索引页中删除一条记录时,它正在被删除。但是当我从搜索页面(显示与索引页面相同的数据)中删除任何记录时,我无法删除该记录。它显示错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'JNN.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
这是我的 Controller ,它适用于索引页面:
public ActionResult Delete(int id)
{
ComplainTable et = oe.ComplainTables.Find(id);
oe.ComplainTables.Remove(et);
oe.SaveChanges();
return RedirectToAction("Index");
}
这是搜索页面的 ActionLink:
<td>
@Html.ActionLink("Update", "Update", new { id = item.ComplainId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ComplainId })
</td>
这是索引页的 ActionLink:
<td>
@Html.ActionLink("Update", "Update", new { id = item.ComplainId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ComplainId })
</td>
两个页面的代码相同,但是为什么删除搜索页面的记录会报错?
最佳答案
从搜索页面中的 ActionLink
传递时,item.ComplaintID
似乎为空。您应该像这样使用可为空的参数:
public ActionResult Delete(int? id)
{
if (id == null)
{
// return view
}
ComplainTable et = oe.ComplainTables.Find(id);
oe.ComplainTables.Remove(et);
oe.SaveChanges();
return RedirectToAction("Index");
}
或者使用 ActionLink
中的空合并运算符设置默认值:
Controller
public ActionResult Delete(int id)
{
if (id == 0)
{
// return view
}
ComplainTable et = oe.ComplainTables.Find(id);
oe.ComplainTables.Remove(et);
oe.SaveChanges();
return RedirectToAction("Index");
}
查看
@Html.ActionLink("Delete", "Delete", new { id = item.ComplainId ?? 0 })
关于c# - 无法从搜索页面删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51702040/