在MVC控制器中使用多个参数时,Ajax表单序列化不绑定
我的模型有多个输入的视图(Html.TextBoxFor(x => x.attribute)等.而我的ajax方法是:
I have a view with multiple inputs for my Model (Html.TextBoxFor(x => x.attribute) etc. And my ajax method is:
function callMethod() {
$.ajax({
type: "POST",
data: $('#Form').serialize() ,
url: '@Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
这很好用,该模型完美地适用于formMethod,但是当我更改formMethod并添加另一个参数(例如"int test")时,它不再起作用.
and this works perfectly, the model comes perfectly to formMethod, but when i change formMethod and add another parameter for example 'int test' it doesnt work anymore.
我的方法如下:
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);
});
};
测试":控制器中的方法的编号确实正确,但是模型现在突然为空?
the "test": number does come correctly to the method in the controller but the model suddenly is null now?
我在做什么错了?
使用.serialize()
将模型序列化为查询字符串(例如someProperty=someValue&anotherProperty=anotherValue&...
).要添加其他名称/值对,您可以手动添加,例如
Using .serialize()
serializes your model as a query string (e.g. someProperty=someValue&anotherProperty=anotherValue&...
). To add additional name/value pairs, you can append then manually, for example
var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
....
data: data;
或使用 param()方法(如果您有多个项目和/或要添加的数组)
or use the param() method (useful if you have multiple items and/or arrays to add)
var data = $("#Form").serialize() + '&' + $.param({ test: number }, true);
$.ajax({
....
data: data;