I've struggled to find any discussion on this.
If you have a simple MVC page for updating a User, and you put a dropdown list on it of Country, you need to populate the dropdown list in the viewmodel. Let's call it List<Country> countries {get; set;}
If the page is posted, and there's an error like they forgot to put a User Name in, we redirect them to the page again to try again, at which point we also have to remember to repopulate the model's List<Country>
before redirecting them back to the page.
Three ways to handle this that I know of:
- In the controller, make a call to the database, e.g.
viewModel.Countries = _dataAccess.GetCountries()
- Store the list in the view bag and not in the model at all e.g.
ViewBag.Countries = _dataAccess.GetCountries()
- Put it into the view model itself, so that
List<Country> {get { return _dataAccess.GetCountries();
and thus inject in aDataAccess
object.
The third approach is what I am considering because then you don't need to worry about populating/repopulating the fields in the controller. But I can't find any evidence via searching that this is an acceptable method, so I fear there is a drawback I am not considering.
The third method also has a big problem in that GetCountries()
is async, and you can't call async methods in properties or even in constructors it seems.