MVC Model Binding List of objects

ajax, asp.net-mvc, c#, jquery

Solution

You can try to use

  @using(Ajax.BeginForm("SaveModel", "controller", formMethod.Post, new AjaxOptions{ }))
  {
      // your form
  }

Don't forget use the jquery.unobtrusive-ajax.js

and with Ajax.BeginForm you can remove that block of jQuery code to send your form, and it makes that your form be bind directly in the Action.

Problem

I am having trouble binding a model that contains list of objects. There are no problems when i try to pass the data from the controller to the view, but when i want to send the data back, i get a message that the method doesnt exists. I am using an ajax call and as data i put $form.serialize() and can see the list with all the data in fiddler, but i am having no luck with the binding. The Model is: ``` public class Single { public int Id {get;set;} public string Name {get;set;} public List<SimpleDropdown> dddl {get;set;} public int SelectedEmp {get;set;} } public class MainModel { public List<Single> main_model_list {get;set;} } ``` In my controller the method for now is: ``` [HttpPost] public string SaveModel(MainModel model) { return ""; } ``` This method doesn't get called, but when i remove the parameter the calling works. So i'm sure that the binding doesn't work. I had a lot more complex model, but i simplified it as much as i can and still couldn't get it to work. So my question is how can i test this to see what is the problem? Edit: I dont have the code at the moment, but that code is functional because i use it in other places in the project. It is something like this: ``` $("#form").submit(function( ) { $.ajax({ url: "/Controller/SaveModel", type: "POST", data: $(this).serialize() }); }); ``` The form looks something like this: ``` @using (Html.BeginForm("SaveModel", "Home", FormMethod.Post, new { id = "form" })) { @for (var z = 0; z < ViewBag.groupes.Length; z++) { <div style="border-left: 1px solid black"> <h1>@ViewBag.groupes[z]</h1> </div> } @for (var i = 0; i < Model.main_model_list.Count; i++) { <div>@Html.LabelFor(x => x.main_model_list[i].Id)</div> <div>@Html.LabelFor(x => x.main_model_list[i].Name)</div> <div style="float: left">@Html.DropDownListFor(x => main_model_list[i].SelectedEmp, new SelectList(main_model_list[i].dddl, "Id", "Value", main_model_list[i].SelectedEmp), new { @class = "preferences_dd_lists" })</div> } } ```

Original source