首页 > 解决方案 > 使用 Javascript Entity Framework C# MVC Json 添加记录时出错

问题描述

我在添加数据中保存的记录时遇到问题。

内部例外是这样的:

列名“CustomerNames_CustomerId”无效。列名“CustomerNames_CustomerId”无效。列名“CustomerNames_CustomerId”无效。

我无法弄清楚这一点,因为 CustomerNames 中有一个 CustomerId 列。一切正常(将商品添加到购物车,获取 CustomerId),除非您去保存订单。

那是当我在线路上收到错误时,我休息了。

控制器操作(PartsController)

 public ActionResult PartsDetail(int id, string mReq)
    {
        Session["CustomerId"] = id;

        if (mReq == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        SubJobDetails modelInstance = SubJobDetails.GetSubjobsAndParts(mReq, db);
        //if (modelInstance == null)
        //{
        //    return HttpNotFound();
        //}
        return View(modelInstance);
    }

    public static List<SubJobDetails> partsList = new List<SubJobDetails>();

    [HttpPost]
    public ActionResult AddToShoppingCart(SubJobDetails parts)
    {
        string message = string.Empty;

        if (parts != null)
        {
            partsList.Add(parts);
            message = "product has been added successfully !";
        }
        else
        {
            message = "something Wrong  !";
        }

        return Json(new { message = message }, JsonRequestBehavior.AllowGet);
    }

    // Displays Shopping Cart
    public ActionResult ShoppingCart()
    {

        List<SubJobDetails> myShoppingCart = partsList;

        return PartialView("~/Views/Customer/ShoppingCart.cshtml", myShoppingCart);
    }

    [HttpPost]
    public ActionResult AddOrder(string[] arrIdPart, int[] arrQtyPart)
    {
        int countPart = arrIdPart.Length;
        int customerId = (int)Session["CustomerId"];
        bool statusTran = false;

        CustomerEntities _context = new CustomerEntities();

        using (DbContextTransaction dbTran = _context.Database.BeginTransaction())
        {
            try
            {
                CustomerNames customer = _context.CustomerNames.Find(customerId);
 **Break incerted here, Error appears ->** if (customer != null)
                {
 **Break Inserted Here, Error appears ->**  customer.Ordered.Add(new Orders { OrderDate = DateTime.Now });
                }

                Orders orderSelected = customer.Ordered.LastOrDefault();

                if (orderSelected != null)
                {
                    for (int i = 0; i < countPart; i++)
                    {
                        Parts selectedPart = _context.Parts.Find(arrIdPart[i]);
                        orderSelected.OrderDetail.Add(new OrderDetails { Part = selectedPart, Quantity = arrQtyPart[i] });
                    }
                }

                //Save Changes
                int countResult = _context.SaveChanges();

                //Commit Transaction
                dbTran.Commit();

                if (countPart > 0)
                {
                    statusTran = true;
                    partsList.Clear();
                }


            }
            catch (Exception)
            {
                dbTran.Rollback();
            }
        }


        return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);
    }

}

模型 - CustomerNames、CustomerViews 和 Orders。

    public class CustomerNames
{
    public CustomerNames()
    {
        Address = new List<Addresses>();
        Ordered = new List<Orders>();
    }

    [Key]
    public int CustomerId { get; set; }
    [Display(Name ="Company Name")]
    public string CustomerName { get; set; }
    public int Status { get; set; }
    public string ExemptionForm { get; set; }
    [UIHint("_IsStatus")]
    public bool ExemptionFormUploaded { get; set; }
    public virtual IEnumerable<Addresses> Address { get; set; }
    public virtual ICollection<Orders> Ordered { get; set; }

}

订单

    public class Orders
{
    public Orders()
    {
        OrderDetail = new List<OrderDetails>();
    }

    [Key]
    public int OrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public string PONumber { get; set; }
    public bool UseCreditCard { get; set; }
    public virtual CustomerNames CustomerNames { get; set; }
    //public virtual Addresses Addresses { get; set; }
    public virtual ICollection<OrderDetails> OrderDetail { get; set; }
}

视图模型

    public partial class SubJobDetails
{
    public static SubJobDetails GetSubjobsAndParts(string mReq, CustomerEntities db)
    {

        var Parts = from pts in db.PartsView
                    join sj in db.SubJobs on pts.SubJob equals sj.SubJob
                    join tlj in db.TopLvlJobs on sj.TopLvlJob equals tlj.TopLvlJob
                    join se in db.SerialNumbers on tlj.TopLvlJob equals se.TopLvlJob
                    where (pts.SubJob == mReq)
                   select new SubJobDetails()
                   {
                       PartsView = pts,
                       TopLvlJob = tlj.TopLvlJob,
                       SubJobs = sj,
                       Material = pts.Material,
                       Description = pts.Description,
                       SellingPrice = pts.SellingPrice,
                       UnitsInStock = pts.UnitsInStock,
                       PartImage = pts.PartImage,
                       CustomerId = se.CustomerId
                   };

        var result = Parts.FirstOrDefault();

        if (result != null)
        {
            result.PartsDetail = db.PartsView.Where(a => a.SubJob == result.PartsView.SubJob);
        };

        return result;
    }

