0

I know how EditorTemplates work in ASP.NET MVC3. I read a lot and make some research but could not find anything that could help me.

I have a simple model:

public class MyModel
{
     public string Name { get; set; }
     public virtual ICollection<SubModel> SubModels { get; set; }
}

What I would like to do is to be able to add/remove SubModel when I edit MyModel...

Baral
  • 3,103
  • 2
  • 19
  • 28
  • 1
    What do you mean on 'add/remove SubModel'? – Agat Nov 06 '13 at 18:27
  • If you look at the `ICollection` interface you will see that it does not have methods to add or remove items, use `IList` instead. – Davor Zlotrg Nov 06 '13 at 18:37
  • @DZL the [`ICollection`](http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) interface definitely has `Add` and `Remove` methods. It's the [recommended](http://stackoverflow.com/questions/7655845/icollectiont-vs-listt-in-entity-framework) collection type for Entity Framework. – Henk Mollema Nov 06 '13 at 18:59
  • It's not clear to me what your asking. Could you elaborate? Also have you tried anything yourself? We can't help you with questions like this. – Henk Mollema Nov 06 '13 at 19:03
  • @HenkMollema Yes, ICollection has Add and Remove, not ICollection – Davor Zlotrg Nov 06 '13 at 19:03
  • @DZL ah my bad, you're right. Never seen the non-generic `ICollection` hehe. – Henk Mollema Nov 06 '13 at 19:05
  • @HenkMollema, to make things simple : Let's say you have an apple tree (MyModel). You edit the tree. On the same page, you can change it's name and add or remove apples (SubModel) from the tree.... – Baral Nov 06 '13 at 20:15
  • Then why don't you use a generic `ICollection` which makes adding and removing items trivial. – Henk Mollema Nov 06 '13 at 20:52

1 Answers1

0

You may take a look at the following blog post in which Steven Sanderson presents a nice approach to handle this. He also used a custom Html.BeginCollectionItem helper in order to generate non sequential indexes for the corresponding input fields and enable to dynamically add/remove rows.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928