IEnumerable View在Controller中具有null值

时间:2016-09-19 17:59:18

标签: c# asp.net-mvc entity-framework

我有类型IEnumerable<MVC.Models.Product>的强类型视图。当我遍历控制器中的IEnumerable时,我收到空值。

查看

    @model IEnumerable<MVC.Models.Product>
   <h2>Product</h2>
    @foreach (var item in Model)
    {

      using (Html.BeginForm("AddToCart", "Home"))
        {
               @Html.DisplayFor(modelItem => item.ProductID)
            <div>
                @Html.DisplayFor(modelItem => item.ProductName)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.ProductVendor)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.ProductDesc)
            </div>
            <div>
                @Html.DisplayFor(modelItem => item.productPrice)
            </div>
            <div>
                @Html.TextBox("Quant")
            </div>
            <div>
                <button type="submit" value="Add to cart">Add to cart</button>
            </div>
        }

    }

控制器

     public ActionResult Index(int? page)
    {
        using (AutoPartsSystemEntities3 db = new Models.AutoPartsSystemEntities3())
        {
            var Query = db.Products;
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            return View(Query.OrderBy(e => e.ProductName).ToPagedList(pageNumber,pageSize));
        }

    }

    public ActionResult Product(int id)
    {
        using (AutoPartsSystemEntities3 db = new AutoPartsSystemEntities3())
        {
            var Query = (from p in db.Products
                        where p.ProductID == id
                        select p).ToList();

            return View(Query);
        }
    }
    [HttpPost]
    public ActionResult AddToCart(IEnumerable<Product> p, int Quant)
    {
        double TotalPrice = 0;
        int ProductID = 0;
        foreach (Product pro in p)
        {
            TotalPrice = pro.productPrice * Quant;
            ProductID = pro.ProductID;
        }
        using (AutoPartsSystemEntities8 db = new AutoPartsSystemEntities8())
        {
            db.Carts.Add(new Cart { ProductId = ProductID, CheckOut = false, DateCreated = DateTime.Now, Price = (float)TotalPrice, Quantity = Quant, UserId = 1 });
            db.SaveChanges();

        }
        return RedirectToAction("Index", "Home");
    }

产品类

public partial class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductVendor { get; set; }
    public string ProductDesc { get; set; }
    public double productPrice { get; set; }
}

1 个答案:

答案 0 :(得分:0)

每个表单都发回一个MVC.Models.Product,而不是Collection(IEnumerable)。尝试:

[HttpPost]
public ActionResult AddToCart(Product p, int Quant)

并修改控制器以反映您一次只保存一件产品的事实。

并添加:

@Html.HiddenFor(modelItem => item.ProductID) 

在displayFor下面,所以它回发了。