I have a basic Create / Edit / Delete / Index format created by MVC with my class (ClassA). The class contains a list of objects (ClassB).
When I call the view to edit the object I can edit all the members of ClassA (textfields etc), but how can I edit the list of objects and then still have them returned back to the post action?
When I try and create and iterate through the objects and add them to the form, it is not returned with the object (ClassA) and the list of objects is empty.
Please help. What is the best practice for doing this?
Below is an example
public ActionResult Edit(int id)
{
ClassA objA = db.ClassAs.Single(a => a.id == id);
objA.myListOfBs.Add(new ClassB());
return View(objA);
}
[HttpPost]
public ActionResult Create(ObjectA obj)
{
obj.myListOfBs <--- this is empty! :(
if (ModelState.IsValid)
{
}
return View(obj);
}
Model classes are :
class ClassA {
int id;
List<ClassB> myListOfBs;
}
class ClassB {
int id;
string name;
}
Here is my View
@model MyProject.Models.ClassA
@{
ViewBag.Title = "ClassA Object";
}
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Objects</legend>
@Html.EditorFor(model => model.myListOfBs)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
foreachloop to iterate through the list, and not respecting the mvc model binders naming requirements'