gpt4 book ai didi

c# - 在 ASP.Net MVC 中使用硬编码形式将数据插入对象中

转载 作者:行者123 更新时间:2023-11-29 11:56:50 24 4
gpt4 key购买 nike

我有两张 table Product & Orders ,我所做的是,我创建了View和 硬编码 HTML 表单,通过 Ordered Products进入Order目的。同时保存Orders我收到错误 INSERT statement conflicted with the FOREIGN KEY constraint我也添加了断点,所有值都已正确填充到 Orders 对象中,但是 Id & Products属性为空。

我创建了一个一对多关系,如下图所示。 Relationship one to many between orders and 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com