Is there a way to structure the html of a form to post all data for the Item class? Here are the classes and controller action:
public class Item
{
public Item (){}
public string Name { get; set; }
public string Description { get; set; }
public List<string> Tag { get; set; }
public List<Note> Notes {get; set; }
}
public class Note
{
public string Id { get; set; }
public string NoteText { get; set; }
public string OtherStuff { get; set; }
}
[HttpPost]
public ActionResult SaveItemcontroller(Item SubmittedItem)
{
DataLayer.Save(SubmittedItem);
}
When I post the following my action method gets an object with Name, Description, and a list of tags:
$.ajax({ type: "POST", dataType: "json", url: $(form).attr('action'), data: $(form).serialize()});
<form method="post" action="/saveitemcontroller">
<input id="Name" name="Name" type="text">
<input id="Description" name="Description" type="text">
<input name="Tag" type="text">
<input name="Tag" type="text">
<input name="Tag" type="text">
<input name="Tag" type="text">
</form>
My question, is there a way to structure the html to include Note objects within the POSTed Item object? Or is the only way to play around with the javascript data object after it gets serialized?
SOLUTION
<input name="Notes[0].Id" type="text">
<input name="Notes[0].NoteText" type="text">
<input name="Notes[0].OtherStuff" type="text">
<input name="Notes[1].Id" type="text">
<input name="Notes[1].NoteText" type="text">
<input name="Notes[1].OtherStuff" type="text">
<input name="Notes[2].Id" type="text">
<input name="Notes[2].NoteText" type="text">
<input name="Notes[2].OtherStuff" type="text">
</form>
NOTE: when javascript is used to add or delete new groupings, it need to make sure the sequence starts at zero and increases +1 without skipping any numbers. An alternative to keeping track of the index numeric sequence is to create a hidden index element that links each grouping together:
<input name="Notes[**anythingstring**].Id" type="text">
<input name="Notes[**anythingstring**].NoteText" type="text">
<input name="Notes[**anythingstring**].OtherStuff" type="text">
<input name="Notes.Index" type="hidden" value="**anythingstring**">