EditorFor collection of items in my model
Asked Answered
M

1

21

My ViewModel has a property that is a collection of another of my model entities, in this case CategoryTags (and each tag has a Tag and an ID).

1) Am I correct in understanding that Html.EditorFor() doesn't have an UI it can create for an ICollection?

2) Assuming #1, I've decided to make an EditorTemplate that is a textbox where my user can key in comma-separated tag names and jquery will autocomplete. Will I have to pass back the list of tag names (or their respective IDs) and then parse them back into the CategoryTags propety on POST?

Thanks!

Mcgaha answered 22/4, 2011 at 15:22 Comment(0)
J
19
  1. Correct - you need your own template (See http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3)
  2. Yes this can work - the model binder will populate properly if they are named the right thing id[0], etc. see Phil Haack's article on this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Edit for #2 - I read your original post a little incorrectly. If you put them all into a single textbox, then you will need to parse them (or create your own model binder). You could have an editor that adds new textboxes to the DOM for each item and then model binder will correctly repopulate the list. However in the case you mentioned, your options are manually do this on the server, or use your own model binder (which would be fairly easy here) to break them apart into a model. Either or : )

Jailhouse answered 22/4, 2011 at 16:34 Comment(4)
Thanks Adam. It sounds like the method you described, adding a new tb to the DOM for each item chosen, is the "right" way to do it. Maybe I'll copy the stackoverflow method where the tags accrue underneath the entry boxMcgaha
Addendum: That post from jarrettmeyer that you linked is really great.Mcgaha
FYI, that first link is broken. Here's Google's Cache: webcache.googleusercontent.com/…Clift
The first link (to jarrettmeyer.com) is working today and it's worth the read and +1 to this answer.Verdieverdigris

© 2022 - 2024 — McMap. All rights reserved.