Is it OK for a Model Binder to do a Repository Lookup?
Asked Answered
C

1

6

I am building an MVC application and am designing a custom model binder for a class; Essentially one of the fields of the model is an object that exists in the database, but it is proving very difficult to associate this with the appropriate objects in HTML. (since a select list will only let me pick an int/string field, I really can't store an 'object' as the 'value' of a Select List).

I was thinking of using the Id stored in a select list to lookup the object in my database in my Model Binder - but a colleague of mine told me this was generally a bad idea. Is this true, and if so, what other options do I have?

Contentious answered 11/11, 2010 at 21:27 Comment(2)
Did your colleague say why it would be a bad idea?Dworman
They said that it was breaking the 'rules' of MVC's 'separation of concerns' ideology.Contentious
P
7

Seems like a subjective question but I think it is acceptable to call the repository in the binder. My backup is the excellent book MVC in Action 2. They have a short section on Model Binders. Below is quote which discusses the idea of calling the database in the binder (emphasis added):

Most of the time, this action parameter is the primary key of the object or another unique identifier, so instead of putting this repeated data access code in all our actions, we can use a custom model binder that can load the stored object before the action is executed. Our action can then take the persisted object type as a parameter instead of the unique identifier.

Which makes sense when if you think that the whole point of the model binder is map your view to the underlying domain model. Their example code demonstrates repository calls in the binder as well.

Peruke answered 11/11, 2010 at 21:49 Comment(3)
Thanks. This helps a bit. I knew how to do it, but knowing that others are practicing it as well makes it a lot easier to justify. My colleague claimed it was 'bad practice' and would make the code harder to maintain (which I didn't quite understand... since it felt like it would make it easier)Contentious
What about dependency injection in your custom model binder? I don't think it's possible, is it?Cryptogenic
you can make a call into the dependencyresolver in mvc3 for thisFireman

© 2022 - 2024 — McMap. All rights reserved.