我有两张 table Product
& Orders
,我所做的是,我创建了View
和 硬编码 HTML 表单,通过 Ordered Products
进入Order
目的。
同时保存Orders
我收到错误 INSERT statement conflicted with the FOREIGN KEY constraint
我也添加了断点,所有值都已正确填充到 Orders 对象中,但是 Id
& Products
属性为空。
这是我的观点
@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>
}
这是我在订单 Controller 中的操作方法
[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 });
}
最佳答案
ProductId 应该是产品表中的 Id,根据您的定义,但您传递的 Model.ProductId 会导致您的问题。
使用您为其添加订单的产品中的 Product.Id 填充您要返回的模型的 ProductId 字段。
newOrderObject.ProductId = Product.Id
return View(newOrderObject);
关于c# - 在 ASP.Net MVC 中使用硬编码形式将数据插入对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059234/