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?

Ciel
  • 17,312
  • 21
  • 104
  • 199

1 Answers1

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.

Michael Gattuso
  • 13,020
  • 2
  • 25
  • 29
  • 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) – Ciel Nov 11 '10 at 22:13
  • What about dependency injection in your custom model binder? I don't think it's possible, is it? – autonomatt Jul 25 '11 at 15:04
  • you can make a call into the dependencyresolver in mvc3 for this – drogon Feb 13 '12 at 05:26