Model binding dynamic collections. II
The second post of the series is a very brief introduction of the foundations of the solution: model binding.
Let me repeat again: model binding is wonderful. And if you are not using it to its full potential, you are running with an iron ball chained to your ankle.
Some useful principles
Embrace view models
Although sometimes one can pass without view models, using the domain/business/data objects (entities from now on) directly in the view, I have found that, most often than not, properties or methods that would not be in the entity are added for the only sake of presentation.
View models take us towards the Thunderdome Principle, a term I first read from Jeremy Miller, that states that controllers take one model as an input, do whatever they need to do (and that is delegating to others) and they return another model. No HTTP, no request or form concerns. I do not want to fight MVC too much, so the principle is loosened up a bit in order to allow the bit of MVC structure that feeds the model into the view.
Although I agree to some extent that view models are structures in the sense that they do not contain any behavior, I sometimes redefine behavior” to not include constructors and/or static factory methods. This redefinition works well to allow simple mappings between entities and models.
Editor Templates rock
They are the mechanism that allows choosing a way to render a bit of specific HTML whenever a given type is displayed in the view.
They are the most elegant way to display elements in a collection too, as they spare the bad memories of .asp pages in which language constructs (such as loops) interleaved with pieces of markup, yielding impossible to understand server pages. Have a collection of complex objects? Create a typed view under the DisplayTemplate (or EditTemplate) and name it after the type that needs to be displayed, add a bit of
@Html.DisplayFor() magic in the view, and enjoy the benefits of a “repeater”.
And decide which one looks better.
A peek at Html
The way HTML is rendered for a collection using the default convention is using indexes in both the id and name of the element, for instance, the second element of a collection of things that is rendered as a hidden input could be:
This sequence allows the default model binder to build an ordered collection (such as an array) back from a list of controls, given that the convention is the one understood by it and noting that gaps in the succession are not allowed.
Displaying a collection of things
The code that displays a collection of things that serves as a baseline to our next adventures can be accessed here. And looks something like: