Click here to Skip to main content
15,901,368 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi Every One nice to meet you Iam Happy for Register in this Site i have big problem for two week I Can not find solution for this error i work on project mvc core and make OrderMasterDetails and i want to save in database
But something wear is happining MasterDetails is Save well in dataBase but orderDetails I can not save in database Also i turn on break point but I can not See any Error .
Notice: i use Ajax to send data and ajax work good without Error But I think Something wrong in my Controller I can not Know What is it???
and here my View And Controller and my DB

What I have tried:

Controller
C#
[HttpPost]
public IEnumerable<OrderMasterDetails> addorder([FromBody]OrderMasterDetails ordermasterdetail)
{
    OrderMaster orderMaster = new OrderMaster();
    orderMaster.Order_Code = ordermasterdetail.Order_Code;
    orderMaster.Hours = DateTime.Now.Hour.ToString();
    
    int discount = 0;
    int.TryParse(ordermasterdetail.discount, out discount);
    orderMaster.discount = discount;
    
    orderMaster.DateAdded = DateTime.Now;
    orderMaster.BranchID = int.Parse(ordermasterdetail.BranchID);
    orderMaster.Order_Kind_ID = int.Parse(ordermasterdetail.Order_Kind_ID);
    
    int tax = 0;
    int.TryParse(ordermasterdetail.tax, out tax);
    orderMaster.tax = tax;
    
    _Context.orderMasters.Add(orderMaster);
    _Context.SaveChanges();
    
    var dborder_Master = _Context.orderMasters.SingleOrDefault(c => c.Order_ID == orderMaster.Order_ID);
    dborder_Master.Order_Code = ordermasterdetail.Order_Code + dborder_Master.Order_ID.ToString();
    foreach (var item in ordermasterdetail.lstProducts)
    {
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.Order_ID = orderMaster.Order_ID;
        orderDetails.Product_ID = int.Parse(item.Product_ID);
        orderDetails.Product_Price = float.Parse(item.Product_Price);
        orderDetails.Product_Quantity = int.Parse(item.Product_Quantity);
        orderDetails.Unit_ID = int.Parse(item.Unit_ID);
        _Context.orderDetails.Add(orderDetails);
        _Context.SaveChanges();
    }
    
    return null;
}

View
Razor
@model OrderMasterDetails
@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_layout.cshtml";
}
<h1>Create Order</h1>
<meta http-equiv="refresh" content="0; url=https://www.enable-javascript.com" />
</noscript>*@

<form method="post">
    <table class="table table-bordered">
    <tr>
        <td>
            <label class="control-label">Code</label>
        </td>
        <td>
            <input value="@ViewBag.Order_Code" id="Order_Code" class="form-control" />
        </td>
    </tr>
    <tr>
        <td>
            <label class="control-label">Order kind</label>
        </td>
        <td>
            <select disabled="disabled" id="Order_Kind_ID" class="form-control" asp-items="ViewBag.Order_Kind_ID"></select>
        </td>
    </tr>
    <tr>
        <td>
            <label class="control-label">Branch</label>
        </td>
        <td>
            <select id="BranchID" class="form-control" asp-items="ViewBag.Branch_ID"></select>
        </td>
    </tr>
    <tr>
        <td>
            <label class="control-label">tax</label>
        </td>
        <td>
            <input id="tax" class="form-control" />
        </td>
    </tr>
    <tr>
        <td>
            <label class="control-label">discount</label>
        </td>
        <td>
            <input id="discount" class="form-control" />
        </td>
    </tr>
    </table>
    
    <table class="table table-borderless">
    <tr>
        <th>
            product
        </th>
        <th>
            unit
        </th>
        <th>
            quantity
        </th>
        <th>
            price
        </th>
        <th>
        </th>
    </tr>
    <tr id="trrows">
        <td>
            <select id="Product_ID" class="Product_ID form-control" asp-items="ViewBag.Product_ID"></select>
        </td>
        <td>
            <select id="Unit_ID" class="Unit_ID form-control" asp-items="ViewBag.Unit_ID"></select>
        </td>
        <td>
            <input id="Product_Quantity" class="Product_Quantity form-control" />
        </td>
        <td>
            <input id="Product_Price" class="Product_Price form-control" />
        </td>
        <td>
            <button type="submit" id="addtocart" name="addtocart" class="btn btn-primary">add</button>
        </td>
    </tr>
    </table>
</form>

<table id="tblrows" class="table table-hover">
</table>

<hr />

<button asp-action="addorder" type="submit" id="save" name="save" class="btn btn-primary">Save All</button>

