IEnumerable视图在控制器中有空值
本文关键字:空值 控制器 视图 IEnumerable | 更新日期: 2023-09-27 18:07:34
我有一个类型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; }
}
每个表单都返回一个MVC.Models。产品,而不是集合(IEnumerable)。试一试:
[HttpPost]
public ActionResult AddToCart(Product p, int Quant)
并修改控制器以反映您一次只保存一个产品的事实。
并添加:
@Html.HiddenFor(modelItem => item.ProductID)
在displayFor下,所以它会返回