我想更新我的产品实体,但是每当我提交表单时,它都会抛出:
System.InvalidOperationException:'序列不包含任何元素'
这是我的看法:
@model myadminpanel.Models.product
@using (Html.BeginForm())
{
<div class="container">
<div class="form-group">
<label>ProductName</label>
@Html.TextBoxFor(x => x.ProductName, new { @class = "form-control" });
</div>
<div class="form-group">
<label>ProductDescription</label>
@Html.TextBoxFor(x => x.ProductDescription, new { @class = "form-control" });
</div>
<div class="form-group">
<label>Price</label>
@Html.TextBoxFor(x => x.Price, new { @class = "form-control" });
</div>
<div class="form-group">
<label>Quantity</label>
@Html.TextBoxFor(x => x.Quantity, new { @class = "form-control" });
<div class="button">
<button>Submit</button>
</div>
</div>
}
我的控制器的编辑代码是这样的:
public ActionResult ProductEdit(int id)
{
var item = db.products.Where(x => x.ProductID == id).First();
return View(item);
}
[HttpPost]
public ActionResult ProductEdit(product model)
{
var item = db.products.Where(x => x.ProductID == model.ProductID).First();
item.ProductName= model.ProductName;
item.ProductDescription = model.ProductDescription;
item.Price = model.Price;
item.Quantity = model.Quantity;
db.SaveChanges();
return View();
}
这是我的产品模型:
namespace myadminpanel.Models
{
using System;
using System.Collections.Generic;
public partial class product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<decimal> Price { get; set; }
public Nullable<int> Quantity { get; set; }
public string CategoryName { get; set; }
public Nullable<int> CategoryID { get; set; }
public virtual category category { get; set; }
}
}
最佳答案
您的表单不包含您要修改的实体的ID,因此
var item = db.products.Where(x => x.ProductID == id).First();
运行为
var item = db.products.Where(x => x.ProductID == 0).First();
并且没有任何ID = 0的产品,因此
First
找不到第一个匹配项(因为没有任何匹配项)。因此,将ID添加为隐藏字段:
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ProductID)
<div class="container">
...
关于c# - 更新实体时序列不包含任何元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55441299/