aryaxt
aryaxt

Reputation: 77596

JQuery Post data to MVC Action Method?

All I'm trying to do is to pass an array of strings/ints to mvc action method. But the data always comes back as null, what am I doing wrong?

MVC Controller

[HttpPost]
 public ActionResult MyAction(List<string> ids)
 {
   // do something with array
   // But it's null
      return View();
 }

JQuery

$.post("/MyController/MyAction", JSON.stringify(ids), function () { alert("woohoo"); }, "application/json");

Data being posted to action result

["156"]

Upvotes: 2

Views: 11812

Answers (1)

Erik Philips
Erik Philips

Reputation: 54618

Try:

... JSON.stringify({ ids : ids }), ...

I'm pretty sure the model binder isn't sure what the list/array is suppose to be bound too.

Consider:

[HttpPost]
public ActionResult MyAction(List<string> ids, List<string> blah)
{
}

If JSON is passed as just an array of values, which parameter to do bind too? JSON can be much more complex than a FORMS submission so it also needs a bit more definition.

For example, the following would work for the previous consideration.

{
  ids : ["asdf","asdf"],
  blah : ["qwer", "qwer"]
}

Update

In order to send json properly the following ajax call would need to be made:

$.ajax({
  type: "POST",
  url: "/Home/Index",
  data: JSON.stringify( ids ),
  contentType: "application/json; charset=utf-8"
});

The last parameter in Post (you specified application/json) is what to expect back from the server. By default, the a $.Post will do a Forms Encoded (application/x-www-form-urlencoded) contentType which appears to be hard coded into the shortcut method. To set the contentType you have to use the long handed version $.ajax.

Upvotes: 3

Related Questions