Home > OS >  How can I pass JSON formatted data from View to controller action in ASP.NET Core MVC
How can I pass JSON formatted data from View to controller action in ASP.NET Core MVC

Time:07-21

I am new in.net core MVC. I want to send data from view to controller in JSON format.

I am creating dynamic table for saving data of data. post I want to send this newly added data controller.

Kindly see the logic and update me if anything I doing wrong or how can I achieve my aim.

I want to retrieve the values in SubmitExpense() method

Here is the javascript:

 $(function () {
            $('#btnSave').on('click', function () {
                //alert('1111');
                var ExpenseCliamViewModel = {};
                var ExpenseClaimLineItems = new Array();
    
                $("#myTable:eq(0) TR").each(function () {
    
                    var row = $(this);
                    var ExpenseClaimLineItem = {};
                    //ExpenseCliamViewModel.ExpenseClaimLineItem.
                    ExpenseClaimLineItem.LineItemTitle = row.find("TD").eq(1).html();
                    ExpenseClaimLineItem.LineItemDescription = row.find("TD").eq(2).html();
                    ExpenseClaimLineItem.ExpenseTypeName = row.find("TD").eq(3).html();
                    ExpenseClaimLineItem.LineItemAmount = row.find("TD").eq(4).html();
                    ExpenseClaimLineItem.LineItemClaimDate = row.find("TD").eq(5).html();
                    // alert(ExpenseClaimLineItem);
                    ExpenseClaimLineItems.push(ExpenseClaimLineItem);
                });
    
                ExpenseCliamViewModel.ExpenseClaimLineItem = ExpenseClaimLineItems;
                ExpenseCliamViewModel.Title = $("#Title").val();
                ExpenseCliamViewModel.Description = $("#Description").val();
                ExpenseCliamViewModel.TotalAmount = $('#lblGrandTotal').html();
    
    
               // ExpenseCliamViewModel.Title = $("#Title").val();
                console.log(JSON.stringify(ExpenseCliamViewModel));
    
                if (ExpenseCliamViewModel != null) {
                    $.ajax({
                        type: "POST",
                        url: "/Expense/SubmitExpense",
                        data: JSON.stringify(ExpenseCliamViewModel),
                         contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            if (response != null) {
                                alert('Sucess');
                            } else {
                                alert("Something went wrong");
                            }
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    }); 
                }
                else
                    alert('failed');          
                
            });
        });

Here is the controller C# method:

[HttpPost]
public JsonResult SubmitExpense(ExpenseCliamViewModel expenseCliamViewModelData)
{
 int insertedRecords = 1;
 return Json(insertedRecords);
}

CodePudding user response:

In your ajax, try :

 $.ajax({
        type:'POST',
        url:"/Expense/SubmitExpense",   
        data:ExpenseCliamViewModel,
        success:function(data){alert("success")},
        error:function(){alert("error")}
    });

CodePudding user response:

Here is my cshtml code

@model ExpenseWebApplication.Models.ExpenseCliamViewModel

<div >
    <h1 >Create New Expense</h1>
</div>
<br />
<br />
<br />


