Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 944
Ciel Avatar asked Nov 11 '10 21:11

Ciel


Video Answer


1 Answers

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.

like image 175
Michael Gattuso Avatar answered Sep 29 '22 20:09

Michael Gattuso