2

I am having a simple issue which is taking way to long to figure out. I cant seem to get data from JS into MVC.

JS:

           var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];
           $.ajax({
                url: '@Url.Action("Action")',
                type: 'POST',
                data: JSON.stringify({ stuff: stuff }),
                traditional: true
            });
            

MVC

         public enum Level
         {
              High = 10,
              Normal = 5,
              Low = 1
         }
         ...
         public class MyModel
         {
              public int a { get; set; }
              public Level b { get; set; }
         }
         ...
         public ActionResult Action(List<MyModel> stuff){
              //stuff is always null no matte what I try?
              ....
         }

I am not sure where my problem actually is, as this is surprisingly hard to debug.

5
  • 1
    Possible duplicate of Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax Commented Nov 19, 2015 at 15:10
  • Is url: '@Url.Action("Action")', actually being converted to a valid url? Commented Nov 19, 2015 at 15:10
  • @Stephen: I'd assume since stuff is always null, that it is actually hitting the right method, just not including the values Commented Nov 19, 2015 at 15:11
  • @Stephen, yes the ActionResult is being hit. Commented Nov 19, 2015 at 15:13
  • @MattBurland there isn't any reason to use FromBodyAttribute in this situation... Commented Nov 19, 2015 at 15:19

2 Answers 2

4

Specify the contentType properpty on your ajax call and it should work fine.

When sending data to server using $.ajax, default contentType value is "application/x-www-form-urlencoded; charset=UTF-8" . Since we are sending JSON data, We should specify it.

var stuff = [{a: 1, b: "Low"}, {a: 5, b:"High"}];

$.ajax({
    url: '@Url.Action("Action")',
    type: 'POST',
    data: JSON.stringify({ stuff: stuff }),

    contentType:"application/json",  //This is the new line

    traditional: true
}).done(function(res) {
    console.log("Result came back");
});
Sign up to request clarification or add additional context in comments.

Comments

0

I just realized this is the issue:

data: JSON.stringify({ stuff: stuff })

change it to:

data: JSON.stringify(stuff)

1 Comment

MVC is smart enough to do either of these. You can pass an object with matching properties/parameters or just pass the straight object and bind it to all parameters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.