Stefan Bossbaly
Stefan Bossbaly

Reputation: 6794

ASP MVC way to repopulate dropdown list without requerying database

Problem

I have a list of view models. Most of the view models have a dropdown input. When the ModelState is valid everything goes fine and I am able to handle inputting the data however when an error occurs in the form validation everything goes a mess because the dropdown menus need to be repopulated with data. This is a bit of a problem because each view model has a different dropdown list.

Attempted Solution

I can go thought each view model and get is corresponding domain model from the database but that doesn't seem very efficient (especially since there might be about 30 fields and each one might have a different dropdown list!).

Is there anyway to have the dropdowns persist if the form validation fails?

Upvotes: 2

Views: 599

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

Is there anyway to have the dropdowns persist if the form validation fails?

There's nothing built-in. One possibility is to Cache the results of those database calls to avoid hitting it everytime. So you would simply have methods that either return the lists from the cache, or if not present query the database, store the resulting list to the cache and return the results. Then if a validation error occurs you will invoke those methods to repopulate your dropdownlists. It's simple and effective way, especially for dropdownlists whose values do not change often.

Upvotes: 1

Related Questions