    public int CustomerId { get; set; }
    public string Material { get; set; }
    public string Description { get; set; }
    public decimal SellingPrice { get; set; }
    public int UnitsInStock { get; set; }
    public string PartImage { get; set; }
    public string LeadTime { get; set; }
    public int QtySelected { get; set; }
    public string TopLvlJob { get; set; }
    public virtual TopLvlJobs TopLvlJobs { get; set; }
    public virtual PartsView PartsView { get; set; }
    public virtual SubJobs SubJobs { get; set; }
    public virtual IEnumerable<PartsView> PartsDetail { get; set; }
}

查看

@model BestenEquipment.Models.SubJobDetails
@{
ViewBag.Title = "PartsDetail";
Layout = "~/Views/Shared/CustomerDashboardLayout.cshtml";
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>

<div id="page-wrapper">
<div class="row">
    <div class="col-lg-12">
        <p>
            <br />
            <h4> @Html.DisplayFor(model => model.SubJobs.Description) </h4>
            @Html.ActionLink("Back to Machine Detail", "MachineDetail", null, new { Job = Model.TopLvlJob }, new { @class = "btn btn-default" })
            <div style="float:right;">
                <button type="button" data-toggle="modal" data-target="#exampleModal" class="btn btn-primary" id="myOrder">
                    <span class="glyphicon glyphicon-shopping-cart"></span> My Order
                </button>
            </div>
        </p>
    </div>
    <!-- /.col-lg-12 -->
</div>
<div class="row">
    <div class="col-lg-12">
        <div>
            <hr />
            <dl class="dl-horizontal">
                <dt>
                    @Html.DisplayNameFor(model => model.SubJobs.ExtDescription)
                </dt>

                <dd>
                    @Html.DisplayFor(model => model.SubJobs.ExtDescription)
                </dd>

                <dt>
                    @Html.DisplayNameFor(model => model.SubJobs.PartNumber)
                </dt>

                <dd>
                    @Html.DisplayFor(model => model.SubJobs.PartNumber)
                </dd>

                <dt>
                    @Html.DisplayNameFor(model => model.SubJobs.Drawing)
                </dt>

                <dd>
                    @Html.DisplayFor(model => model.SubJobs.Drawing)
                </dd>
            </dl>
        </div>
    </div>
    <!-- /.col-lg-12 -->
</div>
<div class="row">
    <div class="col-lg-12">
        <div class="container" style="float:left;">
            <div class="well well-sm">
                <strong>Display</strong>
                <div class="btn-group">
                    <a href="#" id="list" class="btn btn-default btn-sm">
                        <span class="glyphicon glyphicon-th-list">
                        </span>List
                    </a> <a href="#" id="grid" class="btn btn-default btn-sm">
                        <span class="glyphicon glyphicon-th"></span>Grid
                    </a>
                </div>
            </div>
            <div id="products" class="row list-group">

                @foreach (var item in Model.PartsDetail)
                {
                    <div class="item col-sm-3 col-lg-3">
                        <div class="thumbnail">
                            @if (item.PartImage != null)
                            {
                                <img class="group list-group-image" src="@Html.DisplayFor(model => item.PartImage)" alt="" />
                            }
                            else
                            {
                                <img class="group list-group-image" src="~/Content/Images/NoImage.png" alt="" />
                            }
                            <div class="caption">
                                <h4 class="group inner list-group-item-heading">
                                    @Html.DisplayFor(model => item.Material), @Html.DisplayFor(model => item.Status)
                                </h4>
                                <p class="group inner list-group-item-text">
                                    @Html.DisplayFor(model => item.Description)
                                </p>
                                <div class="row">
                                    @if (item.InStockQuanex == true)
                                    {

                                        <div class="col-xs-12 col-md-12">
                                            <p class="group inner list-group-item-text" style="color:red; font-size:14px !important; padding:13px">
                                                This item is in stock at Quanex. Please call your CSR to order.
                                            </p>
                                        </div>
                                    }
                                    else
                                    {
                                        <div class="col-xs-12 col-md-6">
                                            Units in stock: @Html.DisplayFor(model => item.UnitsInStock)<br />
                                            Lead Time: @Html.DisplayFor(model => item.LeadTime)<br />
                                            <input id="Qty_@item.Material" class="form-control" onfocus="if (this.value == 'Quantity') { this.value = '1' }" onblur="if (this.value == '') { this.value='Quantity' }" value="Quantity" />

                                        </div>
                                        <div class="col-xs-12 col-md-6">
                                            <p class="lead">
                                                @Html.DisplayFor(model => item.SellingPrice)
                                                @Html.DisplayFor(model => item.UnitOfMeasure)
                                            </p>
                                            <a class="btn btn-success" id="test" role="button"
                                               data-material="@item.Material"
                                               data-partImage="@item.PartImage"
                                               data-description="@item.Description"
                                               data-sellingPrice="@item.SellingPrice">

                                                Add To Cart
                                            </a>
                                        </div>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                }
            </div>
        </div>
    </div>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /#page-wrapper -->
<!-- MODAL -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title" id="exampleModalLabel"> <span class="glyphicon glyphicon-shopping-cart"></span> Order </h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div> <!-- MODEL HEADER-->
        <div class="modal-body">
        </div> <!-- MODAL BODY-->
    </div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
    $('#list').click(function (event) { event.preventDefault(); $('#products .item').addClass('list-group-item'); });
    $('#grid').click(function (event) { event.preventDefault(); $('#products .item').removeClass('list-group-item'); $('#products .item').addClass('grid-group-item'); });


    $('.btn-success').click(function () {

        var selectedPart = {

            Material: $(this).attr('data-material'),
            PartImage: $(this).attr('data-partImage'),
            Description: $(this).attr('data-description'),
            SellingPrice: $(this).attr('data-SellingPrice'),
            QtySelected: $('#Qty_' + $(this).attr('data-material')).val()
        };

        console.log(selectedPart);

        $.ajax({
            type: 'POST',
            url: '@Url.Action("AddToShoppingCart", "Parts")',
            data: selectedPart,
            success: function (response) {
                alert(response.message);
            },
            error: function (response) {
                alert(response.message);
            }

        });

    });

    $("#myOrder").click(function () {

        $(".modal-body").html('');
        $.ajax({

            type: 'GET',
            url: '@Url.Action("ShoppingCart", "Parts")',
            success: function (response) {

                $(".modal-body").html(response);
                $("#exampleModal").modal('show');

            },
            error: function () {
                alert("Something Wrong");
            }

        });
    });
});
</script>

