I have a collection of entities, called Accounts. A single user will have multiple Accounts and can set percentages for each Account.
The UI will list all the Accounts, the editable field for each Account is the Percentage property. This will be represented by a textbox.
Once the user makes any adjustments, they will post the form back for processing.
I have used MVC in a few other projects and I understand model binding, but I am not sure how to proceed when dealing with a collection of models.
I am not looking for code or for someone to write out the complete answer for me (although, honestly I wouldn’t complain….). I am looking for guidance in the direction to take.
Thanks in advance.
Two things:
1) You’ll want to use a List/Collection of Account or List/Collection of AccountViewModel in your overarching page view model
So, you would have
You now have a view model that contains a list of accounts.
2)
In your view you have two options.
a) Just create a for loop to spit out the HTML you want for each account (not especially pretty)
b) Create an editor template so you don’t have to do anything special
Your page would then have this.
Here’s how editor templates are set up.
This is from a project I’m working on right now. The take away here should be that you add an “EditorTemplates” folder under the view folder that matches what you’re working on. By convention, MVC will look in this folder for a template when you use EditorFor. Now you just insert whatever HTML you want in that strongly typed template (which would take an Account or AccountViewModel object) and you’d be done. No need for a for loop in your view to spit out HTML for each account.
Really, that would be it at that point. Your post action would model bind to a type of MyPageViewModel which would have the updated data you wanted
Hope that gets you pointed in the right direction.