Model binding dynamic collections. V
Adding new entries.
The third (and hopefully last) supported operation is adding some more entries to a list of existing ones.
The experience is as follows:
- a list of things is displayed in the table
- there is a plus button that allows appending new things to the end of the list
- When the list looks as it should, the user can:
- Accept the changes and persist the extended list of things
- Discard the changes and go back to the list of things as of the beginning of the operation
Things that are added are not different from the ones already there, so there is not extra concern (as opposed to the
IClientDeletable when sorting or removing things from the list):
There is nothing special in the display template for
AddableThing. The interesting thing comes from the fact that new row are instances of a client-side template (handlebars can be used for that purpose).
For the default model binder to “detect” those new things, the ids of the controls contained in the rows need to follow the sequence of the list.
So, whenever a new row is about to be added, the last index of the list of things is calculated and passed onto the client side template, in order to perform a value substitution on the ids of the controls for the new row.
That means that specialized
HtmlHelper extension methods are used to render the controls, so that, instead of the index of the element in a collection, an arbitrary client-side placeholder is rendered.
The proverbial “picture worth a thousand words” proves accurate in this instance as well:
And the naming conventions we assume after looking into the generated HTML
The pattern of the controller action is the typical seen before:
Can we add?
All code for additions can be accessed here.