Use jQuery datatables server-side processing with mvc. Serialize criteria form and add this parameter to $ajax.post method

余生颓废 提交于 2019-12-04 14:53:45
Darin Dimitrov

$("myForm").serialize() won't cut the mustard here. First $("myForm") is a selector that is looking for a tag <myForm> which I guess doesn't exist. You are probably looking for a <form> tag with id="myForm" in which case the correct selector would have been $('#myForm').

This being said, the .serialize() method will simply turn the form input fields into application/x-www-form-urlencoded payload. But when you pass that to the hm parameter it obviously won't work. You need the entire request payload to be application/x-www-form-urlencoded if you want the model binder to be able to deserialize it properly.

So let me suggest you the following extension:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Once you have declared it you can simply do that:

$('#myDataTable').dataTable({
    "bServerSide": true,
    "sAjaxSource": "/Home/AjaxHandler",
    "bProcessing": false,
    "sServerMethod": "POST",
    "fnServerData": function (sSource, aoData, fnCallback) {
        var formData = $('#myForm').serializeObject();
        for (var key in formData) {
            if (formData.hasOwnProperty(key)) {
                aoData.push({
                    name: key,
                    value: formData[key]
                });
            }
        }

        $.ajax({
            "dataType": 'json',
            "type": "POST",
            "url": sSource,
            "data": aoData,
            "success": fnCallback
        })
    }
});

and the 2 arguments of your AjaxHandler action will now be correctly bound. Simply inspect the Network tab in your javascript debugging tool to see the difference between the 2 payloads and you will understand why your code didn't work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!