Click here to Skip to main content
15,896,430 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,

Thanks in advance,

I have a JQuery Ajax function which suppose to save data in Database. Unfortunately it gives an error which I could not find out yet. please go through my all codes and tell me where I did the mistake. 

in the MasterIndex.cshtml page I am simply passing int data directly (to CustomerId and UserId) because I do not know how to get id value of selected dropdown text which linked to other table. So after solving error I would like to know how to get ID value also.

here is that code;


if (isAllValid) {
                var data = {
                    AccntInvoiceNo: $('#AccountInvNo').val().trim(),
                    SaleDate: $('#SaleDate').val().trim(),
                    SubTotal: $('#SubTotal').val().trim(),
                    Discount: $('#Discount').val().trim(),
                    NetAmount: $('#NetTotal').val().trim(),
                    CustomerId: 2,
                    UserId: 1,
                    SaleDescs: orderItems
                }



here are other main codes

Sale.cs

C#
public partial class Sale
    {
        public Sale()
        {
            this.Payments = new HashSet<Payment>();
            this.SaleDescs = new HashSet<SaleDesc>();
        }
    
        public int Id { get; set; }

        [Required,Display(Name = "Accounts Invoice No.")]
        public string AccntInvoiceNo { get; set; }

        [Required,Display(Name = "Date of Sale"), DataType(DataType.Date)]
        public System.DateTime SaleDate { get; set; }

        [Display(Name = "Sub Total")]
        public Nullable<decimal> SubTotal { get; set; }

        public Nullable<decimal> Discount { get; set; }

        [Required,Display(Name = "Net Amount")]
        public decimal NetAmount { get; set; }

        [Display(Name = "Customer Name")]
        public int CustomerId { get; set; }

        [Display(Name = "User")]
        public int UserId { get; set; }
    
        public virtual ICollection<Payment> Payments { get; set; }
        public virtual Person Person { get; set; }
        public virtual User User { get; set; }
        public virtual ICollection<SaleDesc> SaleDescs { get; set; }
    }
}



SaleDesc.cs
C#
public partial class SaleDesc
    {
        public int Id { get; set; }

        [Display(Name = "No")]
        public int SaleId { get; set; }

        [Required,Display(Name = "Name of Product")]
        public int ProductId { get; set; }

        public string Size { get; set; }

        [Required]
        public string Quantity { get; set; }

        [Required,Display(Name = "Unit Price")]
        public Nullable<decimal> UnitPrice { get; set; }

        [Required,Display(Name = "Net Amount")]
        public decimal NetAmount { get; set; }
    
        public virtual Product Product { get; set; }
        public virtual Sale Sale { get; set; }
    }


SaleController.cs
C#
public class SaleController : Controller
    {
        private TIASHJDBContext db = new TIASHJDBContext();

        public ActionResult MasterIndex()
        {
            ViewBag.CustomerId = new SelectList(db.Persons, "Id", "FullName");
            ViewBag.ProductId = new SelectList(db.Products, "Id", "PName");
            return View();
        }

        //Post action for Save data to database
        [HttpPost]
        public JsonResult SaveOrder(Sale s)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                
                    Sale sale = new Sale { AccntInvoiceNo = s.AccntInvoiceNo, SaleDate = s.SaleDate, SubTotal = s.SubTotal, Discount = s.Discount, NetAmount = s.NetAmount, CustomerId = s.CustomerId, UserId = s.UserId };
                    foreach (var i in s.SaleDescs)
                    {
                        //
                        // i.TotalAmount = 
                        sale.SaleDescs.Add(i);
                    }
                    db.Sales.Add(sale);
                    db.SaveChanges();
                    status = true;

                
            }
            else
            {
                status = false;
            }
            return new JsonResult { Data = new { status = status } };
        }
}


MasterIndex.cshtml
@{
    ViewBag.Title = "MasterIndex";
}

<h2>Sales Order</h2>