<div>
    <div >
        <div  width="100%">
            <form  asp-action="CreateExpense">
                @*@Html.ValidationSummary(true)*@
                <div >
                    <label ><b>Title</b></label>
                    <input  type="text" asp-for="Title" id="Title" required="required" />
                </div>
                <div >
                    <label ><b>Description</b></label>
                    @*<input  type="text" row asp-for="Description" />*@
                    <textarea  rows="4" asp-for="Description" id="Description"></textarea>
                </div>

                <table id="submissionTable"  width="100%">
                    <tr id="tablerow0">
                        <td>
                            <table>
                                <tr>
                                    <td>
                                        <label ><b>Title</b></label>
                                    </td>
                                    <td>
                                        <div >
                                            <input  id="LineItemTitle"
                                                   name="LineItemTitle" type="text" value=""
                                                   asp-for="LineItemTitle" required="required" />
                                        </div>
                                    </td>
                                    @*</tr>
                                        <tr>*@
                                    <td>
                                        <label ><b>Description</b></label>
                                    </td>
                                    <td>
                                        <div >
                                            <textarea  rows="2" id="LineItemDescription"
                                                      name="LineItemDescription" value=""
                                                      asp-for="LineItemDescription"></textarea>

                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <label ><b>Expense Type </b></label>
                                    </td>
                                    <td>
                                        <div >
                                            <select  id="LineItemExpenseType"
                                                    name="LineItemExpenseType" asp-for="ExpenseTypeList"
                                                    asp-items="Model.ExpenseTypeList"></select>
                                        </div>
                                    </td>
                                    <td>
                                        <label ><b>Amount</b></label>
                                    </td>
                                    <td>
                                        <input  id="LineItemAmount"
                                               name="LineItemAmount[0]" type="text" value=""
                                               required="required" />
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <label ><b>Expenses Date</b></label>
                                    </td>
                                    <td>
                                        @Html.EditorFor(Model => Model.LineItemClaimDate, DateTime.Now.ToShortDateString(),
                                        new { htmlAttributes = new { @class = "form-control input-datepicker", @placeholder = "mm/dd/yyyy" } })
                                    </td>
                                    <td colspan="2" align="right">
                                        <input type="button"  value="Add Row">
                                        @*<button type="button"  onclick="removeTr(0);">Delete</button>*@
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                @*<table id="myTableEmpty" >
                        <thead >
                            <tr>
                                <th>Select</th>
                                <th>Title</th>
                                <th>Description</th>
                                <th>Expense Type</th>
                                <th>Amount</th>
                                <th>Expenses Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="6">No Records Found</td>
                            </tr>
                        </tbody>
                    </table>*@

                <table id="myTable" >
                    <thead >
                        <tr>
                            <th>Select</th>
                            <th>Title</th>
                            <th>Description</th>
                            <th>Expense Type</th>
                            <th>Amount</th>
                            <th>Expenses Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        @*<tr>
                                <td><input type="checkbox" name="record"></td>
                                <td>Title</td>
                                <td>Description</td>
                                <td>
                                    Expense Type
                                </td>
                                <td>Amount</td>
                                <td>Expenses Date</td>
                            </tr>*@
                    </tbody>
                </table>

                <p>
                    <button type="button" >Delete Row</button>
                    <b> <span style="margin-left:100px;"> Total : <span id="lblGrandTotal"></span></span></b>
                </p>

                <div >
                    <input type="submit" id="btnSave" value="Submit" />
                </div>
            </form>
        </div>
    </div>

</div>



