【问题标题】:Can not delete the record from search page无法从搜索页面中删除记录
【发布时间】:2018-08-06 06:52:35
【问题描述】:

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

参数字典包含“JNN.Controllers.HomeController”中方法“System.Web.Mvc.ActionResult Delete(Int32)”的不可为空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。 参数名称:参数

这是我的控制器,它适用于索引页面:

  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>

两个页面有相同的代码,但为什么我在删除搜索页面的记录时收到错误?

【问题讨论】:

  • 两个问题的控制器是否相同?
  • 是的!对于这两个动作控制器是相同的。
  • 尝试设置可为空的int参数:public ActionResult Delete(int? id),或者将默认值设置为可选参数,如public ActionResult Delete(int id = 0)。另外我想看看ActionLinks是如何在搜索页面生成的。

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


【解决方案1】:

item.ComplaintID 在搜索页面中从 ActionLink 传递时似乎为空。您应该像这样使用可为空的参数:

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 的空合并运算符设置默认值:

控制器

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 })

【讨论】:

    【解决方案2】:

    您没有在搜索页面中提供ComplainIdComplainId 在搜索页面中必须是 null。请使用 Chrome 开发者工具 (F12) 检查搜索页面中上述链接的 id 是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2014-10-16
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多