Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a select list from database values?

I was wondering what is the best approach to having a select list on a form which contains values from a database without duplicating any code.

What I thought would make sense would be to load this data in the controller and pass it to a view model, so I can use SelectListFor<> or whatever in order to generate the list. However this means that I have to duplicate all the list loading in both the GET and the POST methods. The other way I can see would be to pass the database context into the view model constructor and have it load the list , but this then presents two more issues:

1) Should the view model know about the database context?

2) I then cannot use model binding by accepting the view model type as a method argument because it does not have a no-argument constructor (if I create a no-argument constructor then it won't have the lists if I want to redisplay the view containing the form).

Is there a better way to do this? This seems like it must be a fairly common scenario and any advice would be appreciated.

like image 628
Tom Haigh Avatar asked Nov 04 '22 19:11

Tom Haigh


1 Answers

We typically implement our lookups through a ReferenceDataRepository that gets used within the controllers in the same way as any other repository interaction. This repository will usually recieve a high number of calls for predominantly static readonly data so we may implement a derived CachedReferenceDataRepository over this using an abstraction of your caching scheme of choice (Session, AppFabric etc).

like image 100
Darren Lewis Avatar answered Nov 09 '22 09:11

Darren Lewis