c# - 在 MVC Controller 中使用多个参数时,Ajax 表单序列化不绑定(bind)

标签 c# jquery ajax asp.net-mvc model

我的模型有多个输入 View (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);
    });
};

这很完美,模型完美地适应了 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);
    });
};

“测试”: Controller 中的方法确实正确输入了数字,但模型现在突然为空?

我做错了什么?

最佳答案

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

var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
    ....
    data: data;

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

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

关于c# - 在 MVC Controller 中使用多个参数时,Ajax 表单序列化不绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525744/

相关文章:

C#静态接口(interface)或抽象实现

jquery - 如何在 jqgrid 内联编辑上添加任何逻辑以在按下回车键时保存行?

javascript - 如果 AJAX 错误,如何停止 jquery 自动完成微调器

javascript 代码或 json 对象作为 ajax 响应?

c# - 如何验证属性值?

c# - 我如何在 .Net 控制台应用程序中获取不记名 token ?

c# - 警告 : Missing XML comment for publicly visible type or member 'Properties.Settings'

javascript - 使用 jQuery 在没有 URL 的窗口中打开 PDF

php - 如何使用 jQuery 在特定的点击项上显示从 php 检索到的数据?

javascript - 将javascript返回值插入html