c# - 无法从搜索页面删除记录

标签 c# sql-server asp.net-mvc

我的应用程序中有一个索引页。当我从索引页中删除一条记录时,它正在被删除。但是当我从搜索页面(显示与索引页面相同的数据)中删除任何记录时,我无法删除该记录。它显示错误:

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/

相关文章:

c# - 反序列化保留本地时间的日期

sql-server - 在 T-SQL 中使用另一列的计算值填充一列

sql-server - 使用SSIS,如何找到人口最多的城市?

asp.net-mvc - 在具有静态内容的网站上进行全文搜索。 Lucene.net 与 elasticsearch

asp.net-mvc - 在 ASP.NET MVC 中是否有抽象身份验证的框架?

c# - 错误 : The type or namespace name 'Configuration' does not exist in the namespace 'System.Web'

c# - LINQPad 如何引用其他类,例如LINQ in Action 示例中的书籍

c# - 异步迭代器任务<IEnumerable<T>>

c# - 绑定(bind)组合框

c# - 如何在 Entity Framework 查询中将 DateTime 转换为 TimeSpan