<script type="text/javascript">
    $(function () {
        $('#btnSave').on('click', function () {
            //alert('1111');
            var ExpenseCliamViewModel = {};
            var ExpenseClaimLineItems = new Array();

            $("#myTable:eq(0) TR").each(function () {

                var row = $(this);
                var ExpenseClaimLineItem = {};
                //ExpenseCliamViewModel.ExpenseClaimLineItem.
                ExpenseClaimLineItem.LineItemTitle = row.find("TD").eq(1).html();
                ExpenseClaimLineItem.LineItemDescription = row.find("TD").eq(2).html();
                ExpenseClaimLineItem.ExpenseTypeName = row.find("TD").eq(3).html();
                ExpenseClaimLineItem.LineItemAmount = row.find("TD").eq(4).html();
                ExpenseClaimLineItem.LineItemClaimDate = row.find("TD").eq(5).html();
                // alert(ExpenseClaimLineItem);
                ExpenseClaimLineItems.push(ExpenseClaimLineItem);
            });

            ExpenseCliamViewModel.ExpenseClaimLineItem = ExpenseClaimLineItems;
            ExpenseCliamViewModel.Title = $("#Title").val();
            ExpenseCliamViewModel.Description = $("#Description").val();
            ExpenseCliamViewModel.TotalAmount = $('#lblGrandTotal').html();


            // ExpenseCliamViewModel.Title = $("#Title").val();
            console.log(JSON.stringify(ExpenseCliamViewModel));

            if (ExpenseCliamViewModel != null) {
                $.ajax({
                    type: 'POST',
                    url: "/Expense/SubmitExpense",
                    data: ExpenseCliamViewModel,
                    success: function (data) { alert("success") },
                    error: function () { alert("error") }
                });
                //$.ajax({
                //    type: "POST",
                //    url: "/Expense/SubmitExpense",
                //    //data: JSON.stringify(ExpenseCliamViewModel),
                //    data: {
                //        expenseCliamViewModelData: JSON.stringify(ExpenseCliamViewModel)
                //    },
                //    contentType: "application/json; charset=utf-8",
                //    dataType: "json",
                //    success: function (response) {
                //        if (response != null) {
                //            alert('Sucess');
                //        } else {
                //            alert("Something went wrong");
                //        }
                //    },
                //    failure: function (response) {
                //        alert(response.responseText);
                //    },
                //    error: function (response) {
                //        alert(response.responseText);
                //    }
                //});
            }
            else
                alert('failed');


        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function () {

        $(".add-row").click(function () {
            //alert('asd');
            var LineItemTitle = $("#LineItemTitle").val();
            var LineItemDescription = $("#LineItemDescription").val();
            var LineItemExpenseType = $('#LineItemExpenseType :selected').text();
            var LineItemAmount = $("#LineItemAmount").val();
            var LineItemClaimDate = new Date($("#LineItemClaimDate").val());
            var myDate = LineItemClaimDate.getDate()   '-'   LineItemClaimDate.getMonth()   '-'   LineItemClaimDate.getFullYear()
            var markup = "<tr><td><input type='checkbox' name='record'></td><td>"   LineItemTitle   "</td><td>"   LineItemDescription   "</td><td>"   LineItemExpenseType   "</td><td>"   LineItemAmount   "</td><td>"   myDate   "</td></tr>";
            var tbody = $('#myTable').children('tbody');
            var table = tbody.length ? tbody : $('#myTable');
            table.append(markup);
            CalculateGrandTotal();
        });

        $(".delete-row").click(function () {
            $("table tbody").find('input[name="record"]').each(function () {
                if ($(this).is(":checked")) {
                    $(this).parents("tr").remove();
                }
            });
            CalculateGrandTotal();
        });
    });

</script>

<script type="text/javascript">
    function CalculateGrandTotal() {
        var grandTotal = 0;

        var tb = $('#myTable:eq(0) tbody');
        var size = tb.find("tr").length;

        tb.find("tr").each(function (index, element) {
            var colSize = $(element).find('td').length;

            $(element).find('td').each(function (index, element) {
                var colVal = $(element).text();
                if (index == 4) {
                    grandTotal  = parseFloat(colVal.trim());
                }
            });
        });
        $('#lblGrandTotal').html(grandTotal.toFixed(2));
    }

</script>

Here is my model class

enter code here

    public class ExpenseCliamViewModel
    {
        public int Id { get; set; }
        public int CurrencyId { get; set; }
        public string ClaimCode { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int ExpenseStatusId { get; set; }
        public decimal TotalAmount { get; set; }
        public int RequestedBy { get; set; }
        public DateTime RequestedDate { get; set; }
        public DateTime ModifiedDate { get; set; }
        public int ApprovedBy { get; set; }
        public DateTime ApprovedDate { get; set; }
        public string ApproverRemark { get; set; }
        public int ProcessedBy { get; set; }
        public DateTime ProcessedDate { get; set; }
        public string ProcessorRemark { get; set; }

        public List<Tbl_ExpenseClaimLineItem> ExpenseClaimLineItem  { get; set;}

        public int LineItemId { get; set; }
        public string LineItemCode { get; set; }
        public string LineItemTitle { get; set; }
        public string LineItemDescription { get; set; }
        public int ExpenseClaimId { get; set; }
       // public int ExpenseTypeId { get; set; }
        public decimal LineItemAmount { get; set; }
        public string LineItemClaimDate { get; set; }
     



        public int ExpenseTypeId { get; set; }
        public string ExpenseTypeCode { get; set; }
        public string ExpenseTypeName { get; set; }
        public decimal ExpenseTypeLimit { get; set; }
        public bool ExpenseTypeIsActive { get; set; }
        public List<SelectListItem> ExpenseTypeList { get; set; }
    }
}


 
  • Related