购物车型号

@model IEnumerable<BestenEquipment.Models.SubJobDetails>
@{
decimal totalOrder = 0;
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>

@if (Model != null && Model.Any())
{
    using (Html.BeginForm("AddOrder", "Customer", new { id = "f" }))
    {
                <table id="tableOrder" class="table table-hover">
                    <tr>
                        <th>Part Number</th>
                        <th>Unit Price</th>
                        <th>Qty Selected</th>
                        <th>Description</th>
                        <th>Total Price</th>
                    </tr>
                    @foreach (var parts in Model)
                    {
                        <tr>
                            <td>@parts.Material</td>
                            <td>@string.Format("{0:C2}", parts.SellingPrice)</td>
                            <td>@parts.QtySelected</td>
                            <td>@parts.Description</td>
                            <td>@string.Format("{0:C2}", (parts.SellingPrice * parts.QtySelected))</td>
                        </tr>
                        totalOrder += (parts.QtySelected * parts.SellingPrice);

                        @Html.HiddenFor(p => parts.Material)
                        @Html.HiddenFor(p => parts.QtySelected)

                    }
                </table>
                <!-- TOTAL PRICE-->
                <h4 style="margin-left: 66%;">Total : <span class="label label-info">@string.Format("{0:C2}", totalOrder)</span></h4>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="SaveOrder">Save Order</button>
                </div> <!-- MODAL FOOTER-->
    }
}
else
{
            <div class="alert alert-warning" role="alert">Your basket is empty !</div>
}

<!--JS-->
<script type="text/javascript">

$(document).ready(function () {

    //add class rounded img-thumbnail to img tag
    $('img').addClass('rounded img-thumbnail');

    //Save Order
    $("#SaveOrder").click(function () {

        var $form = $(this).closest('form');
        var dataPart = $form.serializeArray();

        console.log(dataPart);

        var arrIdPart = [];
        var arrQtyPart = [];

        for (i = 0; i < dataPart.length; i++)
        {
            if (dataPart[i].name == 'parts.Material')
            {
                arrIdPart.push(dataPart[i].value);
            }
            else if (dataPart[i].name == 'parts.QtySelected')
            {
                arrQtyPart.push(dataPart[i].value);

            }
        }

        $.ajax({
            type: 'POST',
            url: '@Url.Action("AddOrder", "Parts")',
            data: { arrIdPart, arrQtyPart },
            success: function (response) {
                if(response.data == true)
                {
                    alert("Order has saved successfully ");
                }
                else
                {
                    alert("Something Wrong ! ");
                }

            },
            error: function (error) {
                alert("Something Wrong ! ");
            }
        });
    });

});

</script>

标签: javascriptc#sql-serverasp.net-mvc

解决方案


推荐阅读