<div class="container">
    <div class="master">
        <h4>Sale details</h4>
        <div class="panel-group">
            <div class="panel panel-default">
                <div class="table">
                    <table class="table">
                        <tr>
                            <td>Account Invoice No</td>
                            <td>
                                <input type="text" id="AccountInvNo" />
                                <span class="error">Account Invoice No is required</span>
                            </td>
                            <td>Sale Date</td>
                            <td>
                                <input type="text" id="SaleDate" />
                                <span class="error">Valid sale date is required (ex. MM-dd-yyyy)</span>
                            </td>
                            <td>Customer Name</td>
                            <td>
                                @*<input type="text" id="Customer" />*@
                               
                                @Html.DropDownList("CustomerID", null,String.Empty, new { id = "Customer", @class = "text-field" })
                                
                                <span class="error">Valid customer name is required</span>
                            </td>
                        </tr>
                        <tr>
                            <td>Sub Total</td>
                            <td>
                                <input type="text" id="SubTotal" readonly="readonly" />
                            </td>
                            <td>Discount</td>
                            <td>
                                <input type="text" id="Discount" />
                            </td>
                            <td>Net Total</td>
                            <td>
                                <input type="text" id="NetTotal" readonly="readonly" />
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
        <div class="details">
            <h4>Sale Item Details</h4>
            <table class="table table-striped table-hover table-condensed">
                <tr>
                    <td>Item Name</td>
                    <td>Quantity</td>
                    <td>Unit Price</td>
                    <td> </td>
                </tr>
                <tr>
                    <td>
                       @* <input type="text" id="itemName" />*@
                        @Html.DropDownList("ProductID", null, String.Empty, new { id = "itemName", @class = "text-field" })
                        <span class="error">Item name is required</span>
                    </td>
                    <td>
                        <input type="text" id="quantity" />
                        <span class="error">Valid quantity is required</span>
                    </td>
                    <td>
                        <input type="text" id="UnitPrice" />
                        <span class="error">Valid Unit Price is required</span>
                    </td>
                    <td>
                        <input type="button" class="btn btn-primary" id="add" value="Add" style="padding:10px 30px" />
                    </td>
                </tr>
            </table>
            <div id="orderItems" class="tablecontainer">

            </div>
            <div style="padding:10px 0px; text-align:right">
                <input id="submit" type="button" value="Save" class="btn btn-success" style="padding:10px 40px" />
            </div>
        </div>
    </div>