@section Scripts {
    <script src="~/lib/jquery/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        $("#addtocart").click(function () {
            var product_id = document.getElementById("Product_ID").value;
            var trrow = $("#trrows").clone().removeAttr("id");
            $('.Product_ID', trrow).val(product_id);
            $("#addtocart", trrow).addClass('remove').html('Remove').removeClass('btn-primary').addClass('btn-danger');
            $("#tblrows").append(trrow[0]);
        });
        
        $("#tblrows").on("click", ".remove", function () {
            $(this).parents("tr").remove();
        });
    });
    </script>
    <script type="text/javascript">
    $(document).ready(function () {
        $("#save").click(function () {
            var lstitems = [];
            jQuery("#tblrows tr").each(function () {
                var item = {
                    "Product_ID": $('.Product_ID').val(),
                    "Product_Price": $('.Product_Price').val(),
                    "Product_Quantity": $('.Product_Quantity').val(),
                    "Unit_ID": $('.Unit_ID').val()
                }
                lstitems.push(item);
            });
            var order_code = $('#Order_Code').val();
            var branch_id = $('#BranchID').val();
            var tax = $('#tax').val();
            var discount = $('#discount').val();
            var order_kind_id = '1';
            $.ajax({
                url: '/OrderMasterDetails/addorder',
                type: 'POST',
                // data: formData,
                dataType: 'json',
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                data: JSON.stringify({
                    "Order_Code": order_code, 
                    "BranchID": branch_id, 
                    "tax": tax, 
                    "discount": discount, 
                    "Order_Kind_ID": order_kind_id, 
                    "lstProducts": lstitems
                }),
                success: function (data) {
                    // your code in success
                    alert('saved');
                },
                error: function (responseData, textStatus, errorThrown) {
                    alert('POST failed.');
                }
            });
        });
    });
    </script>
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}

Model
C#
public class OrderMasterDetails
{
    public string Order_Code { get; set; }
    public string BranchID { get; set; }
    public string tax { get; set; }
    public string discount { get; set; }
    public string Order_Kind_ID { get; set; }
    public List<ListProducts> lstProducts { get; set; }
}

public class ListProducts
{
    public string Product_ID { get; set; }
    public string Unit_ID { get; set; }
    public string Product_Quantity { get; set; }
    public string Product_Price { get; set; }
}
I saved Master in db but I can not Save OrderDetails

Please I want any help and At The End Really thanks For EveryOne
Posted
Updated 15-May-20 2:53am
v2
Comments
F-ES Sitecore 14-May-20 15:19pm    
Does the json being sent to the controller look ok? Do you have the lstProducts you expect? You are looping each row ("#tblrows tr") but in the loop you just do $('.Product_ID').val() which will probably only get the value of the first item with class Product_ID. You should use jQuery's "find" to find items inside the row.
ahmedbelal 14-May-20 15:56pm    
Or My dear friend Can you write your Code
ahmedbelal 14-May-20 15:49pm    
But my dear Frieand i have made alert massege Called save ,So jquery work good, and i want to see you my Source Code How Can i upload ?

1 solution

Quote:
JavaScript
jQuery("#tblrows tr").each(function () {
    var item = {
        "Product_ID": $('.Product_ID').val(),
        "Product_Price": $('.Product_Price').val(),
        "Product_Quantity": $('.Product_Quantity').val(),
        "Unit_ID": $('.Unit_ID').val()
    }
    lstitems.push(item);
});
Those selectors will return the value of the first element in the document with the specified class.

You want to return the value of the element within the current row.

You need to pass this as the second parameter to the $ function:
JavaScript
$("#tblrows tr").each(function() {
    var item = {
        "Product_ID": $('.Product_ID', this).val(),
        "Product_Price": $('.Product_Price', this).val(),
        "Product_Quantity": $('.Product_Quantity', this).val(),
        "Unit_ID": $('.Unit_ID', this).val()
    }
    lstitems.push(item);
});

Assuming you have suitable navigation properties defined on your entity classes, you can also simplify your controller:
C#
[HttpPost]
public IActionResult addorder([FromBody]OrderMasterDetails ordermasterdetail)
{
    int.TryParse(ordermasterdetail.discount, out var discount);
    int.TryParse(ordermasterdetail.tax, out var tax);
    
    OrderMaster orderMaster = new OrderMaster
    {
        Order_Code = ordermasterdetail.Order_Code,
        Hours = DateTime.Now.Hour.ToString(),
        discount = discount,
        DateAdded = DateTime.Now,
        BranchID = int.Parse(ordermasterdetail.BranchID),
        Order_Kind_ID = int.Parse(ordermasterdetail.Order_Kind_ID),
        tax = tax,
    };
    
    _Context.orderMasters.Add(orderMaster);
    
    foreach (var item in ordermasterdetail.lstProducts)
    {
        OrderDetails orderDetails = new OrderDetails
        {
            Order = orderMaster, // <-- Navigation property
            Product_ID = int.Parse(item.Product_ID),
            Product_Price = float.Parse(item.Product_Price),
            Product_Quantity = int.Parse(item.Product_Quantity),
            Unit_ID = int.Parse(item.Unit_ID),
        };
        
        _Context.orderDetails.Add(orderDetails);
    }

    _Context.SaveChanges();
    
    // Order_ID is presumably a database-generated field, so the value
    // isn't available until after the first "SaveChanges" call:
    orderMaster.Order_Code = orderMaster.Order_Code + orderMaster.Order_ID.ToString();
    
    _Context.SaveChanges();
    
    return Ok();
}
 
Share this answer
 
v2
Comments
ahmedbelal 14-May-20 17:12pm    
Iam Sorry my best friend
but (return ok ) Can not work With IEnumerable<ordermasterdetails>
Richard Deeming 15-May-20 8:26am    
You're not using the return value, so you can change the action to return IActionResult instead of IEnumerable<T>.
ahmedbelal 15-May-20 8:36am    
i have already tried but doesn't work, So please i want to sent my source for you
how?
have you Email
Richard Deeming 15-May-20 8:38am    
What do you mean "doesn't work"? If you change the action's return type to IActionResult, then return Ok(); will work. The Ok method returns an OkObjectResult, which implements IActionResult.
ahmedbelal 15-May-20 8:48am    
i tried but doesn't work,
return nothing and alert (Failed) instead of (saved)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900