Results 1 to 2 of 2

Thread: How to pass data from view to controller by ajax request as Input Parameters to Contr

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Apr 2018
    Posts
    67

    How to pass data from view to controller by ajax request as Input Parameters to Contr

    Problem

    cannot pass data from view to controller by ajax request as input parameters to controller action method

    I have class model name SalesHeader as following

    Code:
    public class SalesHeader
        {
            public int SalesOrderNo { get; set; }
            public int SalesYear { get; set; }
            public int CustomerID { get; set; }
            public Customer Customers { get; set; }
            public ICollection<SalesFooter> SalesFooters { get; set; }
        
        }
    I make controller SalesOrder Based on SalesHeader model

    in salesorder controller i have actionresult Create

    I need to pass data from view of create action result to controller salesorder Create Method As Input parameters
    Code:
     [HttpPost]
            public ActionResult Create(SalesHeader sh, SalesFooter[] orderItems)
            {
            }
    sales header represented bySalesHeader sh as ( SalesOrderNo,SalesYear,CustomerId )
    sales Footer represented by SalesFooter sh as ( SalesLineNo,ItemCode,Quantity,UnitPrice,Total )
    and SalesFooter[] orderItems represent public ICollection<SalesFooter> SalesFooters { get; set; }
    and i will receive items data from view to controller as array of items
    Design of form

    Code:
    on Header(represent by Sales Header Model) 
    SalesOrderNO   1
    SalesYear      2019
    CustomerNo     2509
    on Footer(represent by Sales Footer Model)
    SalesLineNo ItemCode  Quantity  Price Total
    1            12929       5        10   50
    2            17918       4         5   20
    my view as following

    Code:
    @model TabDataAccess.Dto.SalesHeader
    
    @{
        ViewData["Title"] = "Create";
        Layout = "~/Views/Shared/_Layout.cshtml";
    
    }
    <link href="~/css/SalesO.css" rel="stylesheet" />
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script>
        $(document).ready(function () {
            var orderItems = [];
            //Add button click function
            $('#add').click(function () {
                //Check validation of order item
                var isValidItem = true;
                if ($('#SalesLineNo').val().trim() == '') {
                    isValidItem = false;
                    $('#SalesLineNo').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#SalesLineNo').siblings('span.error').css('visibility', 'hidden');
                }
                if ($('#ItemCode').val().trim() == '') {
                    isValidItem = false;
                    $('#ItemCode').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#ItemCode').siblings('span.error').css('visibility', 'hidden');
                }
    
                if (!($('#Qunatity').val().trim() != '' && !isNaN($('#Qunatity').val().trim()))) {
                    isValidItem = false;
                    $('#Qunatity').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#Qunatity').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');
                }
                if (!($('#Total').val().trim() != '' && !isNaN($('#Total').val().trim()))) {
                    isValidItem = false;
                    $('#Total').siblings('span.error').css('visibility', 'visible');
                }
                else {
                    $('#Total').siblings('span.error').css('visibility', 'hidden');
                }
    
                //Add item to list if valid
                if (isValidItem) {
                    orderItems.push({
                        SalesLineNo: $('#SalesLineNo').val().trim(),
                        ItemCode: $('#ItemCode').val().trim(),
                        Quantity: parseInt($('#Qunatity').val().trim()),
                        UnitPrice: parseFloat($('#UnitPrice').val().trim()),
                        Total: parseInt($('#Qunatity').val().trim()) * parseFloat($('#UnitPrice').val().trim())
                    });
    
                    ////Clear fields
                    $('#SalesLineNo').val('').focus();
               
                    $('#ItemCode','#Qunatity,#UnitPrice').val('');
    
                }
                //populate order items
                GeneratedItemsTable();
    
            });
            function GeneratedItemsTable() {
                if (orderItems.length > 0) {
                    var $table = $('<table/>');
                    $table.append('<thead><tr><th>SalesLineNo</th><th>ItemCode</th><th>Qunatity</th><th>UnitPrice</th><th>Total</th><th></th></tr></thead>');
                    var $tbody = $('<tbody/>');
                    $.each(orderItems, function (i, val) {
                        var $row = $('<tr/>');
                        $row.append($('<td/>').html(val.SalesLineNo));
                        $row.append($('<td/>').html(val.ItemCode));
                        $row.append($('<td/>').html(val.Qunatity));
                        $row.append($('<td/>').html(val.UnitPrice));
                        $row.append($('<td/>').html(val.Total));
                        var $remove = $('<a href="#">Remove</a>');
                        $remove.click(function (e) {
                            e.preventDefault();
                            orderItems.splice(i, 1);
                            GeneratedItemsTable();
                        });
                        $row.append($('<td/>').html($remove));
                        $tbody.append($row);
                    });
                    console.log("current", orderItems);
                    $table.append($tbody);
                    $('#orderItems').html($table);
                }
                else {
                    $('#orderItems').html('');
                }
            }
            $("#saveOrder").click(function (e) {
                e.preventDefault();
    
                var orderItems = [];
                orderItems.length = 0;
    
                orderItems.push({
                    SalesLineNo: $('#SalesLineNo').val().trim(),
                    ItemCode: $('#ItemCode').val().trim(),
                    Quantity: parseInt($('#Qunatity').val().trim()),
                    UnitPrice: parseFloat($('#UnitPrice').val().trim()),
                    Total: parseInt($('#Qunatity').val().trim()) * parseFloat($('#UnitPrice').val().trim())
                });
    
    
                var data = JSON.stringify({
                    orderfooter: orderItems
                });
                $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: 'POST',
                    url: '/SalesOrder/Create',
                    data: orderItems,
                    success: function (result) {
                        alert(result);
                        location.reload();
                    },
                    error: function () {
                        alert("Error!")
                    }
                });
            });
        });
       
        
        
    </script>
    <h2>Create</h2>
    
    <h4>SalesHeader</h4>
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Create">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="SalesOrderNo" class="control-label"></label>
                    <input asp-for="SalesOrderNo" class="form-control" />
                    <span asp-validation-for="SalesOrderNo" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="SalesYear" class="control-label"></label>
                    <input asp-for="SalesYear" class="form-control" />
                    <span asp-validation-for="SalesYear" class="text-danger"></span>
                </div>
               
               
               
                <div class="form-group">
                    <label asp-for="CustomerID" class="control-label"></label>
                    @*<select asp-for="CustomerID" class="form-control" asp-items="ViewBag.CustomerID"></select>*@
                    <input asp-for="CustomerID" class="form-control" />
                    <span asp-validation-for="CustomerID" class="text-danger"></span>
                </div>
               
                <div class="details">
                    <h4>Order Items</h4>
                    <table width="100%">
                        <tr>
                            <td>SalesLineNo</td>
                            <td>ItemCode</td>
                            <td>Quantity</td>
                            <td>UnitPrice</td>
                            <td>Total</td>
                            <td>&nbsp;</td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="SalesLineNo" />
                                <span class="error">Item name required</span>
                            </td>
                            <td>
                                <input type="text" id="ItemCode" />
                                <span class="error">Valid quantity required</span>
                            </td>
                            <td>
                                <input type="text" id="Qunatity" />
                                <span class="error">Valid rate required</span>
                            </td>
                            <td>
                                <input type="text" id="UnitPrice" />
                                <span class="error">Valid rate required</span>
                            </td>
                            <td>
                                <input type="text" id="Total" />
                                <span class="error">Valid rate required</span>
                            </td>
                            <td>
                                <input type="button" id="add" value="add" />
                            </td>
                        </tr>
                    </table>
                    <div id="orderItems" class="tablecontainer">
    
                    </div>
                    @*<div style="padding:10px 0px; text-align:right">
                <input id="submit" type="button" value="Save" style="padding:10px 20px" />
            </div>*@
                    <div class="form-group">
                        @*<input type="submit" value="Create" class="btn btn-default" />*@
                        <button id="saveOrder" type="submit"value="Create" class="btn btn-default">Save Order</button>
                    </div>
                </div>
                </form>
     
    </div>
        </div>
    so that i will put break point on create method and when click save button

    it must have one record on sales header(sh) and two records on sales footer ( orderItems)

    so that my main question how to pass these record from view to controller

    I work on asp.net core 2.1 visual studio 2017 sql server 2012

    after click save button i make inspect i found two records already sent but on controller nothing exist on sales header or footet paramters of create

  2. #2
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,474

    Re: How to pass data from view to controller by ajax request as Input Parameters to C

    After the lines
    Code:
        var data = JSON.stringify({
                    orderfooter: orderItems
                });
    have been executed what does the contents of the variable data look like? Whatever that variable contains is what you are posting back to the server side action.

    If you want the /SalesOrder/Create action to be able to automatically turn this json into a variable then it will need to have a parameter that is compatible with the JSON you are sending.

    Your definition looks like
    Code:
    public ActionResult Create(SalesHeader sh, SalesFooter[] orderItems)
    so the action is expecting data that matches the structure of the SalesHeader class and also an array of SalesFooter objects, I might be wrong but it looks like this isn't what your javascript is building.

    An easier way might be to take the json from the data variable and use something like http://json2csharp.com/ to generate a compatible class, then make your /SalesOrder/Create action accept this new type as a parameter.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width