[英]Inserting Data in Object with Hard Coded Form in ASP.Net MVC
我有兩個表Product
& Orders
,我所做的是,創建了View
和Hard Coded HTML表單,該表單將Ordered Products
傳遞到Order
Object。 保存Orders
我收到INSERT statement conflicted with the FOREIGN KEY constraint
錯誤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 });
}
ProductId應該是產品表中的ID,按照您的定義,但是您傳遞的是Model.ProductId,這會導致問題。
使用您要為其添加訂單的產品中的Product.Id填充要返回的模型的ProductId字段。
newOrderObject.ProductId = Product.Id
return View(newOrderObject);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.