从ajax回发到控制器操作不起作用?

时间:2018-08-15 07:56:51

标签: jquery json ajax asp.net-mvc modelbinders

这是我的ajax调用:

$('#SaveItemButton').click(function () {   
        var tableData = { 'ItemViewModel': table.$('input, select').serialize() }; // here the data gets returned          
        //Add Data Function
        function Add() {                    
            $.ajax({
                url: "/Item/Add",
                data: tableData,
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    alert("success: " + result);
                },
                error: function (errormessage) {
                    alert("error: " + errormessage);
                }
            });
        }       
    } );

这是我的控制器动作:

public JsonResult Add(List<ItemViewModel> ItemViewModel)
{
   var x = ItemViewModel;               
   return Json(1, JsonRequestBehavior.AllowGet);
}

tableData 返回的实际数据:      “ ItemType=Type1&Unit=select&Quantity=12&Price=1000&Total=&ItemType=Type2&Unit=//select&Quantity=11&Price=2000&Total="

我的控制器操作正在接收ItemViewModel = null。谁能告诉我我需要处理接收到的数据,以便我成功地回发到服务器并绑定到模型:

public class ItemViewModel
    {        
        public int Id { get; set; }
        public string ItemType { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
        public ICollection<ProductViewModel> Products { get; set; }
        public ICollection<ServiceViewModel> Services { get; set; }
        public ICollection<CustomerViewModel> Customers { get; set; }
        public InvoiceViewModel Invoice { get; set; }
        public string ApplicationUserID { get; set; }        
        public int ProductId { get; set; }       
        public int ServiceId { get; set; }       
        public int InvoiceId { get; set; }
        public int CustomerId { get; set; }
        public string InvoiceDate { get; set; }
        public string TransferDate { get; set; }
        public string TransferPlace { get; set; }
        public string InvoiceDescription { get; set; }        
    }

这是我的观点:

@using (Html.BeginForm("Add", "Item", FormMethod.Post, new { @class = "form-horizontal", id = "ItemForm", role = "form" }))
{
    <body>
        <h2>Invoice</h2>

        <table id="ItemTable" class="table table-hover table-secondary" style="width:100%">
            <thead>
                <tr>
                    <th></th>
                    <th>ItemType</th>
                    <th>Unit</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>
                    <th></th>
                </tr>
            </thead>
        </table>

    </body>
}

这是jquery数据表,javascript:

$(document).ready(function () {
    var table = $('#ItemTable').DataTable({
        "dom": '<"toolbar">frtip',
        "paging": true,
        "pagingType": "full_numbers",
        "searching": false,
        responsive: {
            details: {
                type: 'column'
            }
        },
        columnDefs: [{
            className: 'control',
            orderable: false,
            targets: 0
        }],
        order: [1, 'asc']
    });

    $("div.toolbar").html(
        '<button id="addRow" type="button" class="btn btn-outline-info fa fa-plus"> Add</button> <div class="divider"/>' +
        '<button id="SaveItemButton" type="submit" class="btn btn-outline-secondary fa fa-save"> Save</button> <div class="divider"/>' +
        '<button id="PreviewButton" type="button" class="btn btn-outline-info fa fa-eye"> Preview</button> <div class="divider"/>' +
        '<button id="PrintButton" type="button" class="btn btn-info fa fa-print"> Print</button> <div class="divider"/>' +
        '<button id="SendButton" type="button" class="btn btn-lump-sum fa fa-envelope"> Send</button> <div class="divider"/>' +
        '<button id="DeleteButton" type="button" class="btn btn-secondary fa fa-trash"> Delete </button> <div class="divider"/>'
    );

    var counter = 1;

    $('#addRow').on('click', function () {
        table.row.add([
            '',
            '<input name="ItemType" class="form-control" type="text">',

            '<select name="Unit" class="form-control defaultpicker">' +
                '<option value="select">dan</option>' + 
                '<option value="select">Komad</option>' +
                '<option value="select">Sat</option>' +
                '<option value="select">m</option>' +
                '<option value="select">m2</option>' +
                '<option value="select">m3</option>' +
                '<option value="select">kg</option>' +
                '<option value="select">lit</option>' +
                '<option value="select">pak</option>' +
                '<option value="select">reč</option>' +                               
            '</select > ',

            '<input name="Quantity" class="form-control" type="number">',
            '<input name="Price" class="form-control" type="text">',
            '<input name="Total" class="form-control" type="text" readonly>',
            '<button type="button" Id="DeleteButton" class="fa fa-times select-row btn btn-secondary btn-sm" data-id=""></button>',            
        ]).draw(false);

        counter++;
        $('#ItemTable').dataTable().fnPageChange('last');
    });

    $('#ItemTable').on("click", "#DeleteButton", function () {
        var table = $('#ItemTable').DataTable();
        var row;

        console.log($(this).closest('table'));
        if ($(this).closest('table').hasClass("collapsed")) {
            var child = $(this).parents("tr.child");
            row = $(child).prevAll(".parent");
        } else {
            row = $(this).parents('tr');
        }

        table.row(row).remove().draw();
    });

    // Automatically add a first row of data
    $('#addRow').click();    

    $('#SaveItemButton').click(function () {
        debugger;
        //Add Data Function
        function Add() {                    
            $.ajax({
                url: "/Item/Add",
                data: table.$('input, select').serialize(),
                type: "POST",                
                dataType: "json",
                success: function (result) {
                    alert("success: " + result);
                },
                error: function (errormessage) {
                    alert("error: " + errormessage);
                }
            });
        }       
    } );
});

1 个答案:

答案 0 :(得分:1)

您不能在javascript对象中使用合并.serialize(),并且在使用.serialize()时,无论如何都需要使用默认的contentType'application/x-www-form-urlencoded; charset=UTF-8')。

一种选择是在名称属性中包含集合索引器,以便表单控件的name属性为name="[#].ItemType",其中#是从零开始的连续索引器,在这种情况下,ajax调用可以是

$.ajax({
    url: "/Item/Add",
    data: table.$('input, select').serialize(),
    type: "POST",
    ....

但是,由于您似乎还想删除项目,因此这也意味着您需要在每行中为集合索引器(例如<input name="Index" value="#">)添加输入。

或者,您需要根据每个<tr>中每个表单控件的值生成和排列对象,对其进行字符串化,然后使用contentType: 'application/json'

发送

构建数组

var arr = [];
// adjust following to exclude any tr elements in a thead or tfoot if applicable
var rows = $('#ItemTable').find('tr');
$.each(rows, function(index, item) {
    var controls = $(this).find('input, select');
    var item = {
        ItemType: controls.eq(0).val(),
        Unit: controls.eq(1).val(),
        Quantity: controls.eq(2).val(),
        Price controls.eq(3).val(),
    }
    arr.push(item);
});

然后发布

$.ajax({
    url: '@Url.Action("Add", "Item")', // don't hard code your urls
    data: JSON.stringify(arr),
    contentType: 'application/json',
    type: "POST",                
    dataType: "json",
    success: function (result) {
        ....

作为旁注,您正在使用<select>创建一个name="Unit",但模型中似乎没有该名称的属性。此外,您还给了每个<option>相同的value="select"