更新实体时序列不包含任何元素

时间:2019-03-31 13:19:23

标签: c# asp.net-mvc

我想更新我的产品实体,但是每当提交表单时,它都会抛出:

  

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

1 个答案:

答案 0 :(得分:2)

您的表单不包含您要修改的实体的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">  
    ...