6

I am trying to do something along the lines of the following where I have a Controller with an method similar to:

public ActionResult Insert(Author author) {
  //do something...
}

Where the Author type looks like:

public class Author {
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public Book[] Books { get; set; }

  public Author() {
    Books = new Book[0];
  }
}

public class Book {
  public string Title { get; set; }
  public int NumberOfPages { get; set; }
}

From a page I want to submit data using JQuery and Ajax something like

function addAuthor() {
  var auth = {
    'FirstName': 'Roald',
    'LastName': 'Dahl',
    'Books': [
      {
        'Title': 'Charlie and the Chocolate Factory',
        'NumberOfPages': 264
      },
      {
        'Title': 'The Twits',
        'NumberOfPages': 316
      }
    ]
  };

  $.ajax({
    type: "GET",
    url: "/Insert",
    data: auth
  });

}

MVC binds the Author object (FirstName and LastName are set) but doesn't bind the Books property. Why is that and how can I submit an object containing an Array (or a Collection) as a property through AJAX?

David Glenn
  • 24,412
  • 19
  • 74
  • 94

2 Answers2

2

DaveG,

Wouldn't you need to use a POST method rather than the GET ??

i.e.

  $.ajax({
    type: "POST",
    url: "/Insert",
    data: auth
  });

i'm sure there may be other issues as well re json formatting but this is my initial thoights on 1st glance.

jim tollan
  • 22,305
  • 4
  • 49
  • 63
  • I have the same problem and POST made the trick. I don't know why it works like that, but it is what it is – Ivo Jul 27 '12 at 05:00
1

This fixed it for me: https://stackoverflow.com/a/9775470/647845

It comes down to adding

contentType: 'application/json'

and adding JSON.stringify before you send your data:

data: JSON.stringify(dataObj),
Community
  • 1
  • 1
Dirk Boer
  • 8,522
  • 13
  • 63
  • 111