最近离开 MVC 一段时间,回到一个旧项目,尝试重写我之前完成的代码,但在从列表中删除项目时遇到了困难,使用 EF 没问题,但我正在尝试不要使用 Entity Framework 来管理我的模型数据。我想将我的模型用作数据库,直到我乐意提交为止。
我重写了该问题以简化它,而不是转储大量代码,当单击删除时,我收到以下错误:
参数字典包含“Project.Views.requestedController”中方法“System.Web.Mvc.ActionResult RemoveRequested(Int32)”的不可空类型“System.Int32”的参数“id”的空条目'。可选参数必须是引用类型、可为 null 的类型,或者声明为可选参数。 参数名称:参数
我认为 id 通常由 EF 处理,但我认为 [key]
会将其处理为自动增量 - 这可以排序吗?
希望这是有道理的。动态我并不真正关心,所以理想情况下没有 jQuery/java 脚本,除非我必须这样做。
代码:
部分 View
@model IEnumerable<Project.Models.Allocation>
@using (Html.BeginForm())
{
if (Model != null)
{
foreach (var ri in Model)
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
@ri.one
</span>
</div>
<div class="ui-block-b">
<span>
@ri.two
</span>
</div>
<div class="ui-block-c">
<span>
@ri.three
</span>
</div>
<div class="ui-block-d">
<span>
@Html.ActionLink("Delete", "RemoveRequested", new { id = ri.id })
</span>
</div>
</div>
}
}
模型
public class Allocation
{
[Key]
public int? id { get; set; }
[Required]
public string one { get; set; }
[Required]
public string two { get; set; }
[Required]
public string three { get; set; }
}
public class Container
{
[key]
public int? id { get;set; }
[Required]
public List<Allocation> requested { get;set; }
}
Controller 操作方法
public ActionResult RemoveRequested(int id)
{
var newContainer = (Container)Session["containerSession"];
if(newAllocation.requested != null)
{
var del = newContainer.requested.Find(m => m.id == id);
newContainer.requested.Remove(del);
}
Session["containerSession"] = newContainer;
return RedirectToAction("Index");
}
最佳答案
我不会有可为 null 的键并添加 [DatabaseGenerate(DatabaseGenerateOption.Identity)]
属性。
更改您的分配
类型,将其更改为:
public class Allocation
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
public string one { get; set; }
[Required]
public string two { get; set; }
[Required]
public string three { get; set; }
}
这现在将与您的操作参数匹配。 但是,如果您的 key 为空,您一定有其他问题,它们现在将使用默认值零。
另一种选择是更改您的操作以接受可为空类型作为参数:
public ActionResult RemoveRequested(int? id)
请注意,我还会使用 HttpPost
来删除,而不是像您当前所做的那样使用 HttpGet
。
关于c# - 删除 MVC 5 列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31983701/