Killnine
Killnine

Reputation: 5900

Adding many instances of EditorTemplate in View

I have a Create View page in my MVC3 project to create instances of a Church model. A Church contains a list of Contact elements that I want users to be able to add with the view.

I have an EditorTemplate working for the Contact type but right now the view only lets a user add one instance. I'd like to create a link that adds the necessary inputs for adding another Contact (I would probably also add Delete functionality, too).

Right now I just have:

<div class="editor-label">
    @Html.LabelFor(model => model.Contacts)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Contacts)
</div>

I saw a website that went over this while it explained EditorTemplates (I think he used phone numbers as an example) but I can't find it anywhere. Your help is greatly appreciated!

Upvotes: 0

Views: 56

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

You should definitely read this blog post. It illustrates how to achieve exactly that. It explains the difficulties that you might encounter when you start implementing this because of the wire format that the default model binder uses when binding collections and the indexes that you need to respect. When working with javascript to add/remove dynamically input fields you need to still respect this format. So the approach taken in this post uses the Non-Sequential Indices convention by encapsulating it into a reusable Html.BeginCollectionItem helper.

This blog post is excellent as it allows you to understand and learn so many things about how the model binder works in ASP.NET MVC and the different conventions it uses to bind to collections. If you understand well this blog post you already know 30% of the ASP.NET MVC framework. There are so many important concepts covered by it.

Upvotes: 1

Related Questions