</div>

        @*JQuery code*@

        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
        @section Scripts{
            <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
            <script>
    //Date Picker
    $(function () {
        $('#SaleDate').datepicker({
            dateFormat: 'mm-dd-yy'
        });
    });
    var subTot = 0;
    $('#Discount').val(0);
    $(document).ready(function () {
        var orderItems = [];
        //Add button click function
        $('#add').click(function () {
            //Check validation of order item
            var isValidItem = true;
            if ($('#itemName').val().trim() == '') {
                isValidItem = false;
                $('#itemName').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#itemName').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
                isValidItem = false;
                $('#quantity').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#quantity').siblings('span.error').css('visibility', 'hidden');
            }

            if (!($('#UnitPrice').val().trim() != '' && !isNaN($('#UnitPrice').val().trim()))) {
                isValidItem = false;
                $('#UnitPrice').siblings('span.error').css('visibility', 'visible');
            }
            else {
                $('#UnitPrice').siblings('span.error').css('visibility', 'hidden');
            }



            //Add item to list if valid
            if (isValidItem) {
                orderItems.push({
                    ItemName: $('#itemName').val().trim(),
                    Quantity: parseInt($('#quantity').val().trim()),
                    UnitPrice: parseFloat($('#UnitPrice').val().trim()),
                    SubTotal: parseInt($('#quantity').val().trim()) * parseFloat($('#UnitPrice').val().trim())
                });


                subTot = subTot + (parseInt($('#quantity').val().trim()) * parseFloat($('#UnitPrice').val().trim()))


                //Clear fields
                $('#itemName').val('').focus();
                $('#quantity,#UnitPrice').val('');


            }
            //populate order items
            GeneratedItemsTable();

            $('#SubTotal').val(parseFloat(subTot));
            $('#NetTotal').val(parseFloat(subTot) - parseFloat($('#Discount').val().trim()));


        });
        //Save button click function
        $('#submit').click(function () {
            //validation of order
            var isAllValid = true;
            if (orderItems.length == 0) {
                $('#orderItems').html('<span style="color:red;">Please add order items</span>');
                isAllValid = false;
            }

            if ($('#AccountInvNo').val().trim() == '') {
                $('#AccountInvNo').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#AccountInvNo').siblings('span.error').css('visibility', 'hidden');
            }

            if ($('#SaleDate').val().trim() == '') {
                $('#SaleDate').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#SaleDate').siblings('span.error').css('visibility', 'hidden');
            }

            if ($('#Customer').val().trim() == '') {
                $('#Customer').siblings('span.error').css('visibility', 'visible');
                isAllValid = false;
            }
            else {
                $('#Customer').siblings('span.error').css('visibility', 'hidden');
            }

            //Save if valid
            if (isAllValid) {
                var data = {
                    AccntInvoiceNo: $('#AccountInvNo').val().trim(),
                    SaleDate: $('#SaleDate').val().trim(),
                    SubTotal: $('#SubTotal').val().trim(),
                    Discount: $('#Discount').val().trim(),
                    NetAmount: $('#NetTotal').val().trim(),
                    CustomerId: 2,
                    UserId: 1,
                    SaleDescs: orderItems
                }

                $(this).val('Please wait...');

                $.ajax({
                    url: '/Sale/SaveOrder',
                    type: "POST",
                    data: JSON.stringify(data),
                    dataType: "JSON",
                    contentType: "application/json",
                    success: function (d) {
                        //check is successfully save to database
                        if (d.status == true) {
                            //will send status from server side
                            alert('Successfully done.');
                            //clear form
                            orderItems = [];
                            $('#AccountInvNo').val('');
                            $('#saleDate').val('');
                            $('#orderItems').empty();
                        }
                        else {
                            alert('Failed');
                        }
                        $('#submit').val('Save');
                    },
                    error: function (exception) {
                        alert('Exeption:'+exception);
                        $('#submit').val('Save');
                    }
                });
            }

        });
        //function for show added items in table
        function GeneratedItemsTable() {
            if (orderItems.length > 0) {
                var $table = $('<table/>');
                $table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Unit Price</th><th>Total</th></tr></thead>');
                var $tbody = $('<tbody/>');
                $.each(orderItems, function (i, val) {
                    var $row = $('<tr/>');
                    $row.append($('<td/>').html(val.ItemName));
                    $row.append($('<td/>').html(val.Quantity));
                    $row.append($('<td/>').html(val.UnitPrice));
                    $row.append($('<td/>').html(val.SubTotal));
                    $tbody.append($row);
                });
                $table.append($tbody);
                $('#orderItems').html($table);
            }
        }
    });

</script>

        }

        <style>
            /*Adding some css for looks good*/
            span.error {
                display: block;
                visibility: hidden;
                color: red;
                font-size: 90%;
            }


            /*css for table*/
            .container td {
                vertical-align: top;
            }

            .tablecontainer table {
                width: 100%;
                border-collapse: collapse;
                border-top: 1px solid #BFAEAE;
                border-right: 1px solid #BFAEAE;
            }

            .tablecontainer th {
                border-bottom: 2px solid #BFAEAE !important;
            }

            .tablecontainer th, .tablecontainer td {
                text-align: left;
                border-left: 1px solid #BFAEAE;
                padding: 5px;
                border-bottom: 1px solid #BFAEAE;
            }

            .ui-widget {
                font-size: 12px !important;
            }
        </style>


What I have tried:

I tried to debug ajax function on crome, but could not understand.
error was "[object Object]"
Posted
Comments
F-ES Sitecore 16-Feb-16 4:47am    
Dumping hundreds of lines of code with a vague "it doesn't work" description doesn't make things easy. I'd start by isolating the problem and trying to do an ajax call to your method with hard-coded params and try and get that working, then try and get it working from your data. Use the browser's dev tools to help you debug issues;

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+
Member 11883599 16-Feb-16 5:50am    
Im really sorry about those codes, I just wanted to give a clear picture.
BTW, I could find the solution, I was sending string for ProductId instead of int.

but I have new problem now, I don't know how to get id value of selected dropdown list value which linked to other table.
eg: Selected customer name is "Kasun" and i want to get its ID value from person table and assign to CustomerId of Sale table.
please hlep with that also.
[no name] 16-Feb-16 4:54am    
Follow below steps:

1. Put a debugger point in your action and see what value you are getting sale object.
2. Once it hits your method then check what value you are getting in db.SaveChanges() because it always returns no of rows affected.
Member 11883599 16-Feb-16 5:51am    
I followed your steps and found the mistake. thanks a lot.
problem was, I was sending string for ProductId instead of int.

but I have new problem now, I don't know how to get id value of selected dropdown list value which linked to other table.
eg: Selected customer name is "Kasun" and i want to get its ID value from person table and assign to CustomerId of Sale table.
please hlep with that also.

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