C# MVC Post back Child Elements In View

More times than not, you will have objects with child objects in your view.  Weather this is an order with lines or a Product with sources, this is the reality.  Most online tutorials of MVC don't cover these well, but I wanted to touch on the two ways to cover these.  

The first way is in my opinion the cleanest and most reusable.  You simple create a view for the child object itself.  Many times you create a Display version and an Edit version then put int he Shared/DisplayTemplates or Shared/EditTemplates directory respectively.  After that, in your parent object's view, you put something like @Html.DisplayFor(model=>Model.ChildObjs) which will render each with the new view in display templates repeating, design your view html accordingly.

The second way is the inline way.  This isn't as pretty, but works.  You simply put a for loop in place to loop through the children elements and use Html.EditorFor(model=>Model.Childs[i].Field to edit fields.  Make sure to put a hidden in for other fields for each child that need to be posted back to make your safe happen.  Also, foreach isn't going to cut it, you need a For loop with an iterator or it won't be able to reflect the fields back.

Hope this helps!

Add comment