Fahad Meraj
Fahad Meraj

Reputation: 109

Ajax Call to Controller with multiple parameters

$.ajax({
    type: 'POST',
    url: '@Url.Action("AccountUpdate", "Customer")',
    async: false,
    data: { a:"ed", formCollection: $("#form1").serialize() }
});

Controller:-

public void AccountUpdate(string a, FormCollection formCollection) {}

Question:- In controller AccountUpdate I am getting parameter a ="ed" which is fine. But in FormCollection object I am getting the formCollection object and also the 'a' object Why the form collection object receiving the 'a' object ? It should be only formCollection object

Upvotes: 1

Views: 624

Answers (2)

user3559349
user3559349

Reputation:

The parameter of your POST method is typeof FormCollection which is a class that holds all submitted key/value pairs.

Change your method to

[HttpPost]
public void AccountUpdate(string a, Customer model)

And change your script to allow both your model and the additional value to be submitted and bound in the method

var data = $("#form1").serialize() + '&' + $.param({ 'a': 'ed'});

$.ajax({
    type: 'POST',
    url: '@Url.Action("AccountUpdate", "Customer")',
    data: data
});

Upvotes: 1

LeftyX
LeftyX

Reputation: 35597

data: $("#form1").serialize() 

is the way to go.

If you want to add some extra parameters:

$.ajax({
    type: 'POST',
    url: '@Url.Action("AccountUpdate", "Customer")',
    // async: false,
    data: "a=ed&" + $("form1").serialize()
});

This way you can bind directly to your view model:

[HttpPost]
public ActionResult Index(string a, Customer customer)
{
    ...
}

Upvotes: 1

Related Questions