我有两张桌子Product
& Orders
,我做的是,我创建了View
和硬编码HTML表单,将Ordered Products
传递给Order
对象。
保存Orders
时收到错误INSERT statement conflicted with the FOREIGN KEY constraint
我也添加了断点,所有值都在Orders对象中正确填充,但是Id
& Products
属性为null。
这是我的观点
@model Myapp.Areas.Admin.ViewModel.ProductDisplayViewModel
@ViewBag.Message
@using (Html.BeginForm("OrderProduct", "Order"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-group">
<label>Your Name</label>
<input id="Name" name="Name" class="form-control" type="text"/>
</div>
<div class="form-group">
<label>Your Email</label>
@Html.TextBox("Email", null, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Your Contact Number</label>
@Html.TextBox("ContactNumber", null, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Your Address</label>
@Html.TextBox("Address", null, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Quantity</label>
@Html.TextBox("Quantity", null, new { @class = "form-control",type="Number" })
</div>
<div class="form-group">
<label>Any Comments</label>
@Html.TextBox("Comments", null, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.Hidden("ProductId", Model.ProductId)
</div>
<div class="form-group">
<input id="Submit1" type="submit" value="Order Now" class="read-more"/>
<a href="@Url.Action("Index")" class="read-more">Back to Products</a>
</div>
}
这是我在订单控制器中的操作方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult OrderProduct(Orders order)
{
if (ModelState.IsValid)
{
db.Orders.Add(order);
db.SaveChanges();
// if Order Saved in DB show success Message and Redirect on the same product page
ViewBag.Message = "Value Entered in DB";
return RedirectToAction("Details", "Product", new { id = order.ProductId });
}
// if something went wrong Redirect on the same product page
return RedirectToAction("Details", "Product", new { id = order.ProductId });
}
答案 0 :(得分:1)
ProductId应该是产品表中的ID,按照您的定义进行,但您传递的Model.ProductId会导致您的问题。
使用您添加订单的产品中的Product.Id填充您返回的模型的ProductId字段。
{{1}}