0

My action method used to have one parameter, and I didn't have any problem to pass model to it.

public ActionResult actionMethod([Bind(Exclude = "pro1, pro2")] Class model)

And the Ajax call:

var formData = $('form').serialize();
$.ajax({
    url: "@Url.Action("actionMethod", "controller")",
    method: 'post',
    data: { header: formData},
    success: function (result) {
        .....
    }
});

It worked fine, until I had to add another parameter to the method:

public ActionResult actionMethod([Bind(Exclude = "pro1, pro2")] Class model, string anotherParam = "1")

And I'm trying with this Ajax call:

var formData = $('form').serialize();
$.ajax({
    url: "@Url.Action("actionMethod", "controller")",
    method: 'post',
    data: {
        header: formData,
        anotherParam: '1'
    },
    success: function (result) {
        .....
    }
});

And it doesn't work anymore, the model is always null. How should I pass these data?

Akbari
  • 2,369
  • 7
  • 45
  • 85
  • 1
    On option would be just `formData += '&anotherParam=1` and then `data: formData,` but using FormData is a better aproach. Refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) and in particular the last code snippet for adding extra data –  Jul 01 '15 at 05:46
  • Thanks Stephen, I have another not much related question too: I have to put elements of this model in different places, so there are other controls between them. currently, I just use `form` to serialize them. But I might have other forms too, do I have any better option? – Akbari Jul 01 '15 at 05:59
  • Do you mean you have multiple forms on the same page and you want to serialize and post them all? –  Jul 01 '15 at 06:04
  • Yes, and I want them to be bound in one model! – Akbari Jul 01 '15 at 06:05
  • You can still use FormData - perhaps just select all `input`, `textarea` and `select` elements and using a `$.each()` get the `name` attribute (`var name = $(this).attr('name');`) and value (`var value = $(this).val();`) and append each one - `formdata.append(name, value);` –  Jul 01 '15 at 06:10

1 Answers1

1

May not be the best way, but following will make it work.

Pass the form data as usual in the 'data' parameter of ajax, and put the extra parameter in the query string of url.

var formData = $('form').serialize();
$.ajax({
    url: '@Url.Action("actionMethod", "controller", new { anotherParam = 1})',
    method: 'post',
    data: {
        header: formData
    },
    success: function (result) {
        .....
    }
});
wonderbell
  • 1,126
  • 9
  • 19