在 MVC 控制器中使用多个参数时,Ajax 表单序列化不会绑定

Ste*_*ler 5 c# ajax asp.net-mvc jquery model

我的模型有一个包含多个输入的视图(Html.TextBoxFor(x => x.attribute) 等)。我的ajax 方法是:

function callMethod() {
    $.ajax({
        type: "POST",
        data: $('#Form').serialize() ,
        url: '@Url.Action("formMethod", "Test")',
    }).done(function (newTable) {
        $('#RefundTableDiv').html(newTable);
    });
};
Run Code Online (Sandbox Code Playgroud)

这工作得很好,模型完美地适合 formMethod,但是当我更改 formMethod 并添加另一个参数(例如“int test”)时,它不再工作。

我的方法如下所示:

function callMethod() {
 var number = 2;
    $.ajax({
        type: "POST",
        data: {"model": $('#Form').serialize(),
               "test": number}, 
        url: '@Url.Action("formMethod", "Test")',
    }).done(function (newTable) {
        $('#RefundTableDiv').html(newTable);
    });
};
Run Code Online (Sandbox Code Playgroud)

“测试”:数字确实正确地到达控制器中的方法,但模型现在突然为空?

我究竟做错了什么?

小智 4

使用.serialize()将您的模型序列化为查询字符串(例如someProperty=someValue&anotherProperty=anotherValue&...)。要添加其他名称/值对,您可以手动附加,例如

var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
    ....
    data: data;
Run Code Online (Sandbox Code Playgroud)

或使用param()方法(如果要添加多个项目和/或数组,则很有用)

 var data = $("#Form").serialize() + '&' + $.param({ test: number }, true);
 $.ajax({
    ....
    data: data;
Run Code Online (Sandbox Code Playgroud)