开发者

Many to Many ASP.NET MVC Binding

If you have scenario of a User that has many Roles and Roles that have many users. Using MVC is there an easy way to bind to the model directly? If your user class has a list of roles and the roles class has a list of user开发者_如何转开发s.

Thank you.


Model binding in MVC is fairly strong. You have to remember that naming conventions are important, especially when you start attempting to bind collections. To bind to a collection, you have to name your form field something to the effect of name="Model.Roles[]" (where Model is User; that would be dependent on your view being strongly typed to your User object; change accordingly). The brackets denote a collection of information being sent back up to the server. If you want to target a specific point in the collection, perhaps targeting a specific property on that point, you might have something like name="Model.Roles[x].Id where x is a valid index in the collection. It takes some effort to ensure you have these correct, and my approach almost always degrades into sending a custom collection of information back to the server and manually creating the relationships in the action method prior to saving the entity in question.

Phil Haack has a post about binding to a collection, albeit from 2008. It's still relevant, however, and might give you more insight into the model binding behavior.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