5

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);
    });
};

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.

My method looks like:

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?

What am i doing wrong?

1
  • the model is null because you're sending JSON with a url-encoded string within it. You can't mix the formats like that. Your controller just thinks "model" is a random string value. Either submit everything as JSON, or everything as regular query parameters Commented Oct 2, 2017 at 13:47

2 Answers 2

4

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;

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;
Sign up to request clarification or add additional context in comments.

Comments

2

you can do it like this:

function callMethod() {
    var number = 2;
    var sd = $('#Form').serializeArray();
    sd.push({ name:"test", value:number });

    $.ajax({
        type: "POST",
        data: sd,
        url: '@Url.Action("formMethod", "Test")',
    }).done(function (newTable) {
        $('#RefundTableDiv').html(newTable);
    });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.