Consume jQuery.serializeArray in ASP.NET MVC

后端 未结 2 1854
臣服心动
臣服心动 2021-01-26 20:40

I post $(\'#myForm\').serializeArray() to an ASP.NET MVC (2.0) action. serialized array looks as follows:

filters[0][name]    : gemcolor
filters[0][         


        
2条回答
  •  走了就别回头了
    2021-01-26 21:19

    This won't work because the default model binder doesn't expect the data to be formatted like this. Simply use .serialize() instead of serializeArray(). Example:

    $.ajax({
        url: '/foo',
        type: 'post',
        data: $('#myForm').serialize(),
        success: function(result) {
            alert('ok');
        }
    });
    

    or simplify your life by using the excellent jquery form plugin which allows you to AJAXify existing HTML forms in an elegant manner:

    $(function() {
        $('#myForm').ajaxForm(function(result) {
            alert('ok');
        });
    });
    

    UPDATE:

    After the explanation in your comment here's how you could proceed:

    You could use the plugin from this answer which transforms the form elements into an object understandable by the default model binder and could be aggregated with some other information:

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                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;
    };
    

    and then simply:

    data: { filters: $('#myForm').serializeObject(), someOtherData: 'foo bar'  }
    

提交回复
热议问题