【发布时间】:2021-10-22 14:29:17
【问题描述】:
我正在构建一个产品订购 Web 应用程序,我使用 Entity Framework 到 Scaffold-DbContext 将 DB 中的表搭建到模型类中。我在数据库中有一个名为 Inventory 的表,现在在 .Net Core 项目中创建了该视图,该视图显示了数据库中的库存列表,如下所示
我正在尝试在数据库中不需要的模型类中添加一个名为 QuantityRequired 的新字段。在视图中,我试图将其设为输入字段,以便用户可以输入所需的物品数量,然后单击立即购买,将物品添加到购物车中
public partial class Inventory
{
public string StrainId { get; set; }
public string StrainName { get; set; }
public string StrainCode { get; set; }
public string Age { get; set; }
public string Sex { get; set; }
public string Genotype { get; set; }
public int QuantityAvailable { get; set; }
public string RoomNumber { get; set; }
public int InventoryId { get; set; }
[NotMapped]
public int QuantityRequired { get; set; }
}
阅读后我发现[NotMapped] 属性对此有所帮助,因此像上面一样更新了模型类,视图现在就像
<td >
<input id="Text3" type="text" asp-for="@item.QuantityReq" />
</td>
<td>
<a asp-controller="cart" asp-action="buy" asp-route-customerID="@custID.CustomerId" asp-route-invetoryID="@item.InventoryId">Buy Now</a>
</td>
现在它显示了表格中的新字段
我没有在库存页面的控制器上做任何事情。我应该在控制器中绑定这个值吗?因为当单击立即购买按钮时,我在 CartController 上有以下代码
public IActionResult Index()
{
var cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
ViewBag.cart = cart;
return View();
}
[Route("buy/{customerID}/{invetoryID}")]
public async Task<IActionResult> Buy(int? customerID, int? inventoryID)
{
if (customerID == null || inventoryID == null)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart") == null)
{
List<Item> cart = new List<Item>();
cart.Add(new Item
{
Custom = custData,
Inventory = intData,
**Quantity = intData.QuantityReq**
});
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
return RedirectToAction("Index");
}
}
我尝试从 Quantity = intData.QuantityReq 检索 QuantityReq,但它显示“0”而不是用户输入的值
购物车视图页面就像
@foreach (var item in ViewBag.cart)
{
<tr>
<td>@item.Inventory.StrainId</td>
<td>@item.Inventory.StrainName</td>
<td>@item.Inventory.StrainCode</td>
<td>@item.Inventory.Age</td>
<td>@item.Inventory.Sex</td>
<td>@item.Quantity</td>
</tr>
}
如何将用户输入的值从库存页面传递到购物车页面
【问题讨论】:
-
你可以尝试保存在 session 或 viewbag 上
标签: asp.net entity-framework asp.net-core entity-framework-core asp.net-core-mvc