jQuery.POST - 使用Form.Serialize()传递另一个参数 - Asp.net MVC 3

nun*_*unu 5 model-view-controller asp.net-mvc jquery asp.net-mvc-3

当我在Asp.Net MVC应用程序上工作时,在我的应用程序中,我使用jQuery.POST方法提交表单.

例如

jQuery.post('/Product/Save', jQuery(document.forms[0]).serialize(), 
       function (data) { alert('Product Added Successfully.); }
);
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段,我想通过另一个参数..让我们说... ProductID.

所以,这个想法是,我想通过这两个jQuery(document.forms[0]).serialize()ProductID variablejQuery.POST method,所以我既可以得到Form and ProductID我的controller's action method.

有人可以让我知道我会这样做吗?

提前致谢.

Dar*_*rov 13

您可以使用以下插件将表单序列化为JSON对象并添加其他参数:

$.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;
};
Run Code Online (Sandbox Code Playgroud)

像这样:

var data = $('form').serializeObject();
data['ProductId'] = '123';
$.post('<%= Url.Action("Save", "Product") %>', data, function (data) { 
    alert('Product Added Successfully.'); 
});
Run Code Online (Sandbox Code Playgroud)