JQuery Post data to MVC Action Method?

11,738

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.

Share:
11,738
aryaxt
Author by

aryaxt

Updated on June 04, 2022

Comments

  • aryaxt
    aryaxt almost 2 years

    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"]
    
  • aryaxt
    aryaxt about 11 years
    I have tried that already, still coming back as null { "ids" : ["156"] }
  • Erik Philips
    Erik Philips about 11 years
    Sorry you also have to specify the content type. Updating answer.
  • aryaxt
    aryaxt about 11 years
    I have that in my code already, I started parallel (VM) and everything works now. Too ba dI can't delete the question
  • Erik Philips
    Erik Philips about 11 years
    You question is perfectly valid, even if the answer was found, anyone else trying to use $.post to send Json will also experience the same problem and hopefully find this solution. That is why SO exists.
  • Damith
    Damith about 11 years
    @ErikPhilips 1+ and congrats for 10k rep :)