Model binding dynamic collections. V

 
event

The third (and hopefully last) supported operation is adding some more entries to a list of existing ones.

Adding new entries.

The experience is as follows:

  1. a list of things is displayed in the table
  2. there is a plus button that allows appending new things to the end of the list
  3. 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

The model

Things that are added are not different from the ones already there, so there is not extra concern (as opposed to the IClientSortable or IClientDeletable when sorting or removing things from the list):

The Views

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

Javascript code is provided to instantiate the template passing the last index of the new thing:

The Controller

The pattern of the controller action is the typical seen before:

Can we add?

Fill’em!

DynamicCollections_04

All code for additions can be accessed here.