How I need to send the data from the client in order to get it in Save action?
Mean while the contacts list I get in Save action is null.
I checked fiddler and it sends id=1&address=a&id=2&address=b. I realize that I need to do something in order that MVC will “understand” that there are 2 different records.
What is done, in practice, in this case?
// Action in ContactController
public ActionResult Save(List<Contact> contacts)
{
...
}
public class Contact
{
public int Id {get;set;}
public string Address{get;set;}
}
// View
<div id="contacts">
<% for(i=0;i<3;i++) { %>
<input name=<%= list[i].id %> type="text" />
<input name=<%= list[i].address %> type="text" />
<% } %>
</div>
<script type="text/javascript">
var postData = $("#contacts").serialize();
$.ajax({
type: "POST",
url: url,
data: postData,
async: false,
success: function () { ... }
});
</script>
I would recommend you to use editor templates in your view instead of writing some for loops:
For example:
and in the view (which is strongly typed to
IEnumerable<Contact>):and inside the contact editor template (
~/View/Shared/EditorTemplates/Contact.ascx):Editor templates will ensure to generate proper names for the input fields.
Now all that’s left is AJAXify the form: