开发者

How to represent many-to-many selection in MVC3 View?

In my model, I have an Product object, I have an Author object and they have a many-to-many relationship, so I have a ProductAuthor object as well.

Functionally, I want a textbox in my view, where the user can enter an author's name, I'll search for it (using Ajax), and display a few results underneath, then the user can click to add one (or more), and the selected ones are displayed next to this search box. Then, when I press Save on my form, everything gets saved (in the controller), not before (so no async AddAuthor method).

Also, if I load up a Product to edit, and it already has authors attached, I want them to be displayed, and the user must be able to unselect them (so when he presses save, they'll no longer be connected.)

How do I represent it in the View? It's ok if I have to write a foreach loop on display, but on submit how will they get sent? Do I generated hidden fields for every selected author? If so, how do I name them, so I can access them in controller? Can they someho开发者_JAVA技巧w be serialized into typed entities, or will I have to look them up in the FormCollection?

Bonus point if I can use the same thing with very little change for a one-to-many relation (when an article can only have one author, but I don't want to use dropdownlist for that, since there can be many authors, and it wouldn't be searchable, and if I write an async FindAuthor for the many-to-many scenario, I'd like to use it in the one-to-many as well).


In case of product edit, there will be multiple authors which you want to select, so you can store in hidden field. Multiple hidden fields are not necessary. just append the author IDs

<input id="authorIDs" type="hidden" value="56,64,33" />

you can use FormCollection or Typed Entity to get this data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