繁体   English   中英

在ASP.Net MVC中以硬编码形式在对象中插入数据

[英]Inserting Data in Object with Hard Coded Form in ASP.Net MVC

我有两个表ProductOrders ,我所做的是,创建了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对象中,但IdProducts属性为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM