Linking an Ajax Model of a Complex Type

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

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

If the type of Author is as follows:

 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; } } 

On the page, I want to send 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), but does not bind the Books property. Why is this and how can I pass an object containing an Array (or collection) as a property via AJAX?

+6
jquery ajax asp.net-mvc
source share
2 answers

DaveG,

Should I use the POST method, not GET?

i.e.

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

I am sure there may be other problems, as well as re json formatting, but these are my initial thoights at a glance.

+2
source share

This fixed it for me: fooobar.com/questions/668935 / ...

It comes down to adding

 contentType: 'application/json' 

and adding JSON.stringify before sending your data:

 data: JSON.stringify(dataObj), 
+1
source share

All